Code

remove many unnecessary to_2geom and from_2geom calls
[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, NR::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, NR::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<NR::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                                               NR::Rect const &bbox_to_snap,
82                                               DimensionToSnap const snap_dim,
83                                               bool const clip_or_mask,
84                                               NR::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     boost::optional<NR::Rect> bbox_of_item = NR::Rect(); // a default NR::Rect is infinitely large
100     NR::Rect bbox_to_snap_incl = bbox_to_snap; // _incl means: will include the snapper tolerance
101     bbox_to_snap_incl.growBy(getSnapperTolerance()); // see?
102     
103     for (SPObject* o = sp_object_first_child(parent); o != NULL; o = SP_OBJECT_NEXT(o)) {
104         if (SP_IS_ITEM(o) && !SP_ITEM(o)->isLocked() && !(desktop->itemIsHidden(SP_ITEM(o)) && !clip_or_mask)) {
105             // Don't snap to locked items, and
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             }
115             
116             if (it == NULL || i == it->end()) {
117                 SPItem *item = SP_ITEM(o); 
118                 NR::Matrix transform = NR::identity();
119                 if (item) {
120                     SPObject *obj = NULL;
121                     if (clip_or_mask) { // If the current item is a clipping path or a mask
122                         // then store the transformation of the clipped path or mask itself
123                         // but also take into account the additional affine of the object 
124                         // being clipped / masked
125                         transform = item->transform * additional_affine;
126                     } else { // cannot clip or mask more than once                     
127                         // The current item is not a clipping path or a mask, but might
128                         // still be the subject of clipping or masking itself ; if so, then
129                         // we should also consider that path or mask for snapping to
130                         obj = SP_OBJECT(item->clip_ref->getObject());
131                         if (obj) {
132                             _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, item->transform);
133                         } 
134                         obj = SP_OBJECT(item->mask_ref->getObject());
135                         if (obj) {
136                             _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, item->transform);
137                         }
138                     }
139                 }            
140                 
141                 if (SP_IS_GROUP(o)) {
142                     _findCandidates(o, it, false, bbox_to_snap, snap_dim, false, NR::identity());
143                 } else {
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                             sp_item_i2doc_affine(item) * matrix_to_desktop(additional_affine, item),
150                             true);
151                         
152                     } else {
153                         sp_item_invoke_bbox(item, &bbox_of_item, sp_item_i2d_affine(item), true);
154                     }                    
155                     // See if the item is within range                                    
156                     if (bbox_of_item) {
157                         if (bbox_to_snap_incl.intersects(*bbox_of_item)) {
158                             // This item is within snapping range, so record it as a candidate
159                             _candidates->push_back(SnapCandidate(item, clip_or_mask, additional_affine));
160                         }
161                     }
162                 }
163             }
164         }
165     }
169 void Inkscape::ObjectSnapper::_collectNodes(Inkscape::Snapper::PointType const &t,
170                                          bool const &first_point) const
172     // Now, let's first collect all points to snap to. If we have a whole bunch of points to snap,
173     // e.g. when translating an item using the selector tool, then we will only do this for the
174     // first point and store the collection for later use. This significantly improves the performance
175     if (first_point) {
176         _points_to_snap_to->clear();
177         
178          // Determine the type of bounding box we should snap to
179         SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
180         
181         bool p_is_a_node = t & Inkscape::Snapper::SNAPPOINT_NODE;
182         bool p_is_a_bbox = t & Inkscape::Snapper::SNAPPOINT_BBOX;
183         bool p_is_a_guide = t & Inkscape::Snapper::SNAPPOINT_GUIDE;
184         
185         // A point considered for snapping should be either a node, a bbox corner or a guide. Pick only ONE!
186         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));        
187         
188         if (_snap_to_bboxnode) {
189             int prefs_bbox = prefs_get_int_attribute("tools", "bounding_box", 0);
190             bbox_type = (prefs_bbox == 0)? 
191                 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
192         }
193         
194         // Consider the page border for snapping
195         if (_snap_to_page_border) {
196             _getBorderNodes(_points_to_snap_to);            
197         }
199         for (std::vector<SnapCandidate>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
200             //NR::Matrix i2doc(NR::identity());
201             SPItem *root_item = (*i).item;
202             if (SP_IS_USE((*i).item)) {
203                 root_item = sp_use_root(SP_USE((*i).item));
204             }
205             g_return_if_fail(root_item);
207             //Collect all nodes so we can snap to them
208             if (_snap_to_itemnode) {
209                 if (!(_strict_snapping && !p_is_a_node) || p_is_a_guide) {
210                     sp_item_snappoints(root_item, _include_item_center, SnapPointsIter(*_points_to_snap_to));
211                 }
212             }
214             //Collect the bounding box's corners so we can snap to them
215             if (_snap_to_bboxnode) {
216                 if (!(_strict_snapping && !p_is_a_bbox) || p_is_a_guide) {
217                     // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
218                     // of the item AND the bbox of the clipping path at the same time
219                     if (!(*i).clip_or_mask) {  
220                         boost::optional<NR::Rect> b = sp_item_bbox_desktop(root_item, bbox_type);
221                         if (b) {
222                             for ( unsigned k = 0 ; k < 4 ; k++ ) {
223                                 _points_to_snap_to->push_back(b->corner(k));
224                             }
225                         }
226                     }
227                 }
228             }
229         }
230     }
233 void Inkscape::ObjectSnapper::_snapNodes(SnappedConstraints &sc,
234                                          Inkscape::Snapper::PointType const &t,
235                                          NR::Point const &p,
236                                          bool const &first_point,
237                                          std::vector<NR::Point> *unselected_nodes) const
239     // Iterate through all nodes, find out which one is the closest to p, and snap to it!
240     
241     _collectNodes(t, first_point);
242     
243     if (unselected_nodes != NULL) {
244         _points_to_snap_to->insert(_points_to_snap_to->end(), unselected_nodes->begin(), unselected_nodes->end());
245     }   
246     
247     SnappedPoint s;
248     bool success = false;
249     
250     for (std::vector<NR::Point>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
251         NR::Coord dist = NR::L2(*k - p);        
252         if (dist < getSnapperTolerance() && dist < s.getDistance()) {
253             s = SnappedPoint(*k, SNAPTARGET_NODE, dist, getSnapperTolerance(), getSnapperAlwaysSnap());
254             success = true;
255         }
256     }
258     if (success) {
259         sc.points.push_back(s);    
260     }
263 void Inkscape::ObjectSnapper::_snapTranslatingGuideToNodes(SnappedConstraints &sc,
264                                          Inkscape::Snapper::PointType const &t,
265                                          NR::Point const &p,
266                                          NR::Point const &guide_normal) const
268     // Iterate through all nodes, find out which one is the closest to this guide, and snap to it!
269     _collectNodes(t, true);
270     
271     SnappedPoint s;
272     bool success = false;
273     
274     NR::Coord tol = getSnapperTolerance();
275     
276     for (std::vector<NR::Point>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
277         // Project each node (*k) on the guide line (running through point p)
278         NR::Point p_proj = project_on_linesegment(*k, p, p + NR::rot90(guide_normal));
279         NR::Coord dist = NR::L2(*k - p_proj); // distance from node to the guide         
280         NR::Coord dist2 = NR::L2(p - p_proj); // distance from projection of node on the guide, to the mouse location
281         if ((dist < tol && dist2 < tol || getSnapperAlwaysSnap()) && dist < s.getDistance()) {
282             s = SnappedPoint(*k, SNAPTARGET_NODE, dist, tol, getSnapperAlwaysSnap());
283             success = true;
284         }
285     }
287     if (success) {
288         sc.points.push_back(s); 
289     }
293 /**
294  * Returns index of first NR_END bpath in array.
295  */
297 /* Obsolete
298 static unsigned sp_bpath_length(NArtBpath const bpath[])
300     g_return_val_if_fail(bpath != NULL, FALSE);
301     unsigned ret = 0;
302     while ( bpath[ret].code != NR_END ) {
303         ++ret;
304     }
305     ++ret;
306     return ret;
307 }*/
309 void Inkscape::ObjectSnapper::_collectPaths(Inkscape::Snapper::PointType const &t,
310                                          bool const &first_point) const
312     // Now, let's first collect all paths to snap to. If we have a whole bunch of points to snap,
313     // e.g. when translating an item using the selector tool, then we will only do this for the
314     // first point and store the collection for later use. This significantly improves the performance
315     if (first_point) {
316         _clear_paths();
317         
318         // Determine the type of bounding box we should snap to
319         SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
320         
321         bool p_is_a_node = t & Inkscape::Snapper::SNAPPOINT_NODE;
322         
323         if (_snap_to_bboxpath) {
324             int prefs_bbox = prefs_get_int_attribute("tools", "bounding_box", 0);
325             bbox_type = (prefs_bbox ==0)? 
326                 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
327         }
328         
329         // Consider the page border for snapping
330         if (_snap_to_page_border) {
331             Geom::PathVector *border_path = _getBorderPathv();
332             if (border_path != NULL) {
333                 _paths_to_snap_to->push_back(border_path);
334             }
335         }
336         
337         for (std::vector<SnapCandidate>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
339             /* Transform the requested snap point to this item's coordinates */
340             NR::Matrix i2doc(NR::identity());
341             SPItem *root_item = NULL;
342             /* We might have a clone at hand, so make sure we get the root item */
343             if (SP_IS_USE((*i).item)) {
344                 i2doc = sp_use_get_root_transform(SP_USE((*i).item));
345                 root_item = sp_use_root(SP_USE((*i).item));
346                 g_return_if_fail(root_item);
347             } else {
348                 i2doc = sp_item_i2doc_affine((*i).item);
349                 root_item = (*i).item;
350             }
351             
352             //Build a list of all paths considered for snapping to
354             //Add the item's path to snap to
355             if (_snap_to_itempath) {
356                 if (!(_strict_snapping && !p_is_a_node)) {
357                     // Snapping to the path of characters is very cool, but for a large
358                     // chunk of text this will take ages! So limit snapping to text paths
359                     // containing max. 240 characters. Snapping the bbox will not be affected
360                     bool very_lenghty_prose = false;
361                     if (SP_IS_TEXT(root_item) || SP_IS_FLOWTEXT(root_item)) {
362                         very_lenghty_prose =  sp_text_get_length(SP_TEXT(root_item)) > 240;
363                     }
364                     // On my AMD 3000+, the snapping lag becomes annoying at approx. 240 chars
365                     // which corresponds to a lag of 500 msec. This is for snapping a rect
366                     // to a single line of text.
368                     // Snapping for example to a traced bitmap is also very stressing for
369                     // the CPU, so we'll only snap to paths having no more than 500 nodes
370                     // This also leads to a lag of approx. 500 msec (in my lousy test set-up).
371                     bool very_complex_path = false;
372                     if (SP_IS_PATH(root_item)) {
373                         very_complex_path = sp_nodes_in_path(SP_PATH(root_item)) > 500;
374                     }
376                     if (!very_lenghty_prose && !very_complex_path) {
377                         SPCurve *curve = curve_for_item(root_item); 
378                         if (curve) {
379                             // We will get our own copy of the path, which must be freed at some point
380                             Geom::PathVector *borderpathv = pathvector_for_curve(root_item, curve, true, true, Geom::identity(), (*i).additional_affine); 
381                             _paths_to_snap_to->push_back(borderpathv); // Perhaps for speed, get a reference to the Geom::pathvector, and store the transformation besides it.
382                             curve->unref();
383                         }
384                     }
385                 }
386             }
388             //Add the item's bounding box to snap to
389             if (_snap_to_bboxpath) {
390                 if (!(_strict_snapping && p_is_a_node)) {
391                     // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
392                     // of the item AND the bbox of the clipping path at the same time
393                     if (!(*i).clip_or_mask) { 
394                         NRRect rect;
395                         sp_item_invoke_bbox(root_item, &rect, i2doc, TRUE, bbox_type);
396                         Geom::Rect const rect2 = to_2geom(*rect.upgrade());
397                         Geom::PathVector *path = _getPathvFromRect(rect2);
398                         _paths_to_snap_to->push_back(path);                        
399                     }
400                 }
401             }
402         }
403     }
405     
406 void Inkscape::ObjectSnapper::_snapPaths(SnappedConstraints &sc,
407                                      Inkscape::Snapper::PointType const &t,
408                                      NR::Point const &p,
409                                      bool const &first_point,
410                                      std::vector<NR::Point> *unselected_nodes,
411                                      SPPath const *selected_path) const
413     _collectPaths(t, first_point);
414     // Now we can finally do the real snapping, using the paths collected above
415     
416     /* FIXME: this seems like a hack.  Perhaps Snappers should be
417     ** in SPDesktop rather than SPNamedView?
418     */
419     SPDesktop const *desktop = SP_ACTIVE_DESKTOP;    
420     Geom::Point const p_doc = desktop->dt2doc(p);
421     
422     bool const node_tool_active = _snap_to_itempath && selected_path != NULL;
423     
424     if (first_point) {
425         /* While editing a path in the node tool, findCandidates must ignore that path because 
426          * of the node snapping requirements (i.e. only unselected nodes must be snapable).
427          * This path must not be ignored however when snapping to the paths, so we add it here
428          * manually when applicable. 
429          * 
430          * Note that this path must be the last in line!
431          * */        
432         if (node_tool_active) {        
433             SPCurve *curve = curve_for_item(SP_ITEM(selected_path)); 
434             if (curve) {
435                 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
436                 _paths_to_snap_to->push_back(pathv);
437                 curve->unref();
438             }
439         }
440     }
441     
442     for (std::vector<Geom::PathVector*>::const_iterator it_p = _paths_to_snap_to->begin(); it_p != _paths_to_snap_to->end(); it_p++) {
443         bool const being_edited = (node_tool_active && (*it_p) == _paths_to_snap_to->back());            
444         
445         //if true then this pathvector it_pv is currently being edited in the node tool
446         SnappedPoint s;
447         bool success = false;
448         
449         // char * svgd = sp_svg_write_path(**it_p);
450         // std::cout << "Dumping the pathvector: " << svgd << std::endl;        
451         
452         for(Geom::PathVector::iterator it_pv = (*it_p)->begin(); it_pv != (*it_p)->end(); ++it_pv) {
453             std::vector<double> anp;
454             
455             // Find a nearest point for each curve within this path
456             // (path->allNearestPoints() will not do this for us! It was originally 
457             // intended to find for example multiple equidistant solutions)
458             unsigned int num_curves = (*it_pv).size();
459             if ( (*it_pv).closed() ) ++num_curves;
460             for (double t = 0; (t+1) <= double(num_curves); t++) {
461                 // Find a nearest point with time value in the range [t, t+1]
462                 anp.push_back((*it_pv).nearestPoint(p_doc, t, t+1)); 
463             }
464             
465             for (std::vector<double>::const_iterator np = anp.begin(); np != anp.end(); np++) {
466                 bool c1 = true;
467                 bool c2 = true;
468                 Geom::Point start_pt = desktop->doc2dt((*it_pv).pointAt(floor(*np))); 
469                 Geom::Point end_pt = desktop->doc2dt((*it_pv).pointAt(ceil(*np)));
470                 
471                 if (being_edited) {
472                     /* If the path is being edited, then we should only snap though to stationary pieces of the path
473                      * and not to the pieces that are being dragged around. This way we avoid 
474                      * self-snapping. For this we check whether the nodes at both ends of the current
475                      * piece are unselected; if they are then this piece must be stationary 
476                      */                    
477                     g_assert(unselected_nodes != NULL);
478                     c1 = isUnselectedNode(start_pt, unselected_nodes);
479                     c2 = isUnselectedNode(end_pt, unselected_nodes);
480                 }
481                 
482                 Geom::Point const sp_doc = (*it_pv).pointAt(*np);
483                 Geom::Point const sp_dt = desktop->doc2dt(sp_doc);
484                 
485                 if (!being_edited || (c1 && c2)) {
486                     NR::Coord const dist = Geom::distance(sp_doc, p_doc);
487                     if (dist < getSnapperTolerance()) {
488                         double t = MIN(*np, (*it_pv).size()); // make sure that t is within bounds;
489                         //Geom::Curve const & curve = (*it_pv).at_index(int(t));                         
490                         if(is_straight_curve((*it_pv).at_index(int(t)))) {
491                             // if we snap to a line segment, then return this line segment (leaves 1 DOF for snapping)
492                             sc.lines.push_back(Inkscape::SnappedLineSegment(sp_dt, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), start_pt, end_pt));    
493                         } else {                
494                             // for curves other than line segments, we'll return just the closest snapped point
495                             // (this is a fully constrained snap, no degrees of freedom left)
496                             if (dist < s.getDistance()) {
497                                 // If this curve has multiple segments, then we will return only 
498                                 // a single snapped point
499                                 s = SnappedPoint(sp_dt, SNAPTARGET_PATH, dist, getSnapperTolerance(), getSnapperAlwaysSnap());
500                                 success = true;
501                             }
502                         }
503                     }
504                 }
505             }        
506         } // End of: for (Geom::PathVector::iterator ....)
507         
508         // Return a snap point for each path in our collection.
509         // (unless we've already snapped to a line segment, see above)
510         if (success) {
511             sc.points.push_back(s); 
512         }
513         
514     }    
517 /* Returns true if point is coincident with one of the unselected nodes */ 
518 bool Inkscape::ObjectSnapper::isUnselectedNode(NR::Point const &point, std::vector<NR::Point> const *unselected_nodes) const
520     if (unselected_nodes == NULL) {
521         return false;
522     }
523     
524     if (unselected_nodes->size() == 0) {
525         return false;
526     }
527     
528     for (std::vector<NR::Point>::const_iterator i = unselected_nodes->begin(); i != unselected_nodes->end(); i++) {
529         if (NR::L2(point - *i) < 1e-4) {
530             return true;
531         }   
532     }  
533     
534     return false;    
537 void Inkscape::ObjectSnapper::_snapPathsConstrained(SnappedConstraints &sc,
538                                      Inkscape::Snapper::PointType const &t,
539                                      NR::Point const &p,
540                                      bool const &first_point,
541                                      ConstraintLine const &c) const
543     
544     _collectPaths(t, first_point);
545     
546     // Now we can finally do the real snapping, using the paths collected above
547     
548     /* FIXME: this seems like a hack.  Perhaps Snappers should be
549     ** in SPDesktop rather than SPNamedView?
550     */
551     SPDesktop const *desktop = SP_ACTIVE_DESKTOP;    
552     NR::Point const p_doc = desktop->dt2doc(p);    
553     
554     NR::Point direction_vector = c.getDirection();
555     if (!is_zero(direction_vector)) {
556         direction_vector = NR::unit_vector(direction_vector);
557     }
558     
559     NR::Point const p1_on_cl = c.hasPoint() ? c.getPoint() : p;
560     NR::Point const p2_on_cl = p1_on_cl + direction_vector;
561     
562     // The intersection point of the constraint line with any path, 
563     // must lie within two points on the constraintline: p_min_on_cl and p_max_on_cl
564     // The distance between those points is twice the snapping tolerance
565     NR::Point const p_proj_on_cl = project_on_linesegment(p, p1_on_cl, p2_on_cl);
566     NR::Point const p_min_on_cl = desktop->dt2doc(p_proj_on_cl - getSnapperTolerance() * direction_vector);    
567     NR::Point const p_max_on_cl = desktop->dt2doc(p_proj_on_cl + getSnapperTolerance() * direction_vector);
568     
569     Geom::Path cl;
570     std::vector<Geom::Path> clv;    
571     cl.start(p_min_on_cl);
572     cl.appendNew<Geom::LineSegment>(p_max_on_cl);
573     clv.push_back(cl);
574     
575     for (std::vector<Geom::PathVector*>::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
576         if (*k) {                        
577             Geom::CrossingSet cs = Geom::crossings(clv, *(*k));
578             if (cs.size() > 0) {
579                 // We need only the first element of cs, because cl is only a single straight linesegment
580                 // This first element contains a vector filled with crossings of cl with *k
581                 for (std::vector<Geom::Crossing>::const_iterator m = cs[0].begin(); m != cs[0].end(); m++) {                    
582                     if ((*m).ta >= 0 && (*m).ta <= 1 ) {
583                         // Reconstruct the point of intersection
584                         NR::Point p_inters = p_min_on_cl + ((*m).ta) * (p_max_on_cl - p_min_on_cl);
585                         // When it's within snapping range, then return it
586                         // (within snapping range == between p_min_on_cl and p_max_on_cl == 0 < ta < 1)                        
587                         NR::Coord dist = NR::L2(desktop->dt2doc(p_proj_on_cl) - p_inters);
588                         SnappedPoint s(desktop->doc2dt(p_inters), SNAPTARGET_PATH, dist, getSnapperTolerance(), getSnapperAlwaysSnap());
589                         sc.points.push_back(s);
590                     }  
591                 } 
592             }
593         }
594     }
598 void Inkscape::ObjectSnapper::freeSnap(SnappedConstraints &sc,
599                                             Inkscape::Snapper::PointType const &t,
600                                             NR::Point const &p,
601                                             bool const &first_point,
602                                             boost::optional<NR::Rect> const &bbox_to_snap,
603                                             std::vector<SPItem const *> const *it,
604                                             std::vector<NR::Point> *unselected_nodes) const
606     if (_snap_enabled == false || getSnapFrom(t) == false || _named_view == NULL) {
607         return;
608     }
610     /* Get a list of all the SPItems that we will try to snap to */
611     if (first_point) {
612         NR::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : NR::Rect(p, p);
613         _findCandidates(sp_document_root(_named_view->document), it, first_point, local_bbox_to_snap, TRANSL_SNAP_XY, false, NR::identity());
614     }
615     
616     if (_snap_to_itemnode || _snap_to_bboxnode || _snap_to_page_border) {
617         _snapNodes(sc, t, p, first_point, unselected_nodes);
618     }
619     
620     if (_snap_to_itempath || _snap_to_bboxpath || _snap_to_page_border) {
621         unsigned n = (unselected_nodes == NULL) ? 0 : unselected_nodes->size();
622         if (n > 0) {
623             /* While editing a path in the node tool, findCandidates must ignore that path because 
624              * of the node snapping requirements (i.e. only unselected nodes must be snapable).
625              * That path must not be ignored however when snapping to the paths, so we add it here
626              * manually when applicable
627              */            
628             SPPath *path = NULL;
629             if (it != NULL) {
630                 g_assert(SP_IS_PATH(*it->begin()));
631                 g_assert(it->size() == 1);
632                 path = SP_PATH(*it->begin());
633             }
634             _snapPaths(sc, t, p, first_point, unselected_nodes, path);                
635         } else {
636             _snapPaths(sc, t, p, first_point, NULL, NULL);   
637         }        
638     }
641 void Inkscape::ObjectSnapper::constrainedSnap( SnappedConstraints &sc,
642                                                   Inkscape::Snapper::PointType const &t,
643                                                   NR::Point const &p,
644                                                   bool const &first_point,
645                                                   boost::optional<NR::Rect> const &bbox_to_snap,
646                                                   ConstraintLine const &c,
647                                                   std::vector<SPItem const *> const *it) const
649     if (_snap_enabled == false || getSnapFrom(t) == false || _named_view == NULL) {
650         return;
651     }
653     /* Get a list of all the SPItems that we will try to snap to */
654     if (first_point) {
655         NR::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : NR::Rect(p, p);
656         _findCandidates(sp_document_root(_named_view->document), it, first_point, local_bbox_to_snap, TRANSL_SNAP_XY, false, NR::identity());
657     }
658     
659     // A constrained snap, is a snap in only one degree of freedom (specified by the constraint line).
660     // This is usefull for example when scaling an object while maintaining a fixed aspect ratio. It's
661     // nodes are only allowed to move in one direction (i.e. in one degree of freedom).
662     
663     // When snapping to objects, we either snap to their nodes or their paths. It is however very
664     // unlikely that any node will be exactly at the constrained line, so for a constrained snap
665     // to objects we will only consider the object's paths. Beside, the nodes will be at these paths,
666     // so we will more or less snap to them anyhow.   
668     if (_snap_to_itempath || _snap_to_bboxpath || _snap_to_page_border) {
669         _snapPathsConstrained(sc, t, p, first_point, c);
670     }
674 // This method is used to snap a guide to nodes, while dragging the guide around
675 void Inkscape::ObjectSnapper::guideSnap(SnappedConstraints &sc,
676                                         NR::Point const &p,
677                                         NR::Point const &guide_normal) const
679     if ( NULL == _named_view ) {
680         return;
681     }
682     
683     /* Get a list of all the SPItems that we will try to snap to */
684     std::vector<SPItem*> cand;
685     std::vector<SPItem const *> const it; //just an empty list
686     
687     DimensionToSnap snap_dim;
688     if (guide_normal == component_vectors[NR::Y]) {
689         snap_dim = GUIDE_TRANSL_SNAP_Y;
690     } else if (guide_normal == component_vectors[NR::X]) {
691         snap_dim = GUIDE_TRANSL_SNAP_X;
692     } else {
693         snap_dim = ANGLED_GUIDE_TRANSL_SNAP;
694     }
695     
696     // We don't support ANGLED_GUIDE_ROT_SNAP yet. 
697     
698     // It would be cool to allow the user to rotate a guide by dragging it, instead of
699     // only translating it. (For example when CTRL is pressed). We will need an UI part 
700     // for that first; and some important usability choices need to be made: 
701     // E.g. which point should be used for pivoting? A previously snapped point,
702     // or a transformation center (which can be moved after clicking for the
703     // second time on an object; but should this point then be constrained to the
704     // line, or can it be located anywhere?)
705     
706     _findCandidates(sp_document_root(_named_view->document), &it, true, NR::Rect(p, p), snap_dim, false, NR::identity());
707     _snapTranslatingGuideToNodes(sc, Inkscape::Snapper::SNAPPOINT_GUIDE, p, guide_normal);
708     // _snapRotatingGuideToNodes has not been implemented yet. 
711 /**
712  *  \return true if this Snapper will snap at least one kind of point.
713  */
714 bool Inkscape::ObjectSnapper::ThisSnapperMightSnap() const
716     bool snap_to_something = _snap_to_itempath || _snap_to_itemnode || _snap_to_bboxpath || _snap_to_bboxnode || _snap_to_page_border;
717     return (_snap_enabled && _snap_from != 0 && snap_to_something);
720 bool Inkscape::ObjectSnapper::GuidesMightSnap() const
722     bool snap_to_something = _snap_to_itemnode || _snap_to_bboxnode;
723     return (_snap_enabled && (_snap_from & SNAPPOINT_GUIDE) && snap_to_something);
726 void Inkscape::ObjectSnapper::_clear_paths() const 
728     for (std::vector<Geom::PathVector*>::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
729         g_free(*k);
730     }
731     _paths_to_snap_to->clear();
734 Geom::PathVector* Inkscape::ObjectSnapper::_getBorderPathv() const
736     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)));
737     return _getPathvFromRect(border_rect);        
740 Geom::PathVector* Inkscape::ObjectSnapper::_getPathvFromRect(Geom::Rect const rect) const
742     SPCurve const *border_curve = SPCurve::new_from_rect(rect);
743     if (border_curve) {
744         Geom::PathVector *dummy = new Geom::PathVector(border_curve->get_pathvector());
745         return dummy;
746     } else {
747         return NULL;
748     }     
751 void Inkscape::ObjectSnapper::_getBorderNodes(std::vector<NR::Point> *points) const
753     Geom::Coord w = sp_document_width(_named_view->document);
754     Geom::Coord h = sp_document_height(_named_view->document);
755     points->push_back(Geom::Point(0,0));
756     points->push_back(Geom::Point(0,h));
757     points->push_back(Geom::Point(w,h));
758     points->push_back(Geom::Point(w,0));
761 /*
762   Local Variables:
763   mode:c++
764   c-file-style:"stroustrup"
765   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
766   indent-tabs-mode:nil
767   fill-column:99
768   End:
769 */
770 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :