Code

Fix regression in snapping to paths (which caused self-snapping)
[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 - 2008 Authors
10  *
11  * Released under GNU GPL, read the file 'COPYING' for more information
12  */
14 #include "svg/svg.h"
15 #include "libnr/nr-path.h"
16 #include "libnr/nr-rect-ops.h"
17 #include "libnr/nr-point-fns.h"
18 #include <2geom/path-intersection.h>
19 #include <2geom/point.h>
20 #include <2geom/rect.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 "desktop.h"
29 #include "inkscape.h"
30 #include "prefs-utils.h"
31 #include "sp-text.h"
32 #include "sp-flowtext.h"
33 #include "text-editing.h"
34 #include "sp-clippath.h"
35 #include "sp-mask.h"
36 #include "helper/geom-curves.h"
38 Inkscape::SnapCandidate::SnapCandidate(SPItem* item, bool clip_or_mask, Geom::Matrix additional_affine)
39     : item(item), clip_or_mask(clip_or_mask), additional_affine(additional_affine)
40 {    
41 }
43 Inkscape::SnapCandidate::~SnapCandidate()
44 {    
45 }
47 Inkscape::ObjectSnapper::ObjectSnapper(SPNamedView const *nv, Geom::Coord const d)
48     : Snapper(nv, d), _snap_to_itemnode(true), _snap_to_itempath(true),
49       _snap_to_bboxnode(true), _snap_to_bboxpath(true), _snap_to_page_border(false),
50       _strict_snapping(true), _include_item_center(false)
51 {
52     _candidates = new std::vector<SnapCandidate>;
53     _points_to_snap_to = new std::vector<Geom::Point>;
54     _paths_to_snap_to = new std::vector<Geom::PathVector*>;
55 }
57 Inkscape::ObjectSnapper::~ObjectSnapper()
58 {
59     _candidates->clear();
60     delete _candidates;
62     _points_to_snap_to->clear();
63     delete _points_to_snap_to;
65     _clear_paths();
66     delete _paths_to_snap_to;
67 }
69 /**
70  *  Find all items within snapping range.
71  *  \param parent Pointer to the document's root, or to a clipped path or mask object
72  *  \param it List of items to ignore
73  *  \param first_point If true then this point is the first one from a whole bunch of points
74  *  \param bbox_to_snap Bounding box hulling the whole bunch of points, all from the same selection and having the same transformation
75  *  \param DimensionToSnap Snap in X, Y, or both directions.
76  */
78 void Inkscape::ObjectSnapper::_findCandidates(SPObject* parent,
79                                               std::vector<SPItem const *> const *it,
80                                               bool const &first_point,
81                                               Geom::Rect const &bbox_to_snap,
82                                               DimensionToSnap const snap_dim,
83                                               bool const clip_or_mask,
84                                               Geom::Matrix const additional_affine) const // transformation of the item being clipped / masked
85 {
86     bool const c1 = (snap_dim == TRANSL_SNAP_XY) && ThisSnapperMightSnap();
87     bool const c2 = (snap_dim != TRANSL_SNAP_XY) && GuidesMightSnap();
88     
89     if (!(c1 || c2)) {
90         return;        
91     }
92     
93     SPDesktop const *desktop = SP_ACTIVE_DESKTOP;
95     if (first_point) {
96         _candidates->clear();
97     }
98     
99     Geom::Rect bbox_to_snap_incl = bbox_to_snap; // _incl means: will include the snapper tolerance
100     bbox_to_snap_incl.expandBy(getSnapperTolerance()); // see?
101     
102     for (SPObject* o = sp_object_first_child(parent); o != NULL; o = SP_OBJECT_NEXT(o)) {
103         if (SP_IS_ITEM(o) && !SP_ITEM(o)->isLocked() && !(desktop->itemIsHidden(SP_ITEM(o)) && !clip_or_mask)) {
104             // Don't snap to locked items, and
105             // don't snap to hidden objects, unless they're a clipped path or a mask
106             /* See if this item is on the ignore list */
107             std::vector<SPItem const *>::const_iterator i;
108             if (it != NULL) {
109                 i = it->begin();
110                 while (i != it->end() && *i != o) {
111                     i++;
112                 }
113             }
114             
115             if (it == NULL || i == it->end()) {
116                 SPItem *item = SP_ITEM(o); 
117                 Geom::Matrix transform = Geom::identity();
118                 if (item) {
119                     SPObject *obj = NULL;
120                     if (clip_or_mask) { // If the current item is a clipping path or a mask
121                         // then store the transformation of the clipped path or mask itself
122                         // but also take into account the additional affine of the object 
123                         // being clipped / masked
124                         transform = to_2geom(item->transform) * additional_affine;
125                     } else { // cannot clip or mask more than once                     
126                         // The current item is not a clipping path or a mask, but might
127                         // still be the subject of clipping or masking itself ; if so, then
128                         // we should also consider that path or mask for snapping to
129                         obj = SP_OBJECT(item->clip_ref->getObject());
130                         if (obj) {
131                             _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, item->transform);
132                         } 
133                         obj = SP_OBJECT(item->mask_ref->getObject());
134                         if (obj) {
135                             _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, item->transform);
136                         }
137                     }
138                 }            
139                 
140                 if (SP_IS_GROUP(o)) {
141                     _findCandidates(o, it, false, bbox_to_snap, snap_dim, false, Geom::identity());
142                 } else {
143                     boost::optional<NR::Rect> bbox_of_item = NR::Rect();
144                     if (clip_or_mask) {
145                         // Oh oh, this will get ugly. We cannot use sp_item_i2d_affine directly because we need to
146                         // insert an additional transformation in document coordinates (code copied from sp_item_i2d_affine)
147                         sp_item_invoke_bbox(item, 
148                             &bbox_of_item, 
149                             from_2geom(to_2geom(sp_item_i2doc_affine(item)) * matrix_to_desktop(additional_affine, item)),
150                             true);
151                     } else {
152                         sp_item_invoke_bbox(item, &bbox_of_item, sp_item_i2d_affine(item), true);
153                     }
154                     if (bbox_of_item) {
155                         // See if the item is within range                                    
156                         if (bbox_to_snap_incl.intersects(to_2geom(*bbox_of_item))) {
157                             // This item is within snapping range, so record it as a candidate
158                             _candidates->push_back(SnapCandidate(item, clip_or_mask, additional_affine));
159                         }                        
160                     }
161                 }
162             }
163         }
164     }
168 void Inkscape::ObjectSnapper::_collectNodes(Inkscape::Snapper::PointType const &t,
169                                          bool const &first_point) const
171     // Now, let's first collect all points to snap to. If we have a whole bunch of points to snap,
172     // e.g. when translating an item using the selector tool, then we will only do this for the
173     // first point and store the collection for later use. This significantly improves the performance
174     if (first_point) {
175         _points_to_snap_to->clear();
176         
177          // Determine the type of bounding box we should snap to
178         SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
179         
180         bool p_is_a_node = t & Inkscape::Snapper::SNAPPOINT_NODE;
181         bool p_is_a_bbox = t & Inkscape::Snapper::SNAPPOINT_BBOX;
182         bool p_is_a_guide = t & Inkscape::Snapper::SNAPPOINT_GUIDE;
183         
184         // A point considered for snapping should be either a node, a bbox corner or a guide. Pick only ONE!
185         g_assert(!(p_is_a_node && p_is_a_bbox || p_is_a_bbox && p_is_a_guide || p_is_a_node && p_is_a_guide));        
186         
187         if (_snap_to_bboxnode) {
188             int prefs_bbox = prefs_get_int_attribute("tools", "bounding_box", 0);
189             bbox_type = (prefs_bbox == 0)? 
190                 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
191         }
192         
193         // Consider the page border for snapping
194         if (_snap_to_page_border) {
195             _getBorderNodes(_points_to_snap_to);            
196         }
198         for (std::vector<SnapCandidate>::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 (_snap_to_itemnode) {
208                 if (!(_strict_snapping && !p_is_a_node) || p_is_a_guide) {
209                     std::vector<NR::Point> dummy_vctr;
210                     sp_item_snappoints(root_item, _include_item_center, SnapPointsIter(dummy_vctr));
211                     to_2geom(dummy_vctr, *_points_to_snap_to);
212                 }
213             }
215             //Collect the bounding box's corners so we can snap to them
216             if (_snap_to_bboxnode) {
217                 if (!(_strict_snapping && !p_is_a_bbox) || p_is_a_guide) {
218                     // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
219                     // of the item AND the bbox of the clipping path at the same time
220                     if (!(*i).clip_or_mask) {  
221                         boost::optional<NR::Rect> b = sp_item_bbox_desktop(root_item, bbox_type);
222                         if (b) {
223                             for ( unsigned k = 0 ; k < 4 ; k++ ) {
224                                 _points_to_snap_to->push_back(to_2geom(b->corner(k)));
225                             }
226                         }
227                     }
228                 }
229             }
230         }
231     }
234 void Inkscape::ObjectSnapper::_snapNodes(SnappedConstraints &sc,
235                                          Inkscape::Snapper::PointType const &t,
236                                          Geom::Point const &p,
237                                          bool const &first_point,
238                                          std::vector<Geom::Point> *unselected_nodes) const
240     // Iterate through all nodes, find out which one is the closest to p, and snap to it!
241     
242     _collectNodes(t, first_point);
243     
244     if (unselected_nodes != NULL) {
245         _points_to_snap_to->insert(_points_to_snap_to->end(), unselected_nodes->begin(), unselected_nodes->end());
246     }   
247     
248     SnappedPoint s;
249     bool success = false;
250     
251     for (std::vector<Geom::Point>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
252         Geom::Coord dist = Geom::L2(*k - p);        
253         if (dist < getSnapperTolerance() && dist < s.getDistance()) {
254             s = SnappedPoint(*k, SNAPTARGET_NODE, dist, getSnapperTolerance(), getSnapperAlwaysSnap());
255             success = true;
256         }
257     }
259     if (success) {
260         sc.points.push_back(s);    
261     }
264 void Inkscape::ObjectSnapper::_snapTranslatingGuideToNodes(SnappedConstraints &sc,
265                                          Inkscape::Snapper::PointType const &t,
266                                          Geom::Point const &p,
267                                          Geom::Point const &guide_normal) const
269     // Iterate through all nodes, find out which one is the closest to this guide, and snap to it!
270     _collectNodes(t, true);
271     
272     SnappedPoint s;
273     bool success = false;
274     
275     Geom::Coord tol = getSnapperTolerance();
276     
277     for (std::vector<Geom::Point>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
278         // Project each node (*k) on the guide line (running through point p)
279         Geom::Point p_proj = project_on_linesegment(*k, p, p + Geom::rot90(guide_normal));
280         Geom::Coord dist = Geom::L2(*k - p_proj); // distance from node to the guide         
281         Geom::Coord dist2 = Geom::L2(p - p_proj); // distance from projection of node on the guide, to the mouse location
282         if ((dist < tol && dist2 < tol || getSnapperAlwaysSnap()) && dist < s.getDistance()) {
283             s = SnappedPoint(*k, SNAPTARGET_NODE, dist, tol, getSnapperAlwaysSnap());
284             success = true;
285         }
286     }
288     if (success) {
289         sc.points.push_back(s); 
290     }
294 /**
295  * Returns index of first NR_END bpath in array.
296  */
298 /* Obsolete
299 static unsigned sp_bpath_length(NArtBpath const bpath[])
301     g_return_val_if_fail(bpath != NULL, FALSE);
302     unsigned ret = 0;
303     while ( bpath[ret].code != NR_END ) {
304         ++ret;
305     }
306     ++ret;
307     return ret;
308 }*/
310 void Inkscape::ObjectSnapper::_collectPaths(Inkscape::Snapper::PointType const &t,
311                                          bool const &first_point) const
313     // Now, let's first collect all paths to snap to. If we have a whole bunch of points to snap,
314     // e.g. when translating an item using the selector tool, then we will only do this for the
315     // first point and store the collection for later use. This significantly improves the performance
316     if (first_point) {
317         _clear_paths();
318         
319         // Determine the type of bounding box we should snap to
320         SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
321         
322         bool p_is_a_node = t & Inkscape::Snapper::SNAPPOINT_NODE;
323         
324         if (_snap_to_bboxpath) {
325             int prefs_bbox = prefs_get_int_attribute("tools", "bounding_box", 0);
326             bbox_type = (prefs_bbox ==0)? 
327                 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
328         }
329         
330         // Consider the page border for snapping
331         if (_snap_to_page_border) {
332             Geom::PathVector *border_path = _getBorderPathv();
333             if (border_path != NULL) {
334                 _paths_to_snap_to->push_back(border_path);
335             }
336         }
337         
338         for (std::vector<SnapCandidate>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
340             /* Transform the requested snap point to this item's coordinates */
341             Geom::Matrix i2doc(Geom::identity());
342             SPItem *root_item = NULL;
343             /* We might have a clone at hand, so make sure we get the root item */
344             if (SP_IS_USE((*i).item)) {
345                 i2doc = sp_use_get_root_transform(SP_USE((*i).item));
346                 root_item = sp_use_root(SP_USE((*i).item));
347                 g_return_if_fail(root_item);
348             } else {
349                 i2doc = sp_item_i2doc_affine((*i).item);
350                 root_item = (*i).item;
351             }
352             
353             //Build a list of all paths considered for snapping to
355             //Add the item's path to snap to
356             if (_snap_to_itempath) {
357                 if (!(_strict_snapping && !p_is_a_node)) {
358                     // Snapping to the path of characters is very cool, but for a large
359                     // chunk of text this will take ages! So limit snapping to text paths
360                     // containing max. 240 characters. Snapping the bbox will not be affected
361                     bool very_lenghty_prose = false;
362                     if (SP_IS_TEXT(root_item) || SP_IS_FLOWTEXT(root_item)) {
363                         very_lenghty_prose =  sp_text_get_length(SP_TEXT(root_item)) > 240;
364                     }
365                     // On my AMD 3000+, the snapping lag becomes annoying at approx. 240 chars
366                     // which corresponds to a lag of 500 msec. This is for snapping a rect
367                     // to a single line of text.
369                     // Snapping for example to a traced bitmap is also very stressing for
370                     // the CPU, so we'll only snap to paths having no more than 500 nodes
371                     // This also leads to a lag of approx. 500 msec (in my lousy test set-up).
372                     bool very_complex_path = false;
373                     if (SP_IS_PATH(root_item)) {
374                         very_complex_path = sp_nodes_in_path(SP_PATH(root_item)) > 500;
375                     }
377                     if (!very_lenghty_prose && !very_complex_path) {
378                         SPCurve *curve = curve_for_item(root_item); 
379                         if (curve) {
380                             // We will get our own copy of the path, which must be freed at some point
381                             Geom::PathVector *borderpathv = pathvector_for_curve(root_item, curve, true, true, Geom::identity(), (*i).additional_affine); 
382                             _paths_to_snap_to->push_back(borderpathv); // Perhaps for speed, get a reference to the Geom::pathvector, and store the transformation besides it.
383                             curve->unref();
384                         }
385                     }
386                 }
387             }
389             //Add the item's bounding box to snap to
390             if (_snap_to_bboxpath) {
391                 if (!(_strict_snapping && p_is_a_node)) {
392                     // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
393                     // of the item AND the bbox of the clipping path at the same time
394                     if (!(*i).clip_or_mask) { 
395                         NRRect rect;
396                         sp_item_invoke_bbox(root_item, &rect, i2doc, TRUE, bbox_type);
397                         Geom::Rect const rect2 = to_2geom(*rect.upgrade());
398                         Geom::PathVector *path = _getPathvFromRect(rect2);
399                         _paths_to_snap_to->push_back(path);                        
400                     }
401                 }
402             }
403         }
404     }
406     
407 void Inkscape::ObjectSnapper::_snapPaths(SnappedConstraints &sc,
408                                      Inkscape::Snapper::PointType const &t,
409                                      Geom::Point const &p,
410                                      bool const &first_point,
411                                      std::vector<Geom::Point> *unselected_nodes,
412                                      SPPath const *selected_path) const
414     _collectPaths(t, first_point);
415     // Now we can finally do the real snapping, using the paths collected above
416     
417     /* FIXME: this seems like a hack.  Perhaps Snappers should be
418     ** in SPDesktop rather than SPNamedView?
419     */
420     // TODO Diederik: shouldn't we just make all snapping code use document
421     // coordinates instead? Then we won't need a pointer to the desktop any longer
422     // At least we should define a clear boundary between those different coordinates,
423     // now this is not well defined
424     
425     SPDesktop const *desktop = SP_ACTIVE_DESKTOP;    
426     Geom::Point const p_doc = desktop->dt2doc(p);
427     
428     bool const node_tool_active = _snap_to_itempath && selected_path != NULL;
429     
430     if (first_point) {
431         /* While editing a path in the node tool, findCandidates must ignore that path because 
432          * of the node snapping requirements (i.e. only unselected nodes must be snapable).
433          * This path must not be ignored however when snapping to the paths, so we add it here
434          * manually when applicable. 
435          * 
436          * Note that this path must be the last in line!
437          * */        
438         if (node_tool_active) {        
439             SPCurve *curve = curve_for_item(SP_ITEM(selected_path)); 
440             if (curve) {
441                 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
442                 _paths_to_snap_to->push_back(pathv);
443                 curve->unref();
444             }
445         }
446     }
447     
448     for (std::vector<Geom::PathVector*>::const_iterator it_p = _paths_to_snap_to->begin(); it_p != _paths_to_snap_to->end(); it_p++) {
449         bool const being_edited = (node_tool_active && (*it_p) == _paths_to_snap_to->back());            
450         //if true then this pathvector it_pv is currently being edited in the node tool
451         
452         // char * svgd = sp_svg_write_path(**it_p);
453         // std::cout << "Dumping the pathvector: " << svgd << std::endl;        
454         
455         for(Geom::PathVector::iterator it_pv = (*it_p)->begin(); it_pv != (*it_p)->end(); ++it_pv) {
456             // Find a nearest point for each curve within this path
457             // n curves will return n time values with 0 <= t <= 1
458             std::vector<double> anp = (*it_pv).nearestPointPerCurve(p_doc);
459             
460             std::vector<double>::const_iterator np = anp.begin();
461             unsigned int index = 0;
462             for (; np != anp.end(); np++, index++) {
463                 Geom::Curve const *curve = &((*it_pv).at_index(index));
464                 Geom::Point const sp_doc = curve->pointAt(*np);
465                 
466                 bool c1 = true;
467                 bool c2 = true;                                
468                 if (being_edited) {
469                     /* If the path is being edited, then we should only snap though to stationary pieces of the path
470                      * and not to the pieces that are being dragged around. This way we avoid 
471                      * self-snapping. For this we check whether the nodes at both ends of the current
472                      * piece are unselected; if they are then this piece must be stationary 
473                      */                    
474                     g_assert(unselected_nodes != NULL);
475                     Geom::Point start_pt = desktop->doc2dt(curve->pointAt(0)); 
476                     Geom::Point end_pt = desktop->doc2dt(curve->pointAt(1));                                    
477                     c1 = isUnselectedNode(start_pt, unselected_nodes);
478                     c2 = isUnselectedNode(end_pt, unselected_nodes);
479                 }
480                 
481                 Geom::Point const sp_dt = desktop->doc2dt(sp_doc);                
482                 if (!being_edited || (c1 && c2)) {
483                     Geom::Coord const dist = Geom::distance(sp_doc, p_doc);
484                     if (dist < getSnapperTolerance()) {
485                         sc.curves.push_back(Inkscape::SnappedCurve(from_2geom(sp_dt), dist, getSnapperTolerance(), getSnapperAlwaysSnap(), curve));   
486                     }
487                 }
488             }        
489         } // End of: for (Geom::PathVector::iterator ....)        
490     }    
493 /* Returns true if point is coincident with one of the unselected nodes */ 
494 bool Inkscape::ObjectSnapper::isUnselectedNode(Geom::Point const &point, std::vector<Geom::Point> const *unselected_nodes) const
496     if (unselected_nodes == NULL) {
497         return false;
498     }
499     
500     if (unselected_nodes->size() == 0) {
501         return false;
502     }
503     
504     for (std::vector<Geom::Point>::const_iterator i = unselected_nodes->begin(); i != unselected_nodes->end(); i++) {
505         if (Geom::L2(point - *i) < 1e-4) {
506             return true;
507         }   
508     }  
509     
510     return false;    
513 void Inkscape::ObjectSnapper::_snapPathsConstrained(SnappedConstraints &sc,
514                                      Inkscape::Snapper::PointType const &t,
515                                      Geom::Point const &p,
516                                      bool const &first_point,
517                                      ConstraintLine const &c) const
519     
520     _collectPaths(t, first_point);
521     
522     // Now we can finally do the real snapping, using the paths collected above
523     
524     /* FIXME: this seems like a hack.  Perhaps Snappers should be
525     ** in SPDesktop rather than SPNamedView?
526     */
527     SPDesktop const *desktop = SP_ACTIVE_DESKTOP;    
528     Geom::Point const p_doc = desktop->dt2doc(p);    
529     
530     Geom::Point direction_vector = c.getDirection();
531     if (!is_zero(direction_vector)) {
532         direction_vector = Geom::unit_vector(direction_vector);
533     }
534     
535     Geom::Point const p1_on_cl = c.hasPoint() ? c.getPoint() : p;
536     Geom::Point const p2_on_cl = p1_on_cl + direction_vector;
537     
538     // The intersection point of the constraint line with any path, 
539     // must lie within two points on the constraintline: p_min_on_cl and p_max_on_cl
540     // The distance between those points is twice the snapping tolerance
541     Geom::Point const p_proj_on_cl = project_on_linesegment(p, p1_on_cl, p2_on_cl);
542     Geom::Point const p_min_on_cl = desktop->dt2doc(p_proj_on_cl - getSnapperTolerance() * direction_vector);    
543     Geom::Point const p_max_on_cl = desktop->dt2doc(p_proj_on_cl + getSnapperTolerance() * direction_vector);
544     
545     Geom::Path cl;
546     std::vector<Geom::Path> clv;    
547     cl.start(p_min_on_cl);
548     cl.appendNew<Geom::LineSegment>(p_max_on_cl);
549     clv.push_back(cl);
550     
551     for (std::vector<Geom::PathVector*>::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
552         if (*k) {                        
553             Geom::CrossingSet cs = Geom::crossings(clv, *(*k));
554             if (cs.size() > 0) {
555                 // We need only the first element of cs, because cl is only a single straight linesegment
556                 // This first element contains a vector filled with crossings of cl with *k
557                 for (std::vector<Geom::Crossing>::const_iterator m = cs[0].begin(); m != cs[0].end(); m++) {                    
558                     if ((*m).ta >= 0 && (*m).ta <= 1 ) {
559                         // Reconstruct the point of intersection
560                         Geom::Point p_inters = p_min_on_cl + ((*m).ta) * (p_max_on_cl - p_min_on_cl);
561                         // When it's within snapping range, then return it
562                         // (within snapping range == between p_min_on_cl and p_max_on_cl == 0 < ta < 1)                        
563                         Geom::Coord dist = Geom::L2(desktop->dt2doc(p_proj_on_cl) - p_inters);
564                         SnappedPoint s(desktop->doc2dt(p_inters), SNAPTARGET_PATH, dist, getSnapperTolerance(), getSnapperAlwaysSnap());
565                         sc.points.push_back(s);
566                     }  
567                 } 
568             }
569         }
570     }
574 void Inkscape::ObjectSnapper::freeSnap(SnappedConstraints &sc,
575                                             Inkscape::Snapper::PointType const &t,
576                                             Geom::Point const &p,
577                                             bool const &first_point,
578                                             boost::optional<Geom::Rect> const &bbox_to_snap,
579                                             std::vector<SPItem const *> const *it,
580                                             std::vector<Geom::Point> *unselected_nodes) const
582     if (_snap_enabled == false || getSnapFrom(t) == false || _named_view == NULL) {
583         return;
584     }
586     /* Get a list of all the SPItems that we will try to snap to */
587     if (first_point) {
588         Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p, p);
589         _findCandidates(sp_document_root(_named_view->document), it, first_point, local_bbox_to_snap, TRANSL_SNAP_XY, false, Geom::identity());
590     }
591     
592     if (_snap_to_itemnode || _snap_to_bboxnode || _snap_to_page_border) {
593         _snapNodes(sc, t, p, first_point, unselected_nodes);
594     }
595     
596     if (_snap_to_itempath || _snap_to_bboxpath || _snap_to_page_border) {
597         unsigned n = (unselected_nodes == NULL) ? 0 : unselected_nodes->size();
598         if (n > 0) {
599             /* While editing a path in the node tool, findCandidates must ignore that path because 
600              * of the node snapping requirements (i.e. only unselected nodes must be snapable).
601              * That path must not be ignored however when snapping to the paths, so we add it here
602              * manually when applicable
603              */            
604             SPPath *path = NULL;
605             if (it != NULL) {
606                 g_assert(SP_IS_PATH(*it->begin()));
607                 g_assert(it->size() == 1);
608                 path = SP_PATH(*it->begin());
609             }
610             _snapPaths(sc, t, p, first_point, unselected_nodes, path);                
611         } else {
612             _snapPaths(sc, t, p, first_point, NULL, NULL);   
613         }        
614     }
617 void Inkscape::ObjectSnapper::constrainedSnap( SnappedConstraints &sc,
618                                                   Inkscape::Snapper::PointType const &t,
619                                                   Geom::Point const &p,
620                                                   bool const &first_point,
621                                                   boost::optional<Geom::Rect> const &bbox_to_snap,
622                                                   ConstraintLine const &c,
623                                                   std::vector<SPItem const *> const *it) const
625     if (_snap_enabled == false || getSnapFrom(t) == false || _named_view == NULL) {
626         return;
627     }
629     /* Get a list of all the SPItems that we will try to snap to */
630     if (first_point) {
631         Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p, p);
632         _findCandidates(sp_document_root(_named_view->document), it, first_point, local_bbox_to_snap, TRANSL_SNAP_XY, false, Geom::identity());
633     }
634     
635     // A constrained snap, is a snap in only one degree of freedom (specified by the constraint line).
636     // This is usefull for example when scaling an object while maintaining a fixed aspect ratio. It's
637     // nodes are only allowed to move in one direction (i.e. in one degree of freedom).
638     
639     // When snapping to objects, we either snap to their nodes or their paths. It is however very
640     // unlikely that any node will be exactly at the constrained line, so for a constrained snap
641     // to objects we will only consider the object's paths. Beside, the nodes will be at these paths,
642     // so we will more or less snap to them anyhow.   
644     if (_snap_to_itempath || _snap_to_bboxpath || _snap_to_page_border) {
645         _snapPathsConstrained(sc, t, p, first_point, c);
646     }
650 // This method is used to snap a guide to nodes, while dragging the guide around
651 void Inkscape::ObjectSnapper::guideSnap(SnappedConstraints &sc,
652                                         Geom::Point const &p,
653                                         Geom::Point const &guide_normal) const
655     if ( NULL == _named_view ) {
656         return;
657     }
658     
659     /* Get a list of all the SPItems that we will try to snap to */
660     std::vector<SPItem*> cand;
661     std::vector<SPItem const *> const it; //just an empty list
662     
663     DimensionToSnap snap_dim;
664     if (guide_normal == to_2geom(component_vectors[Geom::Y])) {
665         snap_dim = GUIDE_TRANSL_SNAP_Y;
666     } else if (guide_normal == to_2geom(component_vectors[Geom::X])) {
667         snap_dim = GUIDE_TRANSL_SNAP_X;
668     } else {
669         snap_dim = ANGLED_GUIDE_TRANSL_SNAP;
670     }
671     
672     // We don't support ANGLED_GUIDE_ROT_SNAP yet. 
673     
674     // It would be cool to allow the user to rotate a guide by dragging it, instead of
675     // only translating it. (For example when CTRL is pressed). We will need an UI part 
676     // for that first; and some important usability choices need to be made: 
677     // E.g. which point should be used for pivoting? A previously snapped point,
678     // or a transformation center (which can be moved after clicking for the
679     // second time on an object; but should this point then be constrained to the
680     // line, or can it be located anywhere?)
681     
682     _findCandidates(sp_document_root(_named_view->document), &it, true, Geom::Rect(p, p), snap_dim, false, Geom::identity());
683     _snapTranslatingGuideToNodes(sc, Inkscape::Snapper::SNAPPOINT_GUIDE, p, guide_normal);
684     // _snapRotatingGuideToNodes has not been implemented yet. 
687 /**
688  *  \return true if this Snapper will snap at least one kind of point.
689  */
690 bool Inkscape::ObjectSnapper::ThisSnapperMightSnap() const
692     bool snap_to_something = _snap_to_itempath || _snap_to_itemnode || _snap_to_bboxpath || _snap_to_bboxnode || _snap_to_page_border;
693     return (_snap_enabled && _snap_from != 0 && snap_to_something);
696 bool Inkscape::ObjectSnapper::GuidesMightSnap() const
698     bool snap_to_something = _snap_to_itemnode || _snap_to_bboxnode;
699     return (_snap_enabled && (_snap_from & SNAPPOINT_GUIDE) && snap_to_something);
702 void Inkscape::ObjectSnapper::_clear_paths() const 
704     for (std::vector<Geom::PathVector*>::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
705         g_free(*k);
706     }
707     _paths_to_snap_to->clear();
710 Geom::PathVector* Inkscape::ObjectSnapper::_getBorderPathv() const
712     Geom::Rect const border_rect = Geom::Rect(Geom::Point(0,0), Geom::Point(sp_document_width(_named_view->document),sp_document_height(_named_view->document)));
713     return _getPathvFromRect(border_rect);        
716 Geom::PathVector* Inkscape::ObjectSnapper::_getPathvFromRect(Geom::Rect const rect) const
718     SPCurve const *border_curve = SPCurve::new_from_rect(rect);
719     if (border_curve) {
720         Geom::PathVector *dummy = new Geom::PathVector(border_curve->get_pathvector());
721         return dummy;
722     } else {
723         return NULL;
724     }     
727 void Inkscape::ObjectSnapper::_getBorderNodes(std::vector<Geom::Point> *points) const
729     Geom::Coord w = sp_document_width(_named_view->document);
730     Geom::Coord h = sp_document_height(_named_view->document);
731     points->push_back(Geom::Point(0,0));
732     points->push_back(Geom::Point(0,h));
733     points->push_back(Geom::Point(w,h));
734     points->push_back(Geom::Point(w,0));
737 /*
738   Local Variables:
739   mode:c++
740   c-file-style:"stroustrup"
741   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
742   indent-tabs-mode:nil
743   fill-column:99
744   End:
745 */
746 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :