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