Code

10e0c43d4bef3f6529b7a9d2f38eb0c53c464be4
[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;
44     _points_to_snap_to->clear();
45     delete _points_to_snap_to;
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;
72         if (first_point) {
73             _candidates->clear();
74         }
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))) {
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                 }
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 bool 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     bool success = false;
124     // Determine the type of bounding box we should snap to
125     SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
126     if (_snap_to_bboxnode) {
127         gchar const *prefs_bbox = prefs_get_string_attribute("tools.select", "bounding_box");
128         bbox_type = (prefs_bbox != NULL && strcmp(prefs_bbox, "geometric")==0)? SPItem::GEOMETRIC_BBOX : SPItem::APPROXIMATE_BBOX;
129     }
131     bool p_is_a_node = t & Inkscape::Snapper::SNAPPOINT_NODE;
132     bool p_is_a_bbox = t & Inkscape::Snapper::SNAPPOINT_BBOX;
133     bool p_is_a_guide = t & Inkscape::Snapper::SNAPPOINT_GUIDE;
135     // A point considered for snapping should be either a node, a bbox corner or a guide. Pick only ONE!
136     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));
138     // Now, let's first collect all points to snap to. If we have a whole bunch of points to snap,
139     // e.g. when translating an item using the selector tool, then we will only do this for the
140     // first point and store the collection for later use. This dramatically improves the performance
141     if (first_point) {
142         _points_to_snap_to->clear();
143         for (std::vector<SPItem*>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
145             //NR::Matrix i2doc(NR::identity());
146             SPItem *root_item = *i;
147             if (SP_IS_USE(*i)) {
148                 root_item = sp_use_root(SP_USE(*i));
149             }
151             //Collect all nodes so we can snap to them
152             if (_snap_to_itemnode) {
153                 if (!(_strict_snapping && !p_is_a_node) || p_is_a_guide) {
154                     sp_item_snappoints(root_item, _include_item_center, SnapPointsIter(*_points_to_snap_to));
155                 }
156             }
158             //Collect the bounding box's corners so we can snap to them
159             if (_snap_to_bboxnode) {
160                 if (!(_strict_snapping && !p_is_a_bbox) || p_is_a_guide) {
161                     NR::Maybe<NR::Rect> b = sp_item_bbox_desktop(root_item, bbox_type);
162                     if (b) {
163                         for ( unsigned k = 0 ; k < 4 ; k++ ) {
164                             _points_to_snap_to->push_back(b->corner(k));
165                         }
166                     }
167                 }
168             }
169         }
170     }
172     //Do the snapping, using all the nodes and corners collected above
173     for (std::vector<NR::Point>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
174         /* Try to snap to this node of the path */
175         NR::Coord dist = NR_HUGE;
176         NR::Point snapped_point;
177         switch (snap_dim) {
178             case SNAP_X:
179                 dist = fabs((*k)[NR::X] - p[NR::X]);
180                 snapped_point = NR::Point((*k)[NR::X], p[NR::Y]);
181                 break;
182             case SNAP_Y:
183                 dist = fabs((*k)[NR::Y] - p[NR::Y]);
184                 snapped_point = NR::Point(p[NR::X], (*k)[NR::Y]);
185                 break;
186             case SNAP_XY:
187                 dist = NR::L2(*k - p);
188                 snapped_point = *k;
189                 break;
190         }
192         if (dist < getDistance() && dist < s.getDistance()) {
193             s = SnappedPoint(snapped_point, dist);
194             success = true;
195         }
196     }
198     return success;
202 bool Inkscape::ObjectSnapper::_snapPaths(Inkscape::Snapper::PointType const &t,
203                                          Inkscape::SnappedPoint &s,
204                                          NR::Point const &p,
205                                          bool const &first_point) const
207     bool success = false;
208     /* FIXME: this seems like a hack.  Perhaps Snappers should be
209     ** in SPDesktop rather than SPNamedView?
210     */
211     SPDesktop const *desktop = SP_ACTIVE_DESKTOP;
213     NR::Point const p_doc = desktop->dt2doc(p);
215     // Determine the type of bounding box we should snap to
216     SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
217     if (_snap_to_bboxpath) {
218         gchar const *prefs_bbox = prefs_get_string_attribute("tools.select", "bounding_box");
219         bbox_type = (prefs_bbox != NULL && strcmp(prefs_bbox, "geometric")==0)? SPItem::GEOMETRIC_BBOX : SPItem::APPROXIMATE_BBOX;
220     }
222     bool p_is_a_node = t & Inkscape::Snapper::SNAPPOINT_NODE;
224     // Now, let's first collect all paths to snap to. If we have a whole bunch of points to snap,
225     // e.g. when translating an item using the selector tool, then we will only do this for the
226     // first point and store the collection for later use. This dramatically improves the performance
227     if (first_point) {
228         for (std::vector<Path*>::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
229             delete *k;
230         }
231         _paths_to_snap_to->clear();
232         for (std::vector<SPItem*>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
234             /* Transform the requested snap point to this item's coordinates */
235             NR::Matrix i2doc(NR::identity());
236             SPItem *root_item = NULL;
237             /* We might have a clone at hand, so make sure we get the root item */
238             if (SP_IS_USE(*i)) {
239                 i2doc = sp_use_get_root_transform(SP_USE(*i));
240                 root_item = sp_use_root(SP_USE(*i));
241             } else {
242                 i2doc = sp_item_i2doc_affine(*i);
243                 root_item = *i;
244             }
246             //Build a list of all paths considered for snapping to
248             //Add the item's path to snap to
249             if (_snap_to_itempath) {
250                 if (!(_strict_snapping && !p_is_a_node)) {
251                     // Snapping to the path of characters is very cool, but for a large
252                     // chunk of text this will take ages! So limit snapping to text paths
253                     // containing max. 240 characters. Snapping the bbox will not be affected
254                     bool very_lenghty_prose = false;
255                     if (SP_IS_TEXT(root_item) || SP_IS_FLOWTEXT(root_item)) {
256                         very_lenghty_prose =  sp_text_get_length(SP_TEXT(root_item)) > 240;
257                     }
258                     // On my AMD 3000+, the snapping lag becomes annoying at approx. 240 chars
259                     // which corresponds to a lag of 500 msec. This is for snapping a rect
260                     // to a single line of text.
262                     // Snapping for example to a traced bitmap is also very stressing for
263                     // the CPU, so we'll only snap to paths having no more than 500 nodes
264                     // This also leads to a lag of approx. 500 msec (in my lousy test set-up).
265                     bool very_complex_path = false;
266                     if (SP_IS_PATH(root_item)) {
267                         very_complex_path = sp_nodes_in_path(SP_PATH(root_item)) > 500;
268                     }
270                      if (!very_lenghty_prose && !very_complex_path) {
271                         _paths_to_snap_to->push_back(Path_for_item(root_item, true, true));
272                      }
273                 }
274             }
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     }
300     //Now we can finally do the real snapping, using the paths collected above
301     for (std::vector<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             }
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) {
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);
315                 NR::Coord const dist = NR::L2(o_dt - p);
316                 if (dist < getDistance() && dist < s.getDistance()) {
317                     s = SnappedPoint(o_dt, dist);
318                     success = true;
319                 }
320             }
321         }
322     }
324     return success;
328 void Inkscape::ObjectSnapper::_doFreeSnap(SnappedConstraints &sc,
329                                             Inkscape::Snapper::PointType const &t,
330                                             NR::Point const &p,
331                                             bool const &first_point,
332                                              std::vector<NR::Point> &points_to_snap,
333                                             std::list<SPItem const *> const &it) const
335     if ( NULL == _named_view ) {
336         return;
337     }
339     /* Get a list of all the SPItems that we will try to snap to */
340     if (first_point) {
341         _findCandidates(sp_document_root(_named_view->document), it, first_point, points_to_snap, SNAP_XY);
342     }
344     SnappedPoint s(p, NR_HUGE);
345     bool snapped_to_node = false;
346     bool snapped_to_path = false;
348     if (_snap_to_itemnode || _snap_to_bboxnode) {
349         snapped_to_node = _snapNodes(t, s, p, first_point, SNAP_XY);
350     }
351     if (_snap_to_itempath || _snap_to_bboxpath) {
352         snapped_to_path = _snapPaths(t, s, p, first_point);
353     }
355     if (snapped_to_node || snapped_to_path) {
356         sc.points.push_back(s);
357     }
362 void Inkscape::ObjectSnapper::_doConstrainedSnap( SnappedConstraints &sc,
363                                                   Inkscape::Snapper::PointType const &t,
364                                                   NR::Point const &p,
365                                                   bool const &first_point,
366                                                   std::vector<NR::Point> &points_to_snap,
367                                                   ConstraintLine const &/*c*/,
368                                                   std::list<SPItem const *> const &it) const
370     /* FIXME: this needs implementing properly; I think we have to do the
371     ** intersection of c with the objects.
372     */
373     _doFreeSnap(sc, t, p, first_point, points_to_snap, it);
378 Inkscape::SnappedPoint Inkscape::ObjectSnapper::guideSnap(NR::Point const &p,
379                                                           DimensionToSnap const snap_dim) const
381     if ( NULL == _named_view ) {
382         return SnappedPoint(p, NR_HUGE);
383     }
385     /* Get a list of all the SPItems that we will try to snap to */
386     std::vector<SPItem*> cand;
387     std::list<SPItem const *> const it; //just an empty list
389     std::vector<NR::Point> points_to_snap;
390     points_to_snap.push_back(p);
392     _findCandidates(sp_document_root(_named_view->document), it, true, points_to_snap, snap_dim);
394     SnappedPoint s(p, NR_HUGE);
395     _snapNodes(Inkscape::Snapper::SNAPPOINT_GUIDE, s, p, true, snap_dim);
397     return s;
400 /**
401  *  \return true if this Snapper will snap at least one kind of point.
402  */
403 bool Inkscape::ObjectSnapper::ThisSnapperMightSnap() const
405     bool snap_to_something = _snap_to_itempath || _snap_to_itemnode || _snap_to_bboxpath || _snap_to_bboxnode;
406     return (_enabled && _snap_from != 0 && snap_to_something);
410 /*
411   Local Variables:
412   mode:c++
413   c-file-style:"stroustrup"
414   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
415   indent-tabs-mode:nil
416   fill-column:99
417   End:
418 */
419 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :