Code

NR::Maybe => boost::optional
[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                             from_2geom(sp_item_i2doc_affine(item) * matrix_to_desktop(to_2geom(additional_affine), item)),
150                             true);
151                         
152                     } else {
153                         sp_item_invoke_bbox(item, &bbox_of_item, from_2geom(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 = from_2geom(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(), to_2geom((*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 = to_2geom(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 = (*it_pv).allNearestPoints(p_doc);
454             for (std::vector<double>::const_iterator np = anp.begin(); np != anp.end(); np++) {
455                 bool c1 = true;
456                 bool c2 = true;
457                 Geom::Point start_pt = desktop->doc2dt((*it_pv).pointAt(floor(*np))); 
458                 Geom::Point end_pt = desktop->doc2dt((*it_pv).pointAt(ceil(*np)));
459                 if (being_edited) {
460                     /* If the path is being edited, then we should only snap though to stationary pieces of the path
461                      * and not to the pieces that are being dragged around. This way we avoid 
462                      * self-snapping. For this we check whether the nodes at both ends of the current
463                      * piece are unselected; if they are then this piece must be stationary 
464                      */                    
465                     g_assert(unselected_nodes != NULL);
466                     c1 = isUnselectedNode(from_2geom(start_pt), unselected_nodes);
467                     c2 = isUnselectedNode(from_2geom(end_pt), unselected_nodes);     
468                 }
469                 
470                 Geom::Point const sp_doc = (*it_pv).pointAt(*np);
471                 Geom::Point const sp_dt = desktop->doc2dt(sp_doc);
472                 
473                 if (!being_edited || (c2 && c2)) {
474                     NR::Coord const dist = Geom::distance(sp_doc, p_doc);
475     
476                     if (dist < getSnapperTolerance()) {
477                         double t = MIN(*np, (*it_pv).size()); // make sure that t is within bounds;
478                         //Geom::Curve const & curve = (*it_pv).at_index(int(t));                         
479                         if(is_straight_curve((*it_pv).at_index(int(t)))) {
480                             // if we snap to a line segment, then return this line segment (leaves 1 DOF for snapping)
481                             sc.lines.push_back(Inkscape::SnappedLineSegment(from_2geom(sp_dt), dist, getSnapperTolerance(), getSnapperAlwaysSnap(), from_2geom(start_pt), from_2geom(end_pt)));    
482                         } else {                
483                             // for curves other than line segments, we'll return just the closest snapped point
484                             // (this is a fully constrained snap, no degrees of freedom left)
485                             if (dist < s.getDistance()) {
486                                 // If this curve has multiple segments, then we will return only 
487                                 // a single snapped point
488                                 s = SnappedPoint(from_2geom(sp_dt), SNAPTARGET_PATH, dist, getSnapperTolerance(), getSnapperAlwaysSnap());
489                                 success = true;
490                             }
491                         }
492                     }
493                 }
494             }        
495         } // End of: for (Geom::PathVector::iterator ....)
496         
497         // Return a snap point for each path in our collection.
498         // (unless we've already snapped to a line segment, see above)
499         if (success) {
500             sc.points.push_back(s); 
501         }
502         
503     }    
506 /* Returns true if point is coincident with one of the unselected nodes */ 
507 bool Inkscape::ObjectSnapper::isUnselectedNode(NR::Point const &point, std::vector<NR::Point> const *unselected_nodes) const
509     if (unselected_nodes == NULL) {
510         return false;
511     }
512     
513     if (unselected_nodes->size() == 0) {
514         return false;
515     }
516     
517     for (std::vector<NR::Point>::const_iterator i = unselected_nodes->begin(); i != unselected_nodes->end(); i++) {
518         if (NR::L2(point - *i) < 1e-4) {
519             return true;
520         }   
521     }  
522     
523     return false;    
526 void Inkscape::ObjectSnapper::_snapPathsConstrained(SnappedConstraints &sc,
527                                      Inkscape::Snapper::PointType const &t,
528                                      NR::Point const &p,
529                                      bool const &first_point,
530                                      ConstraintLine const &c) const
532     
533     _collectPaths(t, first_point);
534     
535     // Now we can finally do the real snapping, using the paths collected above
536     
537     /* FIXME: this seems like a hack.  Perhaps Snappers should be
538     ** in SPDesktop rather than SPNamedView?
539     */
540     SPDesktop const *desktop = SP_ACTIVE_DESKTOP;    
541     NR::Point const p_doc = desktop->dt2doc(p);    
542     
543     NR::Point direction_vector = c.getDirection();
544     if (!is_zero(direction_vector)) {
545         direction_vector = NR::unit_vector(direction_vector);
546     }
547     
548     NR::Point const p1_on_cl = c.hasPoint() ? c.getPoint() : p;
549     NR::Point const p2_on_cl = p1_on_cl + direction_vector;
550     
551     // The intersection point of the constraint line with any path, 
552     // must lie within two points on the constraintline: p_min_on_cl and p_max_on_cl
553     // The distance between those points is twice the snapping tolerance
554     NR::Point const p_proj_on_cl = project_on_linesegment(p, p1_on_cl, p2_on_cl);
555     NR::Point const p_min_on_cl = desktop->dt2doc(p_proj_on_cl - getSnapperTolerance() * direction_vector);    
556     NR::Point const p_max_on_cl = desktop->dt2doc(p_proj_on_cl + getSnapperTolerance() * direction_vector);
557     
558     Geom::Path cl;
559     std::vector<Geom::Path> clv;    
560     cl.start(p_min_on_cl);
561     cl.appendNew<Geom::LineSegment>(p_max_on_cl);
562     clv.push_back(cl);
563     
564     for (std::vector<Geom::PathVector*>::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
565         if (*k) {                        
566             Geom::CrossingSet cs = Geom::crossings(clv, *(*k));
567             if (cs.size() > 0) {
568                 // We need only the first element of cs, because cl is only a single straight linesegment
569                 // This first element contains a vector filled with crossings of cl with *k
570                 for (std::vector<Geom::Crossing>::const_iterator m = cs[0].begin(); m != cs[0].end(); m++) {                    
571                     if ((*m).ta >= 0 && (*m).ta <= 1 ) {
572                         // Reconstruct the point of intersection
573                         NR::Point p_inters = p_min_on_cl + ((*m).ta) * (p_max_on_cl - p_min_on_cl);
574                         // When it's within snapping range, then return it
575                         // (within snapping range == between p_min_on_cl and p_max_on_cl == 0 < ta < 1)                        
576                         NR::Coord dist = NR::L2(desktop->dt2doc(p_proj_on_cl) - p_inters);
577                         SnappedPoint s(desktop->doc2dt(p_inters), SNAPTARGET_PATH, dist, getSnapperTolerance(), getSnapperAlwaysSnap());
578                         sc.points.push_back(s);
579                     }  
580                 } 
581             }
582         }
583     }
587 void Inkscape::ObjectSnapper::freeSnap(SnappedConstraints &sc,
588                                             Inkscape::Snapper::PointType const &t,
589                                             NR::Point const &p,
590                                             bool const &first_point,
591                                             boost::optional<NR::Rect> const &bbox_to_snap,
592                                             std::vector<SPItem const *> const *it,
593                                             std::vector<NR::Point> *unselected_nodes) const
595     if (_snap_enabled == false || getSnapFrom(t) == false || _named_view == NULL) {
596         return;
597     }
599     /* Get a list of all the SPItems that we will try to snap to */
600     if (first_point) {
601         NR::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : NR::Rect(p, p);
602         _findCandidates(sp_document_root(_named_view->document), it, first_point, local_bbox_to_snap, TRANSL_SNAP_XY, false, NR::identity());
603     }
604     
605     if (_snap_to_itemnode || _snap_to_bboxnode || _snap_to_page_border) {
606         _snapNodes(sc, t, p, first_point, unselected_nodes);
607     }
608     
609     if (_snap_to_itempath || _snap_to_bboxpath || _snap_to_page_border) {
610         unsigned n = (unselected_nodes == NULL) ? 0 : unselected_nodes->size();
611         if (n > 0) {
612             /* While editing a path in the node tool, findCandidates must ignore that path because 
613              * of the node snapping requirements (i.e. only unselected nodes must be snapable).
614              * That path must not be ignored however when snapping to the paths, so we add it here
615              * manually when applicable
616              */            
617             SPPath *path = NULL;
618             if (it != NULL) {
619                 g_assert(SP_IS_PATH(*it->begin()));
620                 g_assert(it->size() == 1);
621                 path = SP_PATH(*it->begin());
622             }
623             _snapPaths(sc, t, p, first_point, unselected_nodes, path);                
624         } else {
625             _snapPaths(sc, t, p, first_point, NULL, NULL);   
626         }        
627     }
630 void Inkscape::ObjectSnapper::constrainedSnap( SnappedConstraints &sc,
631                                                   Inkscape::Snapper::PointType const &t,
632                                                   NR::Point const &p,
633                                                   bool const &first_point,
634                                                   boost::optional<NR::Rect> const &bbox_to_snap,
635                                                   ConstraintLine const &c,
636                                                   std::vector<SPItem const *> const *it) const
638     if (_snap_enabled == false || getSnapFrom(t) == false || _named_view == NULL) {
639         return;
640     }
642     /* Get a list of all the SPItems that we will try to snap to */
643     if (first_point) {
644         NR::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : NR::Rect(p, p);
645         _findCandidates(sp_document_root(_named_view->document), it, first_point, local_bbox_to_snap, TRANSL_SNAP_XY, false, NR::identity());
646     }
647     
648     // A constrained snap, is a snap in only one degree of freedom (specified by the constraint line).
649     // This is usefull for example when scaling an object while maintaining a fixed aspect ratio. It's
650     // nodes are only allowed to move in one direction (i.e. in one degree of freedom).
651     
652     // When snapping to objects, we either snap to their nodes or their paths. It is however very
653     // unlikely that any node will be exactly at the constrained line, so for a constrained snap
654     // to objects we will only consider the object's paths. Beside, the nodes will be at these paths,
655     // so we will more or less snap to them anyhow.   
657     if (_snap_to_itempath || _snap_to_bboxpath || _snap_to_page_border) {
658         _snapPathsConstrained(sc, t, p, first_point, c);
659     }
663 // This method is used to snap a guide to nodes, while dragging the guide around
664 void Inkscape::ObjectSnapper::guideSnap(SnappedConstraints &sc,
665                                         NR::Point const &p,
666                                         NR::Point const &guide_normal) const
668     if ( NULL == _named_view ) {
669         return;
670     }
671     
672     /* Get a list of all the SPItems that we will try to snap to */
673     std::vector<SPItem*> cand;
674     std::vector<SPItem const *> const it; //just an empty list
675     
676     DimensionToSnap snap_dim;
677     if (guide_normal == component_vectors[NR::Y]) {
678         snap_dim = GUIDE_TRANSL_SNAP_Y;
679     } else if (guide_normal == component_vectors[NR::X]) {
680         snap_dim = GUIDE_TRANSL_SNAP_X;
681     } else {
682         snap_dim = ANGLED_GUIDE_TRANSL_SNAP;
683     }
684     
685     // We don't support ANGLED_GUIDE_ROT_SNAP yet. 
686     
687     // It would be cool to allow the user to rotate a guide by dragging it, instead of
688     // only translating it. (For example when CTRL is pressed). We will need an UI part 
689     // for that first; and some important usability choices need to be made: 
690     // E.g. which point should be used for pivoting? A previously snapped point,
691     // or a transformation center (which can be moved after clicking for the
692     // second time on an object; but should this point then be constrained to the
693     // line, or can it be located anywhere?)
694     
695     _findCandidates(sp_document_root(_named_view->document), &it, true, NR::Rect(p, p), snap_dim, false, NR::identity());
696     _snapTranslatingGuideToNodes(sc, Inkscape::Snapper::SNAPPOINT_GUIDE, p, guide_normal);
697     // _snapRotatingGuideToNodes has not been implemented yet. 
700 /**
701  *  \return true if this Snapper will snap at least one kind of point.
702  */
703 bool Inkscape::ObjectSnapper::ThisSnapperMightSnap() const
705     bool snap_to_something = _snap_to_itempath || _snap_to_itemnode || _snap_to_bboxpath || _snap_to_bboxnode || _snap_to_page_border;
706     return (_snap_enabled && _snap_from != 0 && snap_to_something);
709 bool Inkscape::ObjectSnapper::GuidesMightSnap() const
711     bool snap_to_something = _snap_to_itemnode || _snap_to_bboxnode;
712     return (_snap_enabled && (_snap_from & SNAPPOINT_GUIDE) && snap_to_something);
715 void Inkscape::ObjectSnapper::_clear_paths() const 
717     for (std::vector<Geom::PathVector*>::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
718         g_free(*k);
719     }
720     _paths_to_snap_to->clear();
723 Geom::PathVector* Inkscape::ObjectSnapper::_getBorderPathv() const
725     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)));
726     return _getPathvFromRect(border_rect);        
729 Geom::PathVector* Inkscape::ObjectSnapper::_getPathvFromRect(Geom::Rect const rect) const
731     SPCurve const *border_curve = SPCurve::new_from_rect(rect);
732     if (border_curve) {
733         Geom::PathVector *dummy = new Geom::PathVector(border_curve->get_pathvector());
734         return dummy;
735     } else {
736         return NULL;
737     }     
740 void Inkscape::ObjectSnapper::_getBorderNodes(std::vector<NR::Point> *points) const
742     Geom::Coord w = sp_document_width(_named_view->document);
743     Geom::Coord h = sp_document_height(_named_view->document);
744     points->push_back(from_2geom(Geom::Point(0,0)));
745     points->push_back(from_2geom(Geom::Point(0,h)));
746     points->push_back(from_2geom(Geom::Point(w,h)));
747     points->push_back(from_2geom(Geom::Point(w,0)));
750 /*
751   Local Variables:
752   mode:c++
753   c-file-style:"stroustrup"
754   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
755   indent-tabs-mode:nil
756   fill-column:99
757   End:
758 */
759 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :