Code

Pot and Dutch translation update
[inkscape.git] / src / object-snapper.cpp
1 /**
2  *  \file object-snapper.cpp
3  *  \brief Snapping things to objects.
4  *
5  * Authors:
6  *   Carl Hetherington <inkscape@carlh.net>
7  *   Diederik van Lierop <mail@diedenrezi.nl>
8  *
9  * Copyright (C) 2005 - 2010 Authors
10  *
11  * Released under GNU GPL, read the file 'COPYING' for more information
12  */
14 #include "svg/svg.h"
15 #include <2geom/path-intersection.h>
16 #include <2geom/pathvector.h>
17 #include <2geom/point.h>
18 #include <2geom/rect.h>
19 #include <2geom/line.h>
20 #include <2geom/circle.h>
21 #include "document.h"
22 #include "sp-namedview.h"
23 #include "sp-image.h"
24 #include "sp-item-group.h"
25 #include "sp-item.h"
26 #include "sp-use.h"
27 #include "display/curve.h"
28 #include "inkscape.h"
29 #include "preferences.h"
30 #include "sp-text.h"
31 #include "sp-flowtext.h"
32 #include "text-editing.h"
33 #include "sp-clippath.h"
34 #include "sp-mask.h"
35 #include "helper/geom-curves.h"
36 #include "desktop.h"
38 Inkscape::ObjectSnapper::ObjectSnapper(SnapManager *sm, Geom::Coord const d)
39     : Snapper(sm, d)
40 {
41     _candidates = new std::vector<SnapCandidateItem>;
42     _points_to_snap_to = new std::vector<Inkscape::SnapCandidatePoint>;
43     _paths_to_snap_to = new std::vector<Inkscape::SnapCandidatePath >;
44 }
46 Inkscape::ObjectSnapper::~ObjectSnapper()
47 {
48     _candidates->clear();
49     delete _candidates;
51     _points_to_snap_to->clear();
52     delete _points_to_snap_to;
54     _clear_paths();
55     delete _paths_to_snap_to;
56 }
58 /**
59  *  \return Snap tolerance (desktop coordinates); depends on current zoom so that it's always the same in screen pixels
60  */
61 Geom::Coord Inkscape::ObjectSnapper::getSnapperTolerance() const
62 {
63     SPDesktop const *dt = _snapmanager->getDesktop();
64     double const zoom =  dt ? dt->current_zoom() : 1;
65     return _snapmanager->snapprefs.getObjectTolerance() / zoom;
66 }
68 bool Inkscape::ObjectSnapper::getSnapperAlwaysSnap() const
69 {
70     return _snapmanager->snapprefs.getObjectTolerance() == 10000; //TODO: Replace this threshold of 10000 by a constant; see also tolerance-slider.cpp
71 }
73 /**
74  *  Find all items within snapping range.
75  *  \param parent Pointer to the document's root, or to a clipped path or mask object
76  *  \param it List of items to ignore
77  *  \param bbox_to_snap Bounding box hulling the whole bunch of points, all from the same selection and having the same transformation
78  */
80 void Inkscape::ObjectSnapper::_findCandidates(SPObject* parent,
81                                               std::vector<SPItem const *> const *it,
82                                               bool const &first_point,
83                                               Geom::Rect const &bbox_to_snap,
84                                               bool const clip_or_mask,
85                                               Geom::Matrix const additional_affine) const // transformation of the item being clipped / masked
86 {
87     if (!ThisSnapperMightSnap()) {
88         return;
89     }
91     if (_snapmanager->getDesktop() == NULL) {
92         g_warning("desktop == NULL, so we cannot snap; please inform the developpers of this bug");
93         // Apparently the etup() method from the SnapManager class hasn't been called before trying to snap.
94     }
96     if (first_point) {
97         _candidates->clear();
98     }
100     Geom::Rect bbox_to_snap_incl = bbox_to_snap; // _incl means: will include the snapper tolerance
101     bbox_to_snap_incl.expandBy(getSnapperTolerance()); // see?
103     for (SPObject* o = sp_object_first_child(parent); o != NULL; o = SP_OBJECT_NEXT(o)) {
104         if (SP_IS_ITEM(o) && !(_snapmanager->getDesktop()->itemIsHidden(SP_ITEM(o)) && !clip_or_mask)) {
105             // Snapping to items in a locked layer is allowed
106             // Don't snap to hidden objects, unless they're a clipped path or a mask
107             /* See if this item is on the ignore list */
108             std::vector<SPItem const *>::const_iterator i;
109             if (it != NULL) {
110                 i = it->begin();
111                 while (i != it->end() && *i != o) {
112                     i++;
113                 }
114             }
116             if (it == NULL || i == it->end()) {
117                 SPItem *item = SP_ITEM(o);
118                 if (item) {
119                     SPObject *obj = NULL;
120                     if (!clip_or_mask) { // cannot clip or mask more than once
121                         // The current item is not a clipping path or a mask, but might
122                         // still be the subject of clipping or masking itself ; if so, then
123                         // we should also consider that path or mask for snapping to
124                         obj = SP_OBJECT(item->clip_ref->getObject());
125                         if (obj) {
126                             _findCandidates(obj, it, false, bbox_to_snap, true, sp_item_i2doc_affine(item));
127                         }
128                         obj = SP_OBJECT(item->mask_ref->getObject());
129                         if (obj) {
130                             _findCandidates(obj, it, false, bbox_to_snap, true, sp_item_i2doc_affine(item));
131                         }
132                     }
133                 }
135                 if (SP_IS_GROUP(o)) {
136                     _findCandidates(o, it, false, bbox_to_snap, clip_or_mask, additional_affine);
137                 } else {
138                     Geom::OptRect bbox_of_item = Geom::Rect();
139                     if (clip_or_mask) {
140                         // Oh oh, this will get ugly. We cannot use sp_item_i2d_affine directly because we need to
141                         // insert an additional transformation in document coordinates (code copied from sp_item_i2d_affine)
142                         sp_item_invoke_bbox(item,
143                             bbox_of_item,
144                             sp_item_i2doc_affine(item) * additional_affine * _snapmanager->getDesktop()->doc2dt(),
145                             true);
146                     } else {
147                         sp_item_invoke_bbox(item, bbox_of_item, sp_item_i2d_affine(item), true);
148                     }
149                     if (bbox_of_item) {
150                         // See if the item is within range
151                         if (bbox_to_snap_incl.intersects(*bbox_of_item)
152                                 || (_snapmanager->snapprefs.getIncludeItemCenter() && bbox_to_snap_incl.contains(item->getCenter()))) { // rotation center might be outside of the bounding box
153                             // This item is within snapping range, so record it as a candidate
154                             _candidates->push_back(SnapCandidateItem(item, clip_or_mask, additional_affine));
155                             // For debugging: print the id of the candidate to the console
156                             // SPObject *obj = (SPObject*)item;
157                             // std::cout << "Snap candidate added: " << obj->getId() << std::endl;
158                         }
159                     }
160                 }
161             }
162         }
163     }
167 void Inkscape::ObjectSnapper::_collectNodes(Inkscape::SnapSourceType const &t,
168                                             bool const &first_point) const
170     // Now, let's first collect all points to snap to. If we have a whole bunch of points to snap,
171     // e.g. when translating an item using the selector tool, then we will only do this for the
172     // first point and store the collection for later use. This significantly improves the performance
173     if (first_point) {
174         _points_to_snap_to->clear();
176          // Determine the type of bounding box we should snap to
177         SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
179         bool p_is_a_node = t & Inkscape::SNAPSOURCE_NODE_CATEGORY;
180         bool p_is_a_bbox = t & Inkscape::SNAPSOURCE_BBOX_CATEGORY;
181         bool p_is_other = t & Inkscape::SNAPSOURCE_OTHER_CATEGORY;
183         // A point considered for snapping should be either a node, a bbox corner or a guide. Pick only ONE!
184         g_assert(!((p_is_a_node && p_is_a_bbox) || (p_is_a_bbox && p_is_other) || (p_is_a_node && p_is_other)));
186         if (_snapmanager->snapprefs.getSnapToBBoxNode() || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()) {
187             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
188             bool prefs_bbox = prefs->getBool("/tools/bounding_box");
189             bbox_type = !prefs_bbox ?
190                 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
191         }
193         // Consider the page border for snapping to
194         if (_snapmanager->snapprefs.getSnapToPageBorder()) {
195             _getBorderNodes(_points_to_snap_to);
196         }
198         for (std::vector<SnapCandidateItem>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
199             //Geom::Matrix i2doc(Geom::identity());
200             SPItem *root_item = (*i).item;
201             if (SP_IS_USE((*i).item)) {
202                 root_item = sp_use_root(SP_USE((*i).item));
203             }
204             g_return_if_fail(root_item);
206             //Collect all nodes so we can snap to them
207             if (p_is_a_node || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_node) || p_is_other) {
208                 // Note: there are two ways in which intersections are considered:
209                 // Method 1: Intersections are calculated for each shape individually, for both the
210                 //           snap source and snap target (see sp_shape_snappoints)
211                 // Method 2: Intersections are calculated for each curve or line that we've snapped to, i.e. only for
212                 //           the target (see the intersect() method in the SnappedCurve and SnappedLine classes)
213                 // Some differences:
214                 // - Method 1 doesn't find intersections within a set of multiple objects
215                 // - Method 2 only works for targets
216                 // When considering intersections as snap targets:
217                 // - Method 1 only works when snapping to nodes, whereas
218                 // - Method 2 only works when snapping to paths
219                 // - There will be performance differences too!
220                 // If both methods are being used simultaneously, then this might lead to duplicate targets!
222                 // Well, here we will be looking for snap TARGETS. Both methods can therefore be used.
223                 // When snapping to paths, we will get a collection of snapped lines and snapped curves. findBestSnap() will
224                 // go hunting for intersections (but only when asked to in the prefs of course). In that case we can just
225                 // temporarily block the intersections in sp_item_snappoints, we don't need duplicates. If we're not snapping to
226                 // paths though but only to item nodes then we should still look for the intersections in sp_item_snappoints()
227                 bool old_pref = _snapmanager->snapprefs.getSnapIntersectionCS();
228                 if (_snapmanager->snapprefs.getSnapToItemPath()) {
229                     _snapmanager->snapprefs.setSnapIntersectionCS(false);
230                 }
232                 // We should not snap a transformation center to any of the centers of the items in the
233                 // current selection (see the comment in SelTrans::centerRequest())
234                 bool old_pref2 = _snapmanager->snapprefs.getIncludeItemCenter();
235                 if (old_pref2) {
236                     for ( GSList const *itemlist = _snapmanager->getRotationCenterSource(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
237                         if ((*i).item == reinterpret_cast<SPItem*>(itemlist->data)) {
238                             // don't snap to this item's rotation center
239                             _snapmanager->snapprefs.setIncludeItemCenter(false);
240                             break;
241                         }
242                     }
243                 }
245                 sp_item_snappoints(root_item, *_points_to_snap_to, &_snapmanager->snapprefs);
247                 // restore the original snap preferences
248                 _snapmanager->snapprefs.setSnapIntersectionCS(old_pref);
249                 _snapmanager->snapprefs.setIncludeItemCenter(old_pref2);
250             }
252             //Collect the bounding box's corners so we can snap to them
253             if (p_is_a_bbox || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_bbox) || p_is_other) {
254                 // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
255                 // of the item AND the bbox of the clipping path at the same time
256                 if (!(*i).clip_or_mask) {
257                     Geom::OptRect b = sp_item_bbox_desktop(root_item, bbox_type);
258                     getBBoxPoints(b, _points_to_snap_to, true, _snapmanager->snapprefs.getSnapToBBoxNode(), _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints(), _snapmanager->snapprefs.getSnapBBoxMidpoints());
259                 }
260             }
261         }
262     }
265 void Inkscape::ObjectSnapper::_snapNodes(SnappedConstraints &sc,
266                                          Inkscape::SnapCandidatePoint const &p,
267                                          std::vector<SnapCandidatePoint> *unselected_nodes,
268                                          SnapConstraint const &c,
269                                          Geom::Point const &p_proj_on_constraint) const
271     // Iterate through all nodes, find out which one is the closest to p, and snap to it!
273     _collectNodes(p.getSourceType(), p.getSourceNum() <= 0);
275     if (unselected_nodes != NULL && unselected_nodes->size() > 0) {
276         g_assert(_points_to_snap_to != NULL);
277         _points_to_snap_to->insert(_points_to_snap_to->end(), unselected_nodes->begin(), unselected_nodes->end());
278     }
280     SnappedPoint s;
281     bool success = false;
283     for (std::vector<SnapCandidatePoint>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
284         Geom::Point target_pt = (*k).getPoint();
285         Geom::Coord dist = NR_HUGE;
286         if (!c.isUndefined()) {
287             // We're snapping to nodes along a constraint only, so find out if this node
288             // is at the constraint, while allowing for a small margin
289             if (Geom::L2(target_pt - c.projection(target_pt)) > 1e-9) {
290                 // The distance from the target point to its projection on the constraint
291                 // is too large, so this point is not on the constraint. Skip it!
292                 continue;
293             }
294             dist = Geom::L2(target_pt - p_proj_on_constraint);
295         } else {
296             // Free (unconstrained) snapping
297             dist = Geom::L2(target_pt - p.getPoint());
298         }
300         if (dist < getSnapperTolerance() && dist < s.getSnapDistance()) {
301             s = SnappedPoint(target_pt, p.getSourceType(), p.getSourceNum(), (*k).getTargetType(), dist, getSnapperTolerance(), getSnapperAlwaysSnap(), false, true, (*k).getTargetBBox());
302             success = true;
303         }
304     }
306     if (success) {
307         sc.points.push_back(s);
308     }
311 void Inkscape::ObjectSnapper::_snapTranslatingGuide(SnappedConstraints &sc,
312                                          Geom::Point const &p,
313                                          Geom::Point const &guide_normal) const
315     // Iterate through all nodes, find out which one is the closest to this guide, and snap to it!
316     _collectNodes(SNAPSOURCE_GUIDE, true);
318     if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
319         _collectPaths(p, SNAPSOURCE_GUIDE, true);
320         _snapPaths(sc, Inkscape::SnapCandidatePoint(p, SNAPSOURCE_GUIDE), NULL, NULL);
321     }
323     SnappedPoint s;
325     Geom::Coord tol = getSnapperTolerance();
327     for (std::vector<SnapCandidatePoint>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
328         Geom::Point target_pt = (*k).getPoint();
329         // Project each node (*k) on the guide line (running through point p)
330         Geom::Point p_proj = Geom::projection(target_pt, Geom::Line(p, p + Geom::rot90(guide_normal)));
331         Geom::Coord dist = Geom::L2(target_pt - p_proj); // distance from node to the guide
332         Geom::Coord dist2 = Geom::L2(p - p_proj); // distance from projection of node on the guide, to the mouse location
333         if ((dist < tol && dist2 < tol) || getSnapperAlwaysSnap()) {
334             s = SnappedPoint(target_pt, SNAPSOURCE_GUIDE, 0, (*k).getTargetType(), dist, tol, getSnapperAlwaysSnap(), false, true, (*k).getTargetBBox());
335             sc.points.push_back(s);
336         }
337     }
341 /**
342  * Returns index of first NR_END bpath in array.
343  */
345 void Inkscape::ObjectSnapper::_collectPaths(Geom::Point p,
346                                          Inkscape::SnapSourceType const source_type,
347                                          bool const &first_point) const
349     // Now, let's first collect all paths to snap to. If we have a whole bunch of points to snap,
350     // e.g. when translating an item using the selector tool, then we will only do this for the
351     // first point and store the collection for later use. This significantly improves the performance
352     if (first_point) {
353         _clear_paths();
355         // Determine the type of bounding box we should snap to
356         SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
358         bool p_is_a_node = source_type & Inkscape::SNAPSOURCE_NODE_CATEGORY;
359         bool p_is_other = source_type & Inkscape::SNAPSOURCE_OTHER_CATEGORY;
361         if (_snapmanager->snapprefs.getSnapToBBoxPath()) {
362             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
363             int prefs_bbox = prefs->getBool("/tools/bounding_box", 0);
364             bbox_type = !prefs_bbox ?
365                 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
366         }
368         // Consider the page border for snapping
369         if (_snapmanager->snapprefs.getSnapToPageBorder() && _snapmanager->snapprefs.getSnapModeBBoxOrNodes()) {
370             Geom::PathVector *border_path = _getBorderPathv();
371             if (border_path != NULL) {
372                 _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(border_path, SNAPTARGET_PAGE_BORDER, Geom::OptRect()));
373             }
374         }
376         for (std::vector<SnapCandidateItem>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
378             /* Transform the requested snap point to this item's coordinates */
379             Geom::Matrix i2doc(Geom::identity());
380             SPItem *root_item = NULL;
381             /* We might have a clone at hand, so make sure we get the root item */
382             if (SP_IS_USE((*i).item)) {
383                 i2doc = sp_use_get_root_transform(SP_USE((*i).item));
384                 root_item = sp_use_root(SP_USE((*i).item));
385                 g_return_if_fail(root_item);
386             } else {
387                 i2doc = sp_item_i2doc_affine((*i).item);
388                 root_item = (*i).item;
389             }
391             //Build a list of all paths considered for snapping to
393             //Add the item's path to snap to
394             if (_snapmanager->snapprefs.getSnapToItemPath() && _snapmanager->snapprefs.getSnapModeNode()) {
395                 if (p_is_other || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_node)) {
396                     // Snapping to the path of characters is very cool, but for a large
397                     // chunk of text this will take ages! So limit snapping to text paths
398                     // containing max. 240 characters. Snapping the bbox will not be affected
399                     bool very_lenghty_prose = false;
400                     if (SP_IS_TEXT(root_item) || SP_IS_FLOWTEXT(root_item)) {
401                         very_lenghty_prose =  sp_text_get_length(SP_TEXT(root_item)) > 240;
402                     }
403                     // On my AMD 3000+, the snapping lag becomes annoying at approx. 240 chars
404                     // which corresponds to a lag of 500 msec. This is for snapping a rect
405                     // to a single line of text.
407                     // Snapping for example to a traced bitmap is also very stressing for
408                     // the CPU, so we'll only snap to paths having no more than 500 nodes
409                     // This also leads to a lag of approx. 500 msec (in my lousy test set-up).
410                     bool very_complex_path = false;
411                     if (SP_IS_PATH(root_item)) {
412                         very_complex_path = sp_nodes_in_path(SP_PATH(root_item)) > 500;
413                     }
415                     if (!very_lenghty_prose && !very_complex_path) {
416                         SPCurve *curve = curve_for_item(root_item);
417                         if (curve) {
418                             // We will get our own copy of the pathvector, which must be freed at some point
420                             // Geom::PathVector *pv = pathvector_for_curve(root_item, curve, true, true, Geom::identity(), (*i).additional_affine);
422                             Geom::PathVector *pv = new Geom::PathVector(curve->get_pathvector());
423                             (*pv) *= sp_item_i2d_affine(root_item) * (*i).additional_affine * _snapmanager->getDesktop()->doc2dt(); // (_edit_transform * _i2d_transform);
425                             _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(pv, SNAPTARGET_PATH, Geom::OptRect())); // Perhaps for speed, get a reference to the Geom::pathvector, and store the transformation besides it.
426                             curve->unref();
427                         }
428                     }
429                 }
430             }
432             //Add the item's bounding box to snap to
433             if (_snapmanager->snapprefs.getSnapToBBoxPath() && _snapmanager->snapprefs.getSnapModeBBox()) {
434                 if (p_is_other || !(_snapmanager->snapprefs.getStrictSnapping() && p_is_a_node)) {
435                     // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
436                     // of the item AND the bbox of the clipping path at the same time
437                     if (!(*i).clip_or_mask) {
438                         Geom::OptRect rect;
439                         sp_item_invoke_bbox(root_item, rect, i2doc, TRUE, bbox_type);
440                         if (rect) {
441                             Geom::PathVector *path = _getPathvFromRect(*rect);
442                             rect = sp_item_bbox_desktop(root_item, bbox_type);
443                             _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(path, SNAPTARGET_BBOX_EDGE, rect));
444                         }
445                     }
446                 }
447             }
448         }
449     }
452 void Inkscape::ObjectSnapper::_snapPaths(SnappedConstraints &sc,
453                                      Inkscape::SnapCandidatePoint const &p,
454                                      std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes,
455                                      SPPath const *selected_path) const
457     _collectPaths(p.getPoint(), p.getSourceType(), p.getSourceNum() <= 0);
458     // Now we can finally do the real snapping, using the paths collected above
460     g_assert(_snapmanager->getDesktop() != NULL);
461     Geom::Point const p_doc = _snapmanager->getDesktop()->dt2doc(p.getPoint());
463     bool const node_tool_active = _snapmanager->snapprefs.getSnapToItemPath() && selected_path != NULL;
465     if (p.getSourceNum() <= 0) {
466         /* findCandidates() is used for snapping to both paths and nodes. It ignores the path that is
467          * currently being edited, because that path requires special care: when snapping to nodes
468          * only the unselected nodes of that path should be considered, and these will be passed on separately.
469          * This path must not be ignored however when snapping to the paths, so we add it here
470          * manually when applicable.
471          * */
472         if (node_tool_active) {
473             SPCurve *curve = curve_for_item(SP_ITEM(selected_path));
474             if (curve) {
475                 Geom::PathVector *pathv = pathvector_for_curve(SP_ITEM(selected_path), curve, true, true, Geom::identity(), Geom::identity()); // We will get our own copy of the path, which must be freed at some point
476                 _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(pathv, SNAPTARGET_PATH, Geom::OptRect(), true));
477                 curve->unref();
478             }
479         }
480     }
482     int num_path = 0;
483     int num_segm = 0;
485     for (std::vector<Inkscape::SnapCandidatePath >::const_iterator it_p = _paths_to_snap_to->begin(); it_p != _paths_to_snap_to->end(); it_p++) {
486         bool const being_edited = node_tool_active && (*it_p).currently_being_edited;
487         //if true then this pathvector it_pv is currently being edited in the node tool
489         for(Geom::PathVector::iterator it_pv = (it_p->path_vector)->begin(); it_pv != (it_p->path_vector)->end(); ++it_pv) {
490             // Find a nearest point for each curve within this path
491             // n curves will return n time values with 0 <= t <= 1
492             std::vector<double> anp = (*it_pv).nearestPointPerCurve(p_doc);
494             std::vector<double>::const_iterator np = anp.begin();
495             unsigned int index = 0;
496             for (; np != anp.end(); np++, index++) {
497                 Geom::Curve const *curve = &((*it_pv).at_index(index));
498                 Geom::Point const sp_doc = curve->pointAt(*np);
500                 bool c1 = true;
501                 bool c2 = true;
502                 if (being_edited) {
503                     /* If the path is being edited, then we should only snap though to stationary pieces of the path
504                      * and not to the pieces that are being dragged around. This way we avoid
505                      * self-snapping. For this we check whether the nodes at both ends of the current
506                      * piece are unselected; if they are then this piece must be stationary
507                      */
508                     g_assert(unselected_nodes != NULL);
509                     Geom::Point start_pt = _snapmanager->getDesktop()->doc2dt(curve->pointAt(0));
510                     Geom::Point end_pt = _snapmanager->getDesktop()->doc2dt(curve->pointAt(1));
511                     c1 = isUnselectedNode(start_pt, unselected_nodes);
512                     c2 = isUnselectedNode(end_pt, unselected_nodes);
513                     /* Unfortunately, this might yield false positives for coincident nodes. Inkscape might therefore mistakenly
514                      * snap to path segments that are not stationary. There are at least two possible ways to overcome this:
515                      * - Linking the individual nodes of the SPPath we have here, to the nodes of the NodePath::SubPath class as being
516                      *   used in sp_nodepath_selected_nodes_move. This class has a member variable called "selected". For this the nodes
517                      *   should be in the exact same order for both classes, so we can index them
518                      * - Replacing the SPPath being used here by the the NodePath::SubPath class; but how?
519                      */
520                 }
522                 Geom::Point const sp_dt = _snapmanager->getDesktop()->doc2dt(sp_doc);
523                 if (!being_edited || (c1 && c2)) {
524                     Geom::Coord const dist = Geom::distance(sp_doc, p_doc);
525                     if (dist < getSnapperTolerance()) {
526                         sc.curves.push_back(Inkscape::SnappedCurve(sp_dt, num_path, num_segm, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), false, curve, p.getSourceType(), p.getSourceNum(), it_p->target_type, it_p->target_bbox));
527                     }
528                 }
529             }
530             num_segm++;
531         } // End of: for (Geom::PathVector::iterator ....)
532         num_path++;
533     }
536 /* Returns true if point is coincident with one of the unselected nodes */
537 bool Inkscape::ObjectSnapper::isUnselectedNode(Geom::Point const &point, std::vector<Inkscape::SnapCandidatePoint> const *unselected_nodes) const
539     if (unselected_nodes == NULL) {
540         return false;
541     }
543     if (unselected_nodes->size() == 0) {
544         return false;
545     }
547     for (std::vector<Inkscape::SnapCandidatePoint>::const_iterator i = unselected_nodes->begin(); i != unselected_nodes->end(); i++) {
548         if (Geom::L2(point - (*i).getPoint()) < 1e-4) {
549             return true;
550         }
551     }
553     return false;
556 void Inkscape::ObjectSnapper::_snapPathsConstrained(SnappedConstraints &sc,
557                                      Inkscape::SnapCandidatePoint const &p,
558                                      SnapConstraint const &c,
559                                      Geom::Point const &p_proj_on_constraint) const
562     _collectPaths(p_proj_on_constraint, p.getSourceType(), p.getSourceNum() <= 0);
564     // Now we can finally do the real snapping, using the paths collected above
566     g_assert(_snapmanager->getDesktop() != NULL);
567     Geom::Point const p_doc = _snapmanager->getDesktop()->dt2doc(p_proj_on_constraint);
569     Geom::Point direction_vector = c.getDirection();
570     if (!is_zero(direction_vector)) {
571         direction_vector = Geom::unit_vector(direction_vector);
572     }
574     // The intersection point of the constraint line with any path, must lie within two points on the
575     // SnapConstraint: p_min_on_cl and p_max_on_cl. The distance between those points is twice the snapping tolerance
576     Geom::Point const p_min_on_cl = _snapmanager->getDesktop()->dt2doc(p_proj_on_constraint - getSnapperTolerance() * direction_vector);
577     Geom::Point const p_max_on_cl = _snapmanager->getDesktop()->dt2doc(p_proj_on_constraint + getSnapperTolerance() * direction_vector);
578     Geom::Coord tolerance = getSnapperTolerance();
580     // PS: Because the paths we're about to snap to are all expressed relative to document coordinate system, we will have
581     // to convert the snapper coordinates from the desktop coordinates to document coordinates
583     std::vector<Geom::Path> constraint_path;
584     if (c.isCircular()) {
585         Geom::Circle constraint_circle(_snapmanager->getDesktop()->dt2doc(c.getPoint()), c.getRadius());
586         constraint_circle.getPath(constraint_path);
587     } else {
588         Geom::Path constraint_line;
589         constraint_line.start(p_min_on_cl);
590         constraint_line.appendNew<Geom::LineSegment>(p_max_on_cl);
591         constraint_path.push_back(constraint_line);
592     }
593     // Length of constraint_path will always be one
595     // Find all intersections of the constrained path with the snap target candidates
596     std::vector<Geom::Point> intersections;
597     for (std::vector<Inkscape::SnapCandidatePath >::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
598         if (k->path_vector) {
599             // Do the intersection math
600             Geom::CrossingSet cs = Geom::crossings(constraint_path, *(k->path_vector));
601             // Store the results as intersection points
602             unsigned int index = 0;
603             for (Geom::CrossingSet::const_iterator i = cs.begin(); i != cs.end(); i++) {
604                 if (index >= constraint_path.size()) {
605                     break;
606                 }
607                 // Reconstruct and store the points of intersection
608                 for (Geom::Crossings::const_iterator m = (*i).begin(); m != (*i).end(); m++) {
609                     intersections.push_back(constraint_path[index].pointAt((*m).ta));
610                 }
611                 index++;
612             }
614             //Geom::crossings will not consider the closing segment apparently, so we'll handle that separately here
615             //TODO: This should have been fixed in rev. #9859, which makes this workaround obsolete
616             for(Geom::PathVector::iterator it_pv = k->path_vector->begin(); it_pv != k->path_vector->end(); ++it_pv) {
617                 if (it_pv->closed()) {
618                     // Get the closing linesegment and convert it to a path
619                     Geom::Path cls;
620                     cls.close(false);
621                     cls.append(it_pv->back_closed());
622                     // Intersect that closing path with the constrained path
623                     Geom::Crossings cs = Geom::crossings(constraint_path.front(), cls);
624                     // Reconstruct and store the points of intersection
625                     index = 0; // assuming the constraint path vector has only one path
626                     for (Geom::Crossings::const_iterator m = cs.begin(); m != cs.end(); m++) {
627                         intersections.push_back(constraint_path[index].pointAt((*m).ta));
628                     }
629                 }
630             }
632             // Convert the collected points of intersection to snapped points
633             for (std::vector<Geom::Point>::iterator p_inters = intersections.begin(); p_inters != intersections.end(); p_inters++) {
634                 // Convert to desktop coordinates
635                 (*p_inters) = _snapmanager->getDesktop()->doc2dt(*p_inters);
636                 // Construct a snapped point
637                 Geom::Coord dist = Geom::L2(p.getPoint() - *p_inters);
638                 SnappedPoint s = SnappedPoint(*p_inters, p.getSourceType(), p.getSourceNum(), k->target_type, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), true, k->target_bbox);;
639                 // Store the snapped point
640                 if (dist <= tolerance) { // If the intersection is within snapping range, then we might snap to it
641                     sc.points.push_back(s);
642                 }
643             }
644         }
645     }
649 void Inkscape::ObjectSnapper::freeSnap(SnappedConstraints &sc,
650                                             Inkscape::SnapCandidatePoint const &p,
651                                             Geom::OptRect const &bbox_to_snap,
652                                             std::vector<SPItem const *> const *it,
653                                             std::vector<SnapCandidatePoint> *unselected_nodes) const
655     if (_snap_enabled == false || _snapmanager->snapprefs.getSnapFrom(p.getSourceType()) == false ) {
656         return;
657     }
659     /* Get a list of all the SPItems that we will try to snap to */
660     if (p.getSourceNum() <= 0) {
661         Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p.getPoint(), p.getPoint());
662         _findCandidates(sp_document_root(_snapmanager->getDocument()), it, p.getSourceNum() <= 0, local_bbox_to_snap, false, Geom::identity());
663     }
665     // TODO: Argh, UGLY! Get rid of this here, move this logic to the snap manager
666     bool snap_nodes = (_snapmanager->snapprefs.getSnapModeNode() && (
667                             _snapmanager->snapprefs.getSnapToItemNode() ||
668                             _snapmanager->snapprefs.getSnapSmoothNodes() ||
669                             _snapmanager->snapprefs.getSnapLineMidpoints() ||
670                             _snapmanager->snapprefs.getSnapObjectMidpoints()
671                         )) || (_snapmanager->snapprefs.getSnapModeBBox() && (
672                             _snapmanager->snapprefs.getSnapToBBoxNode() ||
673                             _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() ||
674                             _snapmanager->snapprefs.getSnapBBoxMidpoints()
675                         )) || (_snapmanager->snapprefs.getSnapModeBBoxOrNodes() && (
676                             _snapmanager->snapprefs.getIncludeItemCenter() ||
677                             _snapmanager->snapprefs.getSnapToPageBorder()
678                         ));
680     if (snap_nodes) {
681         _snapNodes(sc, p, unselected_nodes);
682     }
684     if ((_snapmanager->snapprefs.getSnapModeNode() && _snapmanager->snapprefs.getSnapToItemPath()) ||
685         (_snapmanager->snapprefs.getSnapModeBBox() && _snapmanager->snapprefs.getSnapToBBoxPath()) ||
686         (_snapmanager->snapprefs.getSnapModeBBoxOrNodes() && _snapmanager->snapprefs.getSnapToPageBorder())) {
687         unsigned n = (unselected_nodes == NULL) ? 0 : unselected_nodes->size();
688         if (n > 0) {
689             /* While editing a path in the node tool, findCandidates must ignore that path because
690              * of the node snapping requirements (i.e. only unselected nodes must be snapable).
691              * That path must not be ignored however when snapping to the paths, so we add it here
692              * manually when applicable
693              */
694             SPPath *path = NULL;
695             if (it != NULL) {
696                 if (it->size() == 1 && SP_IS_PATH(*it->begin())) {
697                     path = SP_PATH(*it->begin());
698                 } // else: *it->begin() might be a SPGroup, e.g. when editing a LPE of text that has been converted to a group of paths
699                 // as reported in bug #356743. In that case we can just ignore it, i.e. not snap to this item
700             }
701             _snapPaths(sc, p, unselected_nodes, path);
702         } else {
703             _snapPaths(sc, p, NULL, NULL);
704         }
705     }
708 void Inkscape::ObjectSnapper::constrainedSnap( SnappedConstraints &sc,
709                                                   Inkscape::SnapCandidatePoint const &p,
710                                                   Geom::OptRect const &bbox_to_snap,
711                                                   SnapConstraint const &c,
712                                                   std::vector<SPItem const *> const *it,
713                                                   std::vector<SnapCandidatePoint> *unselected_nodes) const
715     if (_snap_enabled == false || _snapmanager->snapprefs.getSnapFrom(p.getSourceType()) == false) {
716         return;
717     }
719     // project the mouse pointer onto the constraint. Only the projected point will be considered for snapping
720     Geom::Point pp = c.projection(p.getPoint());
722     /* Get a list of all the SPItems that we will try to snap to */
723     if (p.getSourceNum() <= 0) {
724         Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(pp, pp);
725         _findCandidates(sp_document_root(_snapmanager->getDocument()), it, p.getSourceNum() <= 0, local_bbox_to_snap, false, Geom::identity());
726     }
728     // A constrained snap, is a snap in only one degree of freedom (specified by the constraint line).
729     // This is useful for example when scaling an object while maintaining a fixed aspect ratio. It's
730     // nodes are only allowed to move in one direction (i.e. in one degree of freedom).
732     // TODO: Argh, UGLY! Get rid of this here, move this logic to the snap manager
733     bool snap_nodes = (_snapmanager->snapprefs.getSnapModeNode() && (
734                                 _snapmanager->snapprefs.getSnapToItemNode() ||
735                                 _snapmanager->snapprefs.getSnapSmoothNodes() ||
736                                 _snapmanager->snapprefs.getSnapLineMidpoints() ||
737                                 _snapmanager->snapprefs.getSnapObjectMidpoints()
738                             )) || (_snapmanager->snapprefs.getSnapModeBBox() && (
739                                 _snapmanager->snapprefs.getSnapToBBoxNode() ||
740                                 _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() ||
741                                 _snapmanager->snapprefs.getSnapBBoxMidpoints()
742                             )) || (_snapmanager->snapprefs.getSnapModeBBoxOrNodes() && (
743                                 _snapmanager->snapprefs.getIncludeItemCenter() ||
744                                 _snapmanager->snapprefs.getSnapToPageBorder()
745                             ));
747     if (snap_nodes) {
748         _snapNodes(sc, p, unselected_nodes, c, pp);
749     }
751     if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
752         _snapPathsConstrained(sc, p, c, pp);
753     }
757 // This method is used to snap a guide to nodes, while dragging the guide around
758 void Inkscape::ObjectSnapper::guideFreeSnap(SnappedConstraints &sc,
759                                         Geom::Point const &p,
760                                         Geom::Point const &guide_normal) const
762     /* Get a list of all the SPItems that we will try to snap to */
763     std::vector<SPItem*> cand;
764     std::vector<SPItem const *> const it; //just an empty list
766     _findCandidates(sp_document_root(_snapmanager->getDocument()), &it, true, Geom::Rect(p, p), false, Geom::identity());
767     _snapTranslatingGuide(sc, p, guide_normal);
771 // This method is used to snap the origin of a guide to nodes/paths, while dragging the origin along the guide
772 void Inkscape::ObjectSnapper::guideConstrainedSnap(SnappedConstraints &sc,
773                                         Geom::Point const &p,
774                                         Geom::Point const &guide_normal,
775                                         SnapConstraint const &/*c*/) const
777     /* Get a list of all the SPItems that we will try to snap to */
778     std::vector<SPItem*> cand;
779     std::vector<SPItem const *> const it; //just an empty list
781     _findCandidates(sp_document_root(_snapmanager->getDocument()), &it, true, Geom::Rect(p, p), false, Geom::identity());
782     _snapTranslatingGuide(sc, p, guide_normal);
786 /**
787  *  \return true if this Snapper will snap at least one kind of point.
788  */
789 bool Inkscape::ObjectSnapper::ThisSnapperMightSnap() const
791     bool snap_to_something = (_snapmanager->snapprefs.getSnapModeNode() && (
792                                 _snapmanager->snapprefs.getSnapToItemPath() ||
793                                 _snapmanager->snapprefs.getSnapToItemNode() ||
794                                 _snapmanager->snapprefs.getSnapSmoothNodes() ||
795                                 _snapmanager->snapprefs.getSnapLineMidpoints() ||
796                                 _snapmanager->snapprefs.getSnapObjectMidpoints()
797                             )) || (_snapmanager->snapprefs.getSnapModeBBox() && (
798                                 _snapmanager->snapprefs.getSnapToBBoxPath() ||
799                                 _snapmanager->snapprefs.getSnapToBBoxNode() ||
800                                 _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() ||
801                                 _snapmanager->snapprefs.getSnapBBoxMidpoints()
802                             )) || (_snapmanager->snapprefs.getSnapModeBBoxOrNodes() && (
803                                 _snapmanager->snapprefs.getSnapToPageBorder() ||
804                                 _snapmanager->snapprefs.getIncludeItemCenter()
805                             ));
807     return (_snap_enabled && snap_to_something);
810 void Inkscape::ObjectSnapper::_clear_paths() const
812     for (std::vector<Inkscape::SnapCandidatePath >::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
813         delete k->path_vector;
814     }
815     _paths_to_snap_to->clear();
818 Geom::PathVector* Inkscape::ObjectSnapper::_getBorderPathv() const
820     Geom::Rect const border_rect = Geom::Rect(Geom::Point(0,0), Geom::Point(sp_document_width(_snapmanager->getDocument()),sp_document_height(_snapmanager->getDocument())));
821     return _getPathvFromRect(border_rect);
824 Geom::PathVector* Inkscape::ObjectSnapper::_getPathvFromRect(Geom::Rect const rect) const
826     SPCurve const *border_curve = SPCurve::new_from_rect(rect, true);
827     if (border_curve) {
828         Geom::PathVector *dummy = new Geom::PathVector(border_curve->get_pathvector());
829         return dummy;
830     } else {
831         return NULL;
832     }
835 void Inkscape::ObjectSnapper::_getBorderNodes(std::vector<SnapCandidatePoint> *points) const
837     Geom::Coord w = sp_document_width(_snapmanager->getDocument());
838     Geom::Coord h = sp_document_height(_snapmanager->getDocument());
839     points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(0,0), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
840     points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(0,h), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
841     points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(w,h), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
842     points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(w,0), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
845 void Inkscape::getBBoxPoints(Geom::OptRect const bbox,
846                              std::vector<SnapCandidatePoint> *points,
847                              bool const /*isTarget*/,
848                              bool const includeCorners,
849                              bool const includeLineMidpoints,
850                              bool const includeObjectMidpoints)
852     if (bbox) {
853         // collect the corners of the bounding box
854         for ( unsigned k = 0 ; k < 4 ; k++ ) {
855             if (includeCorners) {
856                 points->push_back(Inkscape::SnapCandidatePoint(bbox->corner(k), Inkscape::SNAPSOURCE_BBOX_CORNER, -1, Inkscape::SNAPTARGET_BBOX_CORNER, *bbox));
857             }
858             // optionally, collect the midpoints of the bounding box's edges too
859             if (includeLineMidpoints) {
860                 points->push_back(Inkscape::SnapCandidatePoint((bbox->corner(k) + bbox->corner((k+1) % 4))/2, Inkscape::SNAPSOURCE_BBOX_EDGE_MIDPOINT, -1, Inkscape::SNAPTARGET_BBOX_EDGE_MIDPOINT, *bbox));
861             }
862         }
863         if (includeObjectMidpoints) {
864             points->push_back(Inkscape::SnapCandidatePoint(bbox->midpoint(), Inkscape::SNAPSOURCE_BBOX_MIDPOINT, -1, Inkscape::SNAPTARGET_BBOX_MIDPOINT, *bbox));
865         }
866     }
869 /*
870   Local Variables:
871   mode:c++
872   c-file-style:"stroustrup"
873   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
874   indent-tabs-mode:nil
875   fill-column:99
876   End:
877 */
878 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :