Code

Snap to page corners too (you won't notice the difference yet because it will snap...
[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/n-art-bpath.h"
16 #include "libnr/nr-path.h"
17 #include "libnr/nr-rect-ops.h"
18 #include "libnr/nr-point-fns.h"
19 #include "libnr/n-art-bpath-2geom.h"
20 #include <2geom/path-intersection.h>
21 #include <2geom/point.h>
22 #include <2geom/rect.h>
23 #include "document.h"
24 #include "sp-namedview.h"
25 #include "sp-image.h"
26 #include "sp-item-group.h"
27 #include "sp-item.h"
28 #include "sp-use.h"
29 #include "display/curve.h"
30 #include "desktop.h"
31 #include "inkscape.h"
32 #include "prefs-utils.h"
33 #include "sp-text.h"
34 #include "sp-flowtext.h"
35 #include "text-editing.h"
36 #include "sp-clippath.h"
37 #include "sp-mask.h"
39 Inkscape::SnapCandidate::SnapCandidate(SPItem* item, bool clip_or_mask, NR::Matrix additional_affine)
40         : item(item), clip_or_mask(clip_or_mask), additional_affine(additional_affine)
41 {       
42 }
44 Inkscape::SnapCandidate::~SnapCandidate()
45 {       
46 }
48 Inkscape::ObjectSnapper::ObjectSnapper(SPNamedView const *nv, NR::Coord const d)
49     : Snapper(nv, d), _snap_to_itemnode(true), _snap_to_itempath(true),
50       _snap_to_bboxnode(true), _snap_to_bboxpath(true), _snap_to_page_border(false),
51       _strict_snapping(true), _include_item_center(false)
52 {
53     _candidates = new std::vector<SnapCandidate>;
54     _points_to_snap_to = new std::vector<NR::Point>;
55     _bpaths_to_snap_to = new std::vector<NArtBpath*>;
56     _paths_to_snap_to = new std::vector<Path*>;
57 }
59 Inkscape::ObjectSnapper::~ObjectSnapper()
60 {
61     _candidates->clear();
62     delete _candidates;
64     _points_to_snap_to->clear();
65     delete _points_to_snap_to;
67     _clear_paths();
68     delete _paths_to_snap_to;
69     delete _bpaths_to_snap_to;
70 }
72 /**
73  *  Find all items within snapping range.
74  *  \param parent Pointer to the document's root, or to a clipped path or mask object
75  *  \param it List of items to ignore
76  *  \param first_point If true then this point is the first one from a whole bunch of points
77  *  \param bbox_to_snap Bounding box hulling the whole bunch of points, all from the same selection and having the same transformation
78  *  \param DimensionToSnap Snap in X, Y, or both directions.
79  */
81 void Inkscape::ObjectSnapper::_findCandidates(SPObject* parent,
82                                               std::vector<SPItem const *> const *it,
83                                               bool const &first_point,
84                                               NR::Rect const &bbox_to_snap,
85                                               DimensionToSnap const snap_dim,
86                                               bool const clip_or_mask,
87                                               NR::Matrix const additional_affine) const // transformation of the item being clipped / masked
88 {
89     bool const c1 = (snap_dim == TRANSL_SNAP_XY) && ThisSnapperMightSnap();
90     bool const c2 = (snap_dim != TRANSL_SNAP_XY) && GuidesMightSnap();
91     
92     if (!(c1 || c2)) {
93         return;        
94     }
95     
96     SPDesktop const *desktop = SP_ACTIVE_DESKTOP;
98     if (first_point) {
99         _candidates->clear();
100     }
101     
102     NR::Maybe<NR::Rect> bbox_of_item = NR::Rect(); // a default NR::Rect is infinitely large
103     NR::Rect bbox_to_snap_incl = bbox_to_snap; // _incl means: will include the snapper tolerance
104     bbox_to_snap_incl.growBy(getSnapperTolerance()); // see?
105     
106     for (SPObject* o = sp_object_first_child(parent); o != NULL; o = SP_OBJECT_NEXT(o)) {
107         if (SP_IS_ITEM(o) && !SP_ITEM(o)->isLocked() && !(desktop->itemIsHidden(SP_ITEM(o)) && !clip_or_mask)) {
108             // Don't snap to locked items, and
109             // don't snap to hidden objects, unless they're a clipped path or a mask
110             /* See if this item is on the ignore list */
111             std::vector<SPItem const *>::const_iterator i;
112             if (it != NULL) {
113                 i = it->begin();
114                 while (i != it->end() && *i != o) {
115                     i++;
116                 }
117             }
118             
119             if (it == NULL || i == it->end()) {
120                 SPItem *item = SP_ITEM(o); 
121                 NR::Matrix transform = NR::identity();
122                 if (item) {
123                     SPObject *obj = NULL;
124                     if (clip_or_mask) { // If the current item is a clipping path or a mask
125                         // then store the transformation of the clipped path or mask itself
126                         // but also take into account the additional affine of the object 
127                         // being clipped / masked
128                         transform = item->transform * additional_affine;
129                     } else { // cannot clip or mask more than once                     
130                         // The current item is not a clipping path or a mask, but might
131                         // still be the subject of clipping or masking itself ; if so, then
132                         // we should also consider that path or mask for snapping to
133                         obj = SP_OBJECT(item->clip_ref->getObject());
134                         if (obj) {
135                             _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, item->transform);
136                         } 
137                         obj = SP_OBJECT(item->mask_ref->getObject());
138                         if (obj) {
139                             _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, item->transform);
140                         }
141                     }
142                 }            
143                 
144                 if (SP_IS_GROUP(o)) {
145                     _findCandidates(o, it, false, bbox_to_snap, snap_dim, false, NR::identity());
146                 } else {
147                     if (clip_or_mask) {
148                         // Oh oh, this will get ugly. We cannot use sp_item_i2d_affine directly because we need to
149                         // insert an additional transformation in document coordinates (code copied from sp_item_i2d_affine)
150                         sp_item_invoke_bbox(item, 
151                                         &bbox_of_item, 
152                                         from_2geom(sp_item_i2doc_affine(item) * matrix_to_desktop(to_2geom(additional_affine), item)),
153                                         true);
154                         
155                     } else {
156                         sp_item_invoke_bbox(item, &bbox_of_item, from_2geom(sp_item_i2d_affine(item)), true);
157                     }                    
158                     // See if the item is within range                                    
159                     if (bbox_of_item) {
160                         if (bbox_to_snap_incl.intersects(*bbox_of_item)) {
161                             // This item is within snapping range, so record it as a candidate
162                             _candidates->push_back(SnapCandidate(item, clip_or_mask, additional_affine));
163                         }
164                     }
165                 }
166             }
167         }
168     }
172 void Inkscape::ObjectSnapper::_collectNodes(Inkscape::Snapper::PointType const &t,
173                                          bool const &first_point) const
175     // Now, let's first collect all points to snap to. If we have a whole bunch of points to snap,
176     // e.g. when translating an item using the selector tool, then we will only do this for the
177     // first point and store the collection for later use. This significantly improves the performance
178     if (first_point) {
179         _points_to_snap_to->clear();
180         
181          // Determine the type of bounding box we should snap to
182         SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
183         
184         bool p_is_a_node = t & Inkscape::Snapper::SNAPPOINT_NODE;
185         bool p_is_a_bbox = t & Inkscape::Snapper::SNAPPOINT_BBOX;
186         bool p_is_a_guide = t & Inkscape::Snapper::SNAPPOINT_GUIDE;
187         
188         // A point considered for snapping should be either a node, a bbox corner or a guide. Pick only ONE!
189         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));        
190         
191         if (_snap_to_bboxnode) {
192             int prefs_bbox = prefs_get_int_attribute("tools", "bounding_box", 0);
193             bbox_type = (prefs_bbox == 0)? 
194                 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
195         }
196         
197         // Consider the page border for snapping
198         if (_snap_to_page_border) {
199                 _getBorderNodes(_points_to_snap_to);            
200         }
202         for (std::vector<SnapCandidate>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
203             //NR::Matrix i2doc(NR::identity());
204             SPItem *root_item = (*i).item;
205             if (SP_IS_USE((*i).item)) {
206                 root_item = sp_use_root(SP_USE((*i).item));
207             }
208             g_return_if_fail(root_item);
210             //Collect all nodes so we can snap to them
211             if (_snap_to_itemnode) {
212                 if (!(_strict_snapping && !p_is_a_node) || p_is_a_guide) {
213                     sp_item_snappoints(root_item, _include_item_center, SnapPointsIter(*_points_to_snap_to));
214                 }
215             }
217             //Collect the bounding box's corners so we can snap to them
218             if (_snap_to_bboxnode) {
219                 if (!(_strict_snapping && !p_is_a_bbox) || p_is_a_guide) {
220                         // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
221                         // of the item AND the bbox of the clipping path at the same time
222                         if (!(*i).clip_or_mask) {  
223                         NR::Maybe<NR::Rect> b = sp_item_bbox_desktop(root_item, bbox_type);
224                         if (b) {
225                             for ( unsigned k = 0 ; k < 4 ; k++ ) {
226                                 _points_to_snap_to->push_back(b->corner(k));
227                             }
228                         }
229                     }
230                 }
231             }
232         }
233     }
236 void Inkscape::ObjectSnapper::_snapNodes(SnappedConstraints &sc,
237                                          Inkscape::Snapper::PointType const &t,
238                                          NR::Point const &p,
239                                          bool const &first_point,
240                                          std::vector<NR::Point> *unselected_nodes) const
242     // Iterate through all nodes, find out which one is the closest to p, and snap to it!
243     
244     _collectNodes(t, first_point);
245     
246     if (unselected_nodes != NULL) {
247         _points_to_snap_to->insert(_points_to_snap_to->end(), unselected_nodes->begin(), unselected_nodes->end());
248     }   
249     
250     SnappedPoint s;
251     bool success = false;
252     
253     for (std::vector<NR::Point>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
254         NR::Coord dist = NR::L2(*k - p);        
255         if (dist < getSnapperTolerance() && dist < s.getDistance()) {
256             s = SnappedPoint(*k, SNAPTARGET_NODE, dist, getSnapperTolerance(), getSnapperAlwaysSnap());
257             success = true;
258         }
259     }
261     if (success) {
262         sc.points.push_back(s); 
263     }
266 void Inkscape::ObjectSnapper::_snapTranslatingGuideToNodes(SnappedConstraints &sc,
267                                          Inkscape::Snapper::PointType const &t,
268                                          NR::Point const &p,
269                                          NR::Point const &guide_normal) const
271     // Iterate through all nodes, find out which one is the closest to this guide, and snap to it!
272     _collectNodes(t, true);
273     
274     SnappedPoint s;
275     bool success = false;
276     
277     NR::Coord tol = getSnapperTolerance();
278     
279     for (std::vector<NR::Point>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
280         // Project each node (*k) on the guide line (running through point p)
281         NR::Point p_proj = project_on_linesegment(*k, p, p + NR::rot90(guide_normal));
282         NR::Coord dist = NR::L2(*k - p_proj); // distance from node to the guide         
283         NR::Coord dist2 = NR::L2(p - p_proj); // distance from projection of node on the guide, to the mouse location
284         if ((dist < tol && dist2 < tol || getSnapperAlwaysSnap()) && dist < s.getDistance()) {
285             s = SnappedPoint(*k, SNAPTARGET_NODE, dist, tol, getSnapperAlwaysSnap());
286             success = true;
287         }
288     }
290     if (success) {
291         sc.points.push_back(s); 
292     }
295 /**
296  * Returns index of first NR_END bpath in array.
297  */
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;
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                 NArtBpath const *border_bpath = _getBorderBPath();   
332                 if (border_bpath != NULL) {
333                     // make our own copy of the const*
334                     NArtBpath *new_bpath;
335                     unsigned const len = sp_bpath_length(border_bpath);
336                     new_bpath = g_new(NArtBpath, len);
337                     memcpy(new_bpath, border_bpath, len * sizeof(NArtBpath));
338         
339                     _bpaths_to_snap_to->push_back(new_bpath);
340                 }
341         }
342         
343         for (std::vector<SnapCandidate>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
345             /* Transform the requested snap point to this item's coordinates */
346             NR::Matrix i2doc(NR::identity());
347             SPItem *root_item = NULL;
348             /* We might have a clone at hand, so make sure we get the root item */
349             if (SP_IS_USE((*i).item)) {
350                 i2doc = sp_use_get_root_transform(SP_USE((*i).item));
351                 root_item = sp_use_root(SP_USE((*i).item));
352                 g_return_if_fail(root_item);
353             } else {
354                 i2doc = from_2geom(sp_item_i2doc_affine((*i).item));
355                 root_item = (*i).item;
356             }
357             
358             //Build a list of all paths considered for snapping to
360             //Add the item's path to snap to
361             if (_snap_to_itempath) {
362                 if (!(_strict_snapping && !p_is_a_node)) {
363                     // Snapping to the path of characters is very cool, but for a large
364                     // chunk of text this will take ages! So limit snapping to text paths
365                     // containing max. 240 characters. Snapping the bbox will not be affected
366                     bool very_lenghty_prose = false;
367                     if (SP_IS_TEXT(root_item) || SP_IS_FLOWTEXT(root_item)) {
368                         very_lenghty_prose =  sp_text_get_length(SP_TEXT(root_item)) > 240;
369                     }
370                     // On my AMD 3000+, the snapping lag becomes annoying at approx. 240 chars
371                     // which corresponds to a lag of 500 msec. This is for snapping a rect
372                     // to a single line of text.
374                     // Snapping for example to a traced bitmap is also very stressing for
375                     // the CPU, so we'll only snap to paths having no more than 500 nodes
376                     // This also leads to a lag of approx. 500 msec (in my lousy test set-up).
377                     bool very_complex_path = false;
378                     if (SP_IS_PATH(root_item)) {
379                         very_complex_path = sp_nodes_in_path(SP_PATH(root_item)) > 500;
380                     }
382                     if (!very_lenghty_prose && !very_complex_path) {
383                         SPCurve *curve = curve_for_item(root_item); 
384                         if (curve) {
385                             NArtBpath *bpath = bpath_for_curve(root_item, curve, true, true, 
386                                                                                            NR::identity(),
387                                                                                            (*i).additional_affine); 
388                             // Perhaps for speed, get a reference to the Geom::pathvector, and store the transformation besides it. 
389                             _bpaths_to_snap_to->push_back(bpath); // we will get a dupe of the path, which must be freed at some point
390                             
391                             /*std::vector<Geom::Path> pathv;
392                             char *svgpath = sp_svg_write_path(bpath);
393                             if (svgpath) {
394                                 std::cout << "path = " << svgpath << std::endl;
395                             }
396                             g_free(svgpath);
397                             */
398                             
399                             curve->unref();
400                         }
401                     }
402                 }
403             }
405             //Add the item's bounding box to snap to
406             if (_snap_to_bboxpath) {
407                 if (!(_strict_snapping && p_is_a_node)) {
408                         // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
409                         // of the item AND the bbox of the clipping path at the same time
410                         if (!(*i).clip_or_mask) { 
411                         NRRect rect;
412                         sp_item_invoke_bbox(root_item, &rect, i2doc, TRUE, bbox_type);
413                         NArtBpath *bpath = nr_path_from_rect(rect);
414                         _bpaths_to_snap_to->push_back(bpath);                        
415                     }
416                 }
417             }
418         }
419     }
421     
422 void Inkscape::ObjectSnapper::_snapPaths(SnappedConstraints &sc,
423                                      Inkscape::Snapper::PointType const &t,
424                                      NR::Point const &p,
425                                      bool const &first_point,
426                                      std::vector<NR::Point> *unselected_nodes,
427                                      SPPath const *selected_path) const
429     _collectPaths(t, first_point);
430     // Now we can finally do the real snapping, using the paths collected above
431     SnappedPoint s;
432     bool success = false;
433     
434     /* FIXME: this seems like a hack.  Perhaps Snappers should be
435     ** in SPDesktop rather than SPNamedView?
436     */
437     SPDesktop const *desktop = SP_ACTIVE_DESKTOP;    
438     NR::Point const p_doc = desktop->dt2doc(p);    
439     
440     bool const node_tool_active = _snap_to_itempath && selected_path != NULL;
441     
442     if (first_point) {
443         /* While editing a path in the node tool, findCandidates must ignore that path because 
444          * of the node snapping requirements (i.e. only unselected nodes must be snapable).
445          * This path must not be ignored however when snapping to the paths, so we add it here
446          * manually when applicable. 
447          * 
448          * Note that this path must be the last in line!
449          * */        
450         if (node_tool_active) {        
451             SPCurve *curve = curve_for_item(SP_ITEM(selected_path)); 
452             if (curve) {
453                 NArtBpath *bpath = bpath_for_curve(SP_ITEM(selected_path), curve, true, true, NR::identity(), NR::identity());
454                 _bpaths_to_snap_to->push_back(bpath); // we will get a dupe of the path, which must be freed at some point
455                 curve->unref();
456             }
457         }   
458         // Convert all bpaths to Paths, because here we really must have Paths
459         // (whereas in _snapPathsConstrained we will use the original bpaths)
460         for (std::vector<NArtBpath*>::const_iterator k = _bpaths_to_snap_to->begin(); k != _bpaths_to_snap_to->end(); k++) {
461             Path *path = bpath_to_Path(*k);
462             if (path) {
463                 path->ConvertWithBackData(0.01); //This is extremely time consuming!
464                 _paths_to_snap_to->push_back(path);
465             }    
466         }
467     }
468     
469     for (std::vector<Path*>::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
470         if (*k) {
471             bool const being_edited = (node_tool_active && (*k) == _paths_to_snap_to->back());            
472             //if true then this path k is currently being edited in the node tool
473             
474             for (unsigned i = 1 ; i < (*k)->pts.size() ; i++) { 
475                 //pts describes a polyline approximation, which might consist of 1000s of points!
476                 NR::Point start_point;
477                 NR::Point end_point;   
478                 NR::Maybe<Path::cut_position> o = NR::Nothing();                 
479                 if (being_edited) { 
480                     /* If the path is being edited, then we will try to snap to each piece of the 
481                      * path individually. We should only snap though to stationary pieces of the paths
482                      * and not to the pieces that are being dragged around. This way we avoid 
483                      * self-snapping. For this we check whether the nodes at both ends of the current
484                      * piece are unselected; if they are then this piece must be stationary 
485                      */                    
486                     unsigned piece = (*k)->pts[i].piece; 
487                     // Example: a cubic spline is a single piece within a path; it will be drawn using
488                     // a polyline, which is described by the collection of lines between the points pts[i] 
489                     (*k)->PointAt(piece, 0, start_point);
490                     (*k)->PointAt(piece, 1, end_point);
491                     start_point = desktop->doc2dt(start_point);
492                     end_point = desktop->doc2dt(end_point);
493                     g_assert(unselected_nodes != NULL);
494                     bool c1 = isUnselectedNode(start_point, unselected_nodes);
495                     bool c2 = isUnselectedNode(end_point, unselected_nodes);     
496                     if (c1 && c2) {
497                         o = get_nearest_position_on_Path(*k, p_doc, i);
498                     }
499                 } else {
500                     /* If the path is NOT being edited, then we will try to snap to the path as a
501                      * whole, so we need to do this only once and we will break out at the end of
502                      * this for-loop iteration */                    
503                     /* Look for the nearest position on this SPItem to our snap point */
504                     o = get_nearest_position_on_Path(*k, p_doc);
505                     (*k)->PointAt(o->piece, 0, start_point);
506                     (*k)->PointAt(o->piece, 1, end_point);
507                     start_point = desktop->doc2dt(start_point);
508                     end_point = desktop->doc2dt(end_point);
509                 }
510                 
511                 if (o && o->t >= 0 && o->t <= 1) {    
512                     /* Convert the nearest point back to desktop coordinates */
513                     NR::Point const o_it = get_point_on_Path(*k, o->piece, o->t);
514                     
515                     /* IF YOU'RE BUG HUNTING: IT LOOKS LIKE get_point_on_Path SOMETIMES
516                      * RETURNS THE WRONG POINT (WITH AN OFFSET, BUT STILL ON THE PATH.
517                      * THIS BUG WILL NO LONGER BE ENCOUNTERED ONCE WE'VE SWITCHED TO 
518                      * 2GEOM FOR THE OBJECT SNAPPER
519                      */
520                      
521                     NR::Point const o_dt = desktop->doc2dt(o_it);                
522                     NR::Coord const dist = NR::L2(o_dt - p);
523     
524                     if (dist < getSnapperTolerance()) {
525                         // if we snap to a straight line segment (within a path), then return this line segment
526                         if ((*k)->IsLineSegment(o->piece)) {
527                             sc.lines.push_back(Inkscape::SnappedLineSegment(o_dt, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), start_point, end_point));    
528                         } else {                
529                             // for segments other than straight lines of a path, we'll return just the closest snapped point
530                             if (dist < s.getDistance()) {
531                                 s = SnappedPoint(o_dt, SNAPTARGET_PATH, dist, getSnapperTolerance(), getSnapperAlwaysSnap());
532                                 success = true;
533                             }
534                         }
535                     }
536                 }        
537                 
538                 // If the path is NOT being edited, then we will try to snap to the path as a whole
539                 // so we need to do this only once
540                 if (!being_edited) break;
541             }
542         }
543     }
545     if (success) {
546         sc.points.push_back(s); 
547     }
550 /* Returns true if point is coincident with one of the unselected nodes */ 
551 bool Inkscape::ObjectSnapper::isUnselectedNode(NR::Point const &point, std::vector<NR::Point> const *unselected_nodes) const
553     if (unselected_nodes == NULL) {
554         return false;
555     }
556     
557     if (unselected_nodes->size() == 0) {
558         return false;
559     }
560     
561     for (std::vector<NR::Point>::const_iterator i = unselected_nodes->begin(); i != unselected_nodes->end(); i++) {
562         if (NR::L2(point - *i) < 1e-4) {
563             return true;
564         }   
565     }  
566     
567     return false;    
570 void Inkscape::ObjectSnapper::_snapPathsConstrained(SnappedConstraints &sc,
571                                      Inkscape::Snapper::PointType const &t,
572                                      NR::Point const &p,
573                                      bool const &first_point,
574                                      ConstraintLine const &c) const
576     
577     _collectPaths(t, first_point);
578     
579     // Now we can finally do the real snapping, using the paths collected above
580     
581     /* FIXME: this seems like a hack.  Perhaps Snappers should be
582     ** in SPDesktop rather than SPNamedView?
583     */
584     SPDesktop const *desktop = SP_ACTIVE_DESKTOP;    
585     NR::Point const p_doc = desktop->dt2doc(p);    
586     
587     NR::Point direction_vector = c.getDirection();
588     if (!is_zero(direction_vector)) {
589         direction_vector = NR::unit_vector(direction_vector);
590     }
591     
592     NR::Point const p1_on_cl = c.hasPoint() ? c.getPoint() : p;
593     NR::Point const p2_on_cl = p1_on_cl + direction_vector;
594     
595     // The intersection point of the constraint line with any path, 
596     // must lie within two points on the constraintline: p_min_on_cl and p_max_on_cl
597     // The distance between those points is twice the snapping tolerance
598     NR::Point const p_proj_on_cl = project_on_linesegment(p, p1_on_cl, p2_on_cl);
599     NR::Point const p_min_on_cl = desktop->dt2doc(p_proj_on_cl - getSnapperTolerance() * direction_vector);    
600     NR::Point const p_max_on_cl = desktop->dt2doc(p_proj_on_cl + getSnapperTolerance() * direction_vector);
601     
602     Geom::Path cl;
603     std::vector<Geom::Path> clv;    
604     cl.start(p_min_on_cl.to_2geom());
605     cl.appendNew<Geom::LineSegment>(p_max_on_cl.to_2geom());
606     clv.push_back(cl);
607     
608     for (std::vector<NArtBpath*>::const_iterator k = _bpaths_to_snap_to->begin(); k != _bpaths_to_snap_to->end(); k++) {
609         if (*k) {                        
610             // convert a Path object (see src/livarot/Path.h) to a 2geom's path object (see 2geom/path.h)
611             // TODO: (Diederik) Only do this once for the first point, needs some storage of pointers in a member variable
612             std::vector<Geom::Path> path_2geom = BPath_to_2GeomPath(*k);  
613             
614             Geom::CrossingSet cs = Geom::crossings(clv, path_2geom);
615             if (cs.size() > 0) {
616                 // We need only the first element of cs, because cl is only a single straight linesegment
617                 // This first element contains a vector filled with crossings of cl with path_2geom
618                 for (std::vector<Geom::Crossing>::const_iterator m = cs[0].begin(); m != cs[0].end(); m++) {                    
619                     if ((*m).ta >= 0 && (*m).ta <= 1 ) {
620                         // Reconstruct the point of intersection
621                         NR::Point p_inters = p_min_on_cl + ((*m).ta) * (p_max_on_cl - p_min_on_cl);
622                         // When it's within snapping range, then return it
623                         // (within snapping range == between p_min_on_cl and p_max_on_cl == 0 < ta < 1)                        
624                         NR::Coord dist = NR::L2(desktop->dt2doc(p_proj_on_cl) - p_inters);
625                         SnappedPoint s(desktop->doc2dt(p_inters), SNAPTARGET_PATH, dist, getSnapperTolerance(), getSnapperAlwaysSnap());
626                         sc.points.push_back(s);    
627                     }  
628                 } 
629             }
630         }
631     }
635 void Inkscape::ObjectSnapper::freeSnap(SnappedConstraints &sc,
636                                             Inkscape::Snapper::PointType const &t,
637                                             NR::Point const &p,
638                                             bool const &first_point,
639                                             NR::Maybe<NR::Rect> const &bbox_to_snap,
640                                             std::vector<SPItem const *> const *it,
641                                             std::vector<NR::Point> *unselected_nodes) const
643     if (_snap_enabled == false || getSnapFrom(t) == false || _named_view == NULL) {
644         return;
645     }
647     /* Get a list of all the SPItems that we will try to snap to */
648     if (first_point) {
649         NR::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : NR::Rect(p, p);
650         _findCandidates(sp_document_root(_named_view->document), it, first_point, local_bbox_to_snap, TRANSL_SNAP_XY, false, NR::identity());
651     }
652     
653     if (_snap_to_itemnode || _snap_to_bboxnode || _snap_to_page_border) {
654         _snapNodes(sc, t, p, first_point, unselected_nodes);
655     }
656     
657     if (_snap_to_itempath || _snap_to_bboxpath || _snap_to_page_border) {
658         unsigned n = (unselected_nodes == NULL) ? 0 : unselected_nodes->size();
659         if (n > 0) {
660             /* While editing a path in the node tool, findCandidates must ignore that path because 
661              * of the node snapping requirements (i.e. only unselected nodes must be snapable).
662              * That path must not be ignored however when snapping to the paths, so we add it here
663              * manually when applicable
664              */            
665             SPPath *path = NULL;
666             if (it != NULL) {
667                 g_assert(SP_IS_PATH(*it->begin()));
668                 g_assert(it->size() == 1);
669                 path = SP_PATH(*it->begin());
670             }
671             _snapPaths(sc, t, p, first_point, unselected_nodes, path);                
672         } else {
673             _snapPaths(sc, t, p, first_point, NULL, NULL);   
674         }        
675     }
678 void Inkscape::ObjectSnapper::constrainedSnap( SnappedConstraints &sc,
679                                                   Inkscape::Snapper::PointType const &t,
680                                                   NR::Point const &p,
681                                                   bool const &first_point,
682                                                   NR::Maybe<NR::Rect> const &bbox_to_snap,
683                                                   ConstraintLine const &c,
684                                                   std::vector<SPItem const *> const *it) const
686     if (_snap_enabled == false || getSnapFrom(t) == false || _named_view == NULL) {
687         return;
688     }
690     /* Get a list of all the SPItems that we will try to snap to */
691     if (first_point) {
692         NR::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : NR::Rect(p, p);
693         _findCandidates(sp_document_root(_named_view->document), it, first_point, local_bbox_to_snap, TRANSL_SNAP_XY, false, NR::identity());
694     }
695     
696     // A constrained snap, is a snap in only one degree of freedom (specified by the constraint line).
697     // This is usefull for example when scaling an object while maintaining a fixed aspect ratio. It's
698     // nodes are only allowed to move in one direction (i.e. in one degree of freedom).
699     
700     // When snapping to objects, we either snap to their nodes or their paths. It is however very
701     // unlikely that any node will be exactly at the constrained line, so for a constrained snap
702     // to objects we will only consider the object's paths. Beside, the nodes will be at these paths,
703     // so we will more or less snap to them anyhow.   
705     if (_snap_to_itempath || _snap_to_bboxpath || _snap_to_page_border) {
706         _snapPathsConstrained(sc, t, p, first_point, c);
707     }
711 // This method is used to snap a guide to nodes, while dragging the guide around
712 void Inkscape::ObjectSnapper::guideSnap(SnappedConstraints &sc,
713                                                                                 NR::Point const &p,
714                                             NR::Point const &guide_normal) const
716     if ( NULL == _named_view ) {
717         return;
718     }
719     
720     /* Get a list of all the SPItems that we will try to snap to */
721     std::vector<SPItem*> cand;
722     std::vector<SPItem const *> const it; //just an empty list
723     
724     DimensionToSnap snap_dim;
725     if (guide_normal == component_vectors[NR::Y]) {
726         snap_dim = GUIDE_TRANSL_SNAP_Y;
727     } else if (guide_normal == component_vectors[NR::X]) {
728         snap_dim = GUIDE_TRANSL_SNAP_X;
729     } else {
730         snap_dim = ANGLED_GUIDE_TRANSL_SNAP;
731     }
732     
733     // We don't support ANGLED_GUIDE_ROT_SNAP yet. 
734     
735     // It would be cool to allow the user to rotate a guide by dragging it, instead of
736     // only translating it. (For example when CTRL is pressed). We will need an UI part 
737     // for that first; and some important usability choices need to be made: 
738     // E.g. which point should be used for pivoting? A previously snapped point,
739     // or a transformation center (which can be moved after clicking for the
740     // second time on an object; but should this point then be constrained to the
741     // line, or can it be located anywhere?)
742     
743     _findCandidates(sp_document_root(_named_view->document), &it, true, NR::Rect(p, p), snap_dim, false, NR::identity());
744         _snapTranslatingGuideToNodes(sc, Inkscape::Snapper::SNAPPOINT_GUIDE, p, guide_normal);
745     // _snapRotatingGuideToNodes has not been implemented yet. 
748 /**
749  *  \return true if this Snapper will snap at least one kind of point.
750  */
751 bool Inkscape::ObjectSnapper::ThisSnapperMightSnap() const
753     bool snap_to_something = _snap_to_itempath || _snap_to_itemnode || _snap_to_bboxpath || _snap_to_bboxnode || _snap_to_page_border;
754     return (_snap_enabled && _snap_from != 0 && snap_to_something);
757 bool Inkscape::ObjectSnapper::GuidesMightSnap() const
759     bool snap_to_something = _snap_to_itemnode || _snap_to_bboxnode;
760     return (_snap_enabled && (_snap_from & SNAPPOINT_GUIDE) && snap_to_something);
763 void Inkscape::ObjectSnapper::_clear_paths() const 
765     for (std::vector<NArtBpath*>::const_iterator k = _bpaths_to_snap_to->begin(); k != _bpaths_to_snap_to->end(); k++) {
766         g_free(*k);
767     }
768     _bpaths_to_snap_to->clear();
769     
770     for (std::vector<Path*>::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
771         delete *k;    
772     }
773     _paths_to_snap_to->clear();
776 NArtBpath const* Inkscape::ObjectSnapper::_getBorderBPath() const
778     NArtBpath const *border_bpath = NULL;
779     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)));
780     SPCurve const *border_curve = SPCurve::new_from_rect(border_rect);
781     if (border_curve) {
782         border_bpath = BPath_from_2GeomPath(border_curve->get_pathvector()); 
783     }
784         
785     return border_bpath;
788 void Inkscape::ObjectSnapper::_getBorderNodes(std::vector<NR::Point> *points) const
790         Geom::Coord w = sp_document_width(_named_view->document);
791         Geom::Coord h = sp_document_height(_named_view->document);
792         points->push_back(from_2geom(Geom::Point(0,0)));
793         points->push_back(from_2geom(Geom::Point(0,h)));
794         points->push_back(from_2geom(Geom::Point(w,h)));
795         points->push_back(from_2geom(Geom::Point(w,0)));
797 /*
798   Local Variables:
799   mode:c++
800   c-file-style:"stroustrup"
801   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
802   indent-tabs-mode:nil
803   fill-column:99
804   End:
805 */
806 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :