Code

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