Code

f253d35386fd771a41a40a53e090d5ba6f5d53e1
[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  *
8  * Copyright (C) 2005 Authors
9  *
10  * Released under GNU GPL, read the file 'COPYING' for more information
11  */
13 #include "libnr/n-art-bpath.h"
14 #include "libnr/nr-rect-ops.h"
15 #include "document.h"
16 #include "sp-namedview.h"
17 #include "sp-image.h"
18 #include "sp-item-group.h"
19 #include "sp-item.h"
20 #include "sp-use.h"
21 #include "display/curve.h"
22 #include "desktop.h"
23 #include "inkscape.h"
24 #include "prefs-utils.h"
27 Inkscape::ObjectSnapper::ObjectSnapper(SPNamedView const *nv, NR::Coord const d)
28     : Snapper(nv, d), _snap_to_itemnode(true), _snap_to_itempath(true), 
29     _snap_to_bboxnode(true), _snap_to_bboxpath(true), _strict_snapping(true),
30     _include_item_center(false)
31 {
32         _candidates = new std::list<SPItem*>;
33         _points_to_snap_to = new std::list<NR::Point>;
34         _paths_to_snap_to = new std::list<Path*>;
35 }
37 Inkscape::ObjectSnapper::~ObjectSnapper() 
38 {
39         _candidates->clear(); //Don't delete the candidates themselves, as these are not ours!
40         delete _candidates;     
41         
42         _points_to_snap_to->clear();
43         delete _points_to_snap_to;
44         
45         for (std::list<Path*>::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
46                 delete *k;
47     }
48     _paths_to_snap_to->clear();
49         delete _paths_to_snap_to;
50 }
52 /**
53  *      Find all items within snapping range.  
54  *      \param r Pointer to the current document
55  *  \param it List of items to ignore 
56  *  \param first_point If true then this point is the first one from a whole bunch of points 
57  *  \param points_to_snap The whole bunch of points, all from the same selection and having the same transformation 
58  *  \param DimensionToSnap Snap in X, Y, or both directions.
59  */
61 void Inkscape::ObjectSnapper::_findCandidates(SPObject* r,
62                                               std::list<SPItem const *> const &it,
63                                               bool const &first_point,
64                                               std::vector<NR::Point> &points_to_snap,
65                                               DimensionToSnap const snap_dim) const
66 {
67     if (ThisSnapperMightSnap()) {    
68         SPDesktop const *desktop = SP_ACTIVE_DESKTOP;
69         
70         if (first_point) { 
71                 _candidates->clear();    
72                 
73                 for (SPObject* o = sp_object_first_child(r); o != NULL; o = SP_OBJECT_NEXT(o)) {
74                     if (SP_IS_ITEM(o) && !SP_ITEM(o)->isLocked() && !desktop->itemIsHidden(SP_ITEM(o))) {
75             
76                         /* See if this item is on the ignore list */
77                         std::list<SPItem const *>::const_iterator i = it.begin();
78                         while (i != it.end() && *i != o) {
79                             i++;
80                         }
81             
82                         if (i == it.end()) {
83                             /* See if the item is within range */
84                             if (SP_IS_GROUP(o)) {
85                                 _findCandidates(o, it, false, points_to_snap, snap_dim);
86                             } else {
87                                 // Now let's see if any of the snapping points is within
88                                 // snapping range of this object  
89                                 NR::Maybe<NR::Rect> b = sp_item_bbox_desktop(SP_ITEM(o));
90                                 if (b) {
91                                         for (std::vector<NR::Point>::const_iterator i = points_to_snap.begin(); i != points_to_snap.end(); i++) {
92                                                 NR::Point b_min = b->min();
93                                                 NR::Point b_max = b->max();                                     
94                                                 double d = getDistance();
95                                                 bool withinX = ((*i)[NR::X] >= b_min[NR::X] - d) && ((*i)[NR::X] <= b_max[NR::X] + d); 
96                                                 bool withinY = ((*i)[NR::Y] >= b_min[NR::Y] - d) && ((*i)[NR::Y] <= b_max[NR::Y] + d);
97                                                 if (snap_dim == SNAP_X && withinX || snap_dim == SNAP_Y && withinY || snap_dim == SNAP_XY && withinX && withinY) {
98                                                    //We've found a point that is within snapping range 
99                                                    //of this object, so record it as a candidate
100                                                    _candidates->push_back(SP_ITEM(o));
101                                                    break;
102                                                 }       
103                                         }       
104                                 }
105                             }
106                         }    
107                     }
108                 }
109         }        
110     }
114 void Inkscape::ObjectSnapper::_snapNodes(Inkscape::Snapper::PointType const &t,
115                                                                                  Inkscape::SnappedPoint &s,
116                                          NR::Point const &p,
117                                          bool const &first_point,
118                                          DimensionToSnap const snap_dim) const
120     /* FIXME: this seems like a hack.  Perhaps Snappers should be
121     ** in SPDesktop rather than SPNamedView?
122     */
123     SPDesktop const *desktop = SP_ACTIVE_DESKTOP;
124     
125     // Determine the type of bounding box we should snap to
126     SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX; 
127         if (_snap_to_bboxnode) {        
128                 gchar const *prefs_bbox = prefs_get_string_attribute("tools.select", "bounding_box");
129                 bbox_type = (prefs_bbox != NULL && strcmp(prefs_bbox, "geometric")==0)? SPItem::GEOMETRIC_BBOX : SPItem::APPROXIMATE_BBOX;
130         }        
131         
132         bool p_is_a_node = t & Inkscape::Snapper::SNAPPOINT_NODE;        
133         bool p_is_a_bbox = t & Inkscape::Snapper::SNAPPOINT_BBOX; 
134         bool p_is_a_guide = t & Inkscape::Snapper::SNAPPOINT_GUIDE;
135         
136         // A point considered for snapping should be either a node, a bbox corner or a guide. Pick only ONE! 
137         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));  
139     // Now, let's first collect all points to snap to. If we have a whole bunch of points to snap,
140     // e.g. when translating an item using the selector tool, then we will only do this for the
141     // first point and store the collection for later use. This dramatically improves the performance
142         if (first_point) {
143                 _points_to_snap_to->clear();
144             for (std::list<SPItem*>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
145                 
146                 NR::Matrix i2doc(NR::identity());
147                 SPItem *root_item = NULL;
148                 if (SP_IS_USE(*i)) {
149                     i2doc = sp_use_get_root_transform(SP_USE(*i));
150                     root_item = sp_use_root(SP_USE(*i));
151                 } else { 
152                     i2doc = sp_item_i2doc_affine(*i);
153                     root_item = *i;
154                 }
155                 
156                 SPCurve *curve = NULL;
157                 
158                 if (SP_IS_SHAPE(root_item)) {
159                     SPShape const *sh = SP_SHAPE(root_item);
160                     curve = sh->curve;
161                 } else if (SP_IS_IMAGE(root_item)) {
162                     SPImage const *im = SP_IMAGE(root_item);
163                     curve = im->curve;
164                 }
165                     
166                         //Collect all nodes so we can snap to them
167                 if (_snap_to_itemnode) {
168                         if (!(_strict_snapping && !p_is_a_node) || p_is_a_guide) {
169                                 if (curve) {
170                                     int j = 0;
171                                     while (SP_CURVE_BPATH(curve)[j].code != NR_END) {        
172                                         /* Get this node in desktop coordinates */
173                                         NArtBpath const &bp = SP_CURVE_BPATH(curve)[j];
174                                         _points_to_snap_to->push_back(desktop->doc2dt(bp.c(3) * i2doc));
175                                         j++;
176                                     }
177                                     if (_include_item_center) {
178                                         _points_to_snap_to->push_back(root_item->getCenter());  
179                                     }                       
180                                 }
181                         }
182                 }
183                 
184                 //Collect the bounding box's corners so we can snap to them
185                 if (_snap_to_bboxnode) {
186                         if (!(_strict_snapping && !p_is_a_bbox) || p_is_a_guide) {
187                                 NR::Maybe<NR::Rect> b = sp_item_bbox_desktop(root_item, bbox_type);
188                                 if (b) {
189                                         for ( unsigned k = 0 ; k < 4 ; k++ ) {
190                                             _points_to_snap_to->push_back(b->corner(k));
191                                         }
192                                 }
193                         }        
194                 }
195             }
196         }
197     
198     //Do the snapping, using all the nodes and corners collected above
199     for (std::list<NR::Point>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
200             /* Try to snap to this node of the path */
201         NR::Coord dist = NR_HUGE;
202         NR::Point snapped_point;
203         switch (snap_dim) {
204                 case SNAP_X:
205                         dist = fabs((*k)[NR::X] - p[NR::X]);
206                         snapped_point = NR::Point((*k)[NR::X], p[NR::Y]); 
207                         break;
208                 case SNAP_Y:
209                         dist = fabs((*k)[NR::Y] - p[NR::Y]);
210                         snapped_point = NR::Point(p[NR::X], (*k)[NR::Y]);
211                         break;
212                 case SNAP_XY:
213                         dist = NR::L2(*k - p);
214                         snapped_point = *k;
215                         break;
216         }
217         if (dist < getDistance() && dist < s.getDistance()) {
218             s = SnappedPoint(snapped_point, dist);
219         }       
220     }
224 void Inkscape::ObjectSnapper::_snapPaths(Inkscape::Snapper::PointType const &t,
225                                                                                  Inkscape::SnappedPoint &s,
226                                          NR::Point const &p,
227                                          bool const &first_point) const
229     /* FIXME: this seems like a hack.  Perhaps Snappers should be
230     ** in SPDesktop rather than SPNamedView?
231     */
232     SPDesktop const *desktop = SP_ACTIVE_DESKTOP;
234     NR::Point const p_doc = desktop->dt2doc(p);
235     
236     // Determine the type of bounding box we should snap to
237     SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX; 
238         if (_snap_to_bboxpath) {        
239         gchar const *prefs_bbox = prefs_get_string_attribute("tools.select", "bounding_box");
240                 bbox_type = (prefs_bbox != NULL && strcmp(prefs_bbox, "geometric")==0)? SPItem::GEOMETRIC_BBOX : SPItem::APPROXIMATE_BBOX;        
241         }
242         
243         bool p_is_a_node = t & Inkscape::Snapper::SNAPPOINT_NODE;        
244         
245     // Now, let's first collect all paths to snap to. If we have a whole bunch of points to snap,
246     // e.g. when translating an item using the selector tool, then we will only do this for the
247     // first point and store the collection for later use. This dramatically improves the performance
248     if (first_point) {      
249             for (std::list<Path*>::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
250                 delete *k;
251             }
252             _paths_to_snap_to->clear();
253             for (std::list<SPItem*>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
254         
255                 /* Transform the requested snap point to this item's coordinates */
256                 NR::Matrix i2doc(NR::identity());
257                 SPItem *root_item = NULL;
258                 /* We might have a clone at hand, so make sure we get the root item */
259                 if (SP_IS_USE(*i)) {
260                     i2doc = sp_use_get_root_transform(SP_USE(*i));
261                     root_item = sp_use_root(SP_USE(*i));
262                 } else {
263                     i2doc = sp_item_i2doc_affine(*i);
264                     root_item = *i;
265                 }
266                 
267                 //Build a list of all paths considered for snapping to          
268                 
269                 //Add the item's path to snap to
270                 if (_snap_to_itempath) {
271                         if (!(_strict_snapping && !p_is_a_node)) {
272                                 _paths_to_snap_to->push_back(Path_for_item(root_item, true, true));
273                         }
274                 }
275                         
276                 //Add the item's bounding box to snap to
277                 if (_snap_to_bboxpath) {
278                         if (!(_strict_snapping && p_is_a_node)) {               
279                                 //This will get ugly... rect -> curve -> bpath
280                                 NRRect rect;
281                                 sp_item_invoke_bbox(root_item, &rect, i2doc, TRUE, bbox_type);
282                                 NR::Maybe<NR::Rect> bbox = rect.upgrade();
283                                 SPCurve *curve = sp_curve_new_from_rect(bbox);
284                                 if (curve) {
285                                         NArtBpath *bpath = SP_CURVE_BPATH(curve);
286                                         if (bpath) {
287                                                 Path *path = bpath_to_Path(bpath);  
288                                                 if (path) {
289                                                         _paths_to_snap_to->push_back(path);
290                                                 }
291                                                 delete bpath;
292                                         }    
293                                         delete curve;                                   
294                                 }
295                         }
296                 }
297             }
298     }
299         
300     //Now we can finally do the real snapping, using the paths collected above        
301     for (std::list<Path*>::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
302         if (*k) {
303             if (first_point) {
304                 (*k)->ConvertWithBackData(0.01); //This is extremely time consuming!
305             }
306         
307                 /* Look for the nearest position on this SPItem to our snap point */
308                 NR::Maybe<Path::cut_position> const o = get_nearest_position_on_Path(*k, p_doc);
309                 if (o && o->t >= 0 && o->t <= 1) {
310         
311                     /* Convert the nearest point back to desktop coordinates */
312                     NR::Point const o_it = get_point_on_Path(*k, o->piece, o->t);                           
313                     NR::Point const o_dt = desktop->doc2dt(o_it);
314                                 
315                     NR::Coord const dist = NR::L2(o_dt - p);
316                     if (dist < getDistance() && dist < s.getDistance()) {
317                         s = SnappedPoint(o_dt, dist);
318                     }
319                 }
320         }        
321     }
325 Inkscape::SnappedPoint Inkscape::ObjectSnapper::_doFreeSnap(Inkscape::Snapper::PointType const &t,
326                                                                                                                         NR::Point const &p,
327                                                                                                                         bool const &first_point,
328                                                                         std::vector<NR::Point> &points_to_snap,
329                                                             std::list<SPItem const *> const &it) const
331     if ( NULL == _named_view ) {
332         return SnappedPoint(p, NR_HUGE);
333     }
335             /* Get a list of all the SPItems that we will try to snap to */
336     _findCandidates(sp_document_root(_named_view->document), it, first_point, points_to_snap, SNAP_XY);
338         SnappedPoint s(p, NR_HUGE);
340     if (_snap_to_itemnode || _snap_to_bboxnode) {
341         _snapNodes(t, s, p, first_point, SNAP_XY);
342     }
343     if (_snap_to_itempath || _snap_to_bboxpath) {
344         _snapPaths(t, s, p, first_point);
345     }
347     return s;
352 Inkscape::SnappedPoint Inkscape::ObjectSnapper::_doConstrainedSnap(Inkscape::Snapper::PointType const &t,
353                                                                                                                                    NR::Point const &p,
354                                                                                                                                    bool const &first_point,
355                                                                                    std::vector<NR::Point> &points_to_snap,
356                                                                    ConstraintLine const &c,
357                                                                    std::list<SPItem const *> const &it) const
359     /* FIXME: this needs implementing properly; I think we have to do the
360     ** intersection of c with the objects.
361     */
362     return _doFreeSnap(t, p, first_point, points_to_snap, it);
367 Inkscape::SnappedPoint Inkscape::ObjectSnapper::guideSnap(NR::Point const &p,
368                                                                                                                   DimensionToSnap const snap_dim) const
370     if ( NULL == _named_view ) {
371         return SnappedPoint(p, NR_HUGE);
372     }
374     /* Get a list of all the SPItems that we will try to snap to */
375     std::list<SPItem*> cand;
376     std::list<SPItem const *> const it; //just an empty list
377     
378     std::vector<NR::Point> points_to_snap;
379     points_to_snap.push_back(p);
380     
381     _findCandidates(sp_document_root(_named_view->document), it, true, points_to_snap, snap_dim);
383     SnappedPoint s(p, NR_HUGE);
384     _snapNodes(Inkscape::Snapper::SNAPPOINT_GUIDE, s, p, true, snap_dim);
385     
386     return s;
389 /**
390  *  \return true if this Snapper will snap at least one kind of point.
391  */
392 bool Inkscape::ObjectSnapper::ThisSnapperMightSnap() const
394     bool snap_to_something = _snap_to_itempath || _snap_to_itemnode || _snap_to_bboxpath || _snap_to_bboxnode;
395     return (_enabled && _snap_from != 0 && snap_to_something);
399 /*
400   Local Variables:
401   mode:c++
402   c-file-style:"stroustrup"
403   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
404   indent-tabs-mode:nil
405   fill-column:99
406   End:
407 */
408 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :