Code

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