1 /** @file
2 * Node selection - implementation
3 */
4 /* Authors:
5 * Krzysztof KosiĆski <tweenk.pl@gmail.com>
6 *
7 * Copyright (C) 2009 Authors
8 * Released under GNU GPL, read the file 'COPYING' for more information
9 */
11 #include <boost/none.hpp>
12 #include <2geom/transforms.h>
13 #include "desktop.h"
14 #include "preferences.h"
15 #include "ui/tool/control-point-selection.h"
16 #include "ui/tool/event-utils.h"
17 #include "ui/tool/selectable-control-point.h"
18 #include "ui/tool/transform-handle-set.h"
20 namespace Inkscape {
21 namespace UI {
23 /**
24 * @class ControlPointSelection
25 * @brief Group of selected control points.
26 *
27 * Some operations can be performed on all selected points regardless of their type, therefore
28 * this class is also a Manipulator. It handles the transformations of points using
29 * the keyboard.
30 *
31 * The exposed interface is similar to that of an STL set. Internally, a hash map is used.
32 * @todo Correct iterators (that don't expose the connection list)
33 */
35 /** @var ControlPointSelection::signal_update
36 * Fires when the display needs to be updated to reflect changes.
37 */
38 /** @var ControlPointSelection::signal_point_changed
39 * Fires when a control point is added to or removed from the selection.
40 * The first param contains a pointer to the control point that changed sel. state.
41 * The second says whether the point is currently selected.
42 */
43 /** @var ControlPointSelection::signal_commit
44 * Fires when a change that needs to be committed to XML happens.
45 */
47 ControlPointSelection::ControlPointSelection(SPDesktop *d, SPCanvasGroup *th_group)
48 : Manipulator(d)
49 , _handles(new TransformHandleSet(d, th_group))
50 , _dragging(false)
51 , _handles_visible(true)
52 , _one_node_handles(false)
53 {
54 signal_update.connect( sigc::bind(
55 sigc::mem_fun(*this, &ControlPointSelection::_updateTransformHandles),
56 true));
57 ControlPoint::signal_mouseover_change.connect(
58 sigc::hide(
59 sigc::mem_fun(*this, &ControlPointSelection::_mouseoverChanged)));
60 _handles->signal_transform.connect(
61 sigc::mem_fun(*this, &ControlPointSelection::transform));
62 _handles->signal_commit.connect(
63 sigc::mem_fun(*this, &ControlPointSelection::_commitHandlesTransform));
64 }
66 ControlPointSelection::~ControlPointSelection()
67 {
68 clear();
69 delete _handles;
70 }
72 /** Add a control point to the selection. */
73 std::pair<ControlPointSelection::iterator, bool> ControlPointSelection::insert(const value_type &x)
74 {
75 iterator found = _points.find(x);
76 if (found != _points.end()) {
77 return std::pair<iterator, bool>(found, false);
78 }
80 found = _points.insert(x).first;
82 x->updateState();
83 _pointChanged(x, true);
85 return std::pair<iterator, bool>(found, true);
86 }
88 /** Remove a point from the selection. */
89 void ControlPointSelection::erase(iterator pos)
90 {
91 SelectableControlPoint *erased = *pos;
92 _points.erase(pos);
93 erased->updateState();
94 _pointChanged(erased, false);
95 }
96 ControlPointSelection::size_type ControlPointSelection::erase(const key_type &k)
97 {
98 iterator pos = _points.find(k);
99 if (pos == _points.end()) return 0;
100 erase(pos);
101 return 1;
102 }
103 void ControlPointSelection::erase(iterator first, iterator last)
104 {
105 while (first != last) erase(first++);
106 }
108 /** Remove all points from the selection, making it empty. */
109 void ControlPointSelection::clear()
110 {
111 for (iterator i = begin(); i != end(); )
112 erase(i++);
113 }
115 /** Select all points that this selection can contain. */
116 void ControlPointSelection::selectAll()
117 {
118 for (set_type::iterator i = _all_points.begin(); i != _all_points.end(); ++i) {
119 insert(*i);
120 }
121 }
122 /** Select all points inside the given rectangle (in desktop coordinates). */
123 void ControlPointSelection::selectArea(Geom::Rect const &r)
124 {
125 for (set_type::iterator i = _all_points.begin(); i != _all_points.end(); ++i) {
126 if (r.contains(**i))
127 insert(*i);
128 }
129 }
130 /** Unselect all selected points and select all unselected points. */
131 void ControlPointSelection::invertSelection()
132 {
133 for (set_type::iterator i = _all_points.begin(); i != _all_points.end(); ++i) {
134 if ((*i)->selected()) erase(*i);
135 else insert(*i);
136 }
137 }
138 void ControlPointSelection::spatialGrow(SelectableControlPoint *origin, int dir)
139 {
140 bool grow = (dir > 0);
141 Geom::Point p = origin->position();
142 double best_dist = grow ? HUGE_VAL : 0;
143 SelectableControlPoint *match = NULL;
144 for (set_type::iterator i = _all_points.begin(); i != _all_points.end(); ++i) {
145 bool selected = (*i)->selected();
146 if (grow && !selected) {
147 double dist = Geom::distance((*i)->position(), p);
148 if (dist < best_dist) {
149 best_dist = dist;
150 match = *i;
151 }
152 }
153 if (!grow && selected) {
154 double dist = Geom::distance((*i)->position(), p);
155 // use >= to also deselect the origin node when it's the last one selected
156 if (dist >= best_dist) {
157 best_dist = dist;
158 match = *i;
159 }
160 }
161 }
162 if (match) {
163 if (grow) insert(match);
164 else erase(match);
165 }
166 }
168 /** Transform all selected control points by the given affine transformation. */
169 void ControlPointSelection::transform(Geom::Matrix const &m)
170 {
171 for (iterator i = _points.begin(); i != _points.end(); ++i) {
172 SelectableControlPoint *cur = *i;
173 cur->transform(m);
174 }
175 _updateBounds();
176 // TODO preserving the rotation radius needs some rethinking...
177 if (_rot_radius) (*_rot_radius) *= m.descrim();
178 if (_mouseover_rot_radius) (*_mouseover_rot_radius) *= m.descrim();
179 signal_update.emit();
180 }
182 /** Align control points on the specified axis. */
183 void ControlPointSelection::align(Geom::Dim2 axis)
184 {
185 if (empty()) return;
186 Geom::Dim2 d = static_cast<Geom::Dim2>((axis + 1) % 2);
188 Geom::OptInterval bound;
189 for (iterator i = _points.begin(); i != _points.end(); ++i) {
190 bound.unionWith(Geom::OptInterval((*i)->position()[d]));
191 }
193 double new_coord = bound->middle();
194 for (iterator i = _points.begin(); i != _points.end(); ++i) {
195 Geom::Point pos = (*i)->position();
196 pos[d] = new_coord;
197 (*i)->move(pos);
198 }
199 }
201 /** Equdistantly distribute control points by moving them in the specified dimension. */
202 void ControlPointSelection::distribute(Geom::Dim2 d)
203 {
204 if (empty()) return;
206 // this needs to be a multimap, otherwise it will fail when some points have the same coord
207 typedef std::multimap<double, SelectableControlPoint*> SortMap;
209 SortMap sm;
210 Geom::OptInterval bound;
211 // first we insert all points into a multimap keyed by the aligned coord to sort them
212 // simultaneously we compute the extent of selection
213 for (iterator i = _points.begin(); i != _points.end(); ++i) {
214 Geom::Point pos = (*i)->position();
215 sm.insert(std::make_pair(pos[d], (*i)));
216 bound.unionWith(Geom::OptInterval(pos[d]));
217 }
219 // now we iterate over the multimap and set aligned positions.
220 double step = size() == 1 ? 0 : bound->extent() / (size() - 1);
221 double start = bound->min();
222 unsigned num = 0;
223 for (SortMap::iterator i = sm.begin(); i != sm.end(); ++i, ++num) {
224 Geom::Point pos = i->second->position();
225 pos[d] = start + num * step;
226 i->second->move(pos);
227 }
228 }
230 /** Get the bounds of the selection.
231 * @return Smallest rectangle containing the positions of all selected points,
232 * or nothing if the selection is empty */
233 Geom::OptRect ControlPointSelection::pointwiseBounds()
234 {
235 return _bounds;
236 }
238 Geom::OptRect ControlPointSelection::bounds()
239 {
240 return size() == 1 ? (*_points.begin())->bounds() : _bounds;
241 }
243 void ControlPointSelection::showTransformHandles(bool v, bool one_node)
244 {
245 _one_node_handles = one_node;
246 _handles_visible = v;
247 _updateTransformHandles(false);
248 }
250 void ControlPointSelection::hideTransformHandles()
251 {
252 _handles->setVisible(false);
253 }
254 void ControlPointSelection::restoreTransformHandles()
255 {
256 _updateTransformHandles(true);
257 }
259 void ControlPointSelection::toggleTransformHandlesMode()
260 {
261 if (_handles->mode() == TransformHandleSet::MODE_SCALE) {
262 _handles->setMode(TransformHandleSet::MODE_ROTATE_SKEW);
263 if (size() == 1) _handles->rotationCenter().setVisible(false);
264 } else {
265 _handles->setMode(TransformHandleSet::MODE_SCALE);
266 }
267 }
269 void ControlPointSelection::_pointGrabbed()
270 {
271 hideTransformHandles();
272 _dragging = true;
273 }
275 void ControlPointSelection::_pointDragged(Geom::Point const &old_pos, Geom::Point &new_pos,
276 GdkEventMotion */*event*/)
277 {
278 Geom::Point delta = new_pos - old_pos;
279 for (iterator i = _points.begin(); i != _points.end(); ++i) {
280 SelectableControlPoint *cur = (*i);
281 cur->move(cur->position() + delta);
282 }
283 _handles->rotationCenter().move(_handles->rotationCenter().position() + delta);
284 signal_update.emit();
285 }
287 void ControlPointSelection::_pointUngrabbed()
288 {
289 _dragging = false;
290 _grabbed_point = NULL;
291 _updateBounds();
292 restoreTransformHandles();
293 signal_commit.emit(COMMIT_MOUSE_MOVE);
294 }
296 bool ControlPointSelection::_pointClicked(SelectableControlPoint *p, GdkEventButton *event)
297 {
298 // clicking a selected node should toggle the transform handles between rotate and scale mode,
299 // if they are visible
300 if (held_no_modifiers(*event) && _handles_visible && p->selected()) {
301 toggleTransformHandlesMode();
302 return true;
303 }
304 return false;
305 }
307 void ControlPointSelection::_pointChanged(SelectableControlPoint *p, bool selected)
308 {
309 _updateBounds();
310 _updateTransformHandles(false);
311 if (_bounds)
312 _handles->rotationCenter().move(_bounds->midpoint());
314 signal_point_changed.emit(p, selected);
315 }
317 void ControlPointSelection::_mouseoverChanged()
318 {
319 _mouseover_rot_radius = boost::none;
320 }
322 void ControlPointSelection::_updateBounds()
323 {
324 _rot_radius = boost::none;
325 _bounds = Geom::OptRect();
326 for (iterator i = _points.begin(); i != _points.end(); ++i) {
327 SelectableControlPoint *cur = (*i);
328 Geom::Point p = cur->position();
329 if (!_bounds) {
330 _bounds = Geom::Rect(p, p);
331 } else {
332 _bounds->expandTo(p);
333 }
334 }
335 }
337 void ControlPointSelection::_updateTransformHandles(bool preserve_center)
338 {
339 if (_dragging) return;
341 if (_handles_visible && size() > 1) {
342 _handles->setBounds(*bounds(), preserve_center);
343 _handles->setVisible(true);
344 } else if (_one_node_handles && size() == 1) { // only one control point in selection
345 SelectableControlPoint *p = *begin();
346 _handles->setBounds(p->bounds());
347 _handles->rotationCenter().move(p->position());
348 _handles->rotationCenter().setVisible(false);
349 _handles->setVisible(true);
350 } else {
351 _handles->setVisible(false);
352 }
353 }
355 /** Moves the selected points along the supplied unit vector according to
356 * the modifier state of the supplied event. */
357 bool ControlPointSelection::_keyboardMove(GdkEventKey const &event, Geom::Point const &dir)
358 {
359 if (held_control(event)) return false;
360 unsigned num = 1 + combine_key_events(shortcut_key(event), 0);
362 Geom::Point delta = dir * num;
363 if (held_shift(event)) delta *= 10;
364 if (held_alt(event)) {
365 delta /= _desktop->current_zoom();
366 } else {
367 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
368 double nudge = prefs->getDoubleLimited("/options/nudgedistance/value", 2, 0, 1000);
369 delta *= nudge;
370 }
372 transform(Geom::Translate(delta));
373 if (fabs(dir[Geom::X]) > 0) {
374 signal_commit.emit(COMMIT_KEYBOARD_MOVE_X);
375 } else {
376 signal_commit.emit(COMMIT_KEYBOARD_MOVE_Y);
377 }
378 return true;
379 }
381 /** @brief Computes the distance to the farthest corner of the bounding box.
382 * Used to determine what it means to "rotate by one pixel". */
383 double ControlPointSelection::_rotationRadius(Geom::Point const &rc)
384 {
385 if (empty()) return 1.0; // some safe value
386 Geom::Rect b = *bounds();
387 double maxlen = 0;
388 for (unsigned i = 0; i < 4; ++i) {
389 double len = Geom::distance(b.corner(i), rc);
390 if (len > maxlen) maxlen = len;
391 }
392 return maxlen;
393 }
395 /** Rotates the selected points in the given direction according to the modifier state
396 * from the supplied event.
397 * @param event Key event to take modifier state from
398 * @param dir Direction of rotation (math convention: 1 = counterclockwise, -1 = clockwise)
399 */
400 bool ControlPointSelection::_keyboardRotate(GdkEventKey const &event, int dir)
401 {
402 if (empty()) return false;
404 Geom::Point rc;
406 // rotate around the mouseovered point, or the selection's rotation center
407 // if nothing is mouseovered
408 double radius;
409 SelectableControlPoint *scp =
410 dynamic_cast<SelectableControlPoint*>(ControlPoint::mouseovered_point);
411 if (scp) {
412 rc = scp->position();
413 if (!_mouseover_rot_radius) {
414 _mouseover_rot_radius = _rotationRadius(rc);
415 }
416 radius = *_mouseover_rot_radius;
417 } else {
418 rc = _handles->rotationCenter();
419 if (!_rot_radius) {
420 _rot_radius = _rotationRadius(rc);
421 }
422 radius = *_rot_radius;
423 }
425 double angle;
426 if (held_alt(event)) {
427 // Rotate by "one pixel". We interpret this as rotating by an angle that causes
428 // the topmost point of a circle circumscribed about the selection's bounding box
429 // to move on an arc 1 screen pixel long.
430 angle = atan2(1.0 / _desktop->current_zoom(), radius) * dir;
431 } else {
432 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
433 int snaps = prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000);
434 angle = M_PI * dir / snaps;
435 }
437 // translate to origin, rotate, translate back to original position
438 Geom::Matrix m = Geom::Translate(-rc)
439 * Geom::Rotate(angle) * Geom::Translate(rc);
440 transform(m);
441 signal_commit.emit(COMMIT_KEYBOARD_ROTATE);
442 return true;
443 }
446 bool ControlPointSelection::_keyboardScale(GdkEventKey const &event, int dir)
447 {
448 if (empty()) return false;
450 double maxext = bounds()->maxExtent();
451 if (Geom::are_near(maxext, 0)) return false;
453 Geom::Point center;
454 SelectableControlPoint *scp =
455 dynamic_cast<SelectableControlPoint*>(ControlPoint::mouseovered_point);
456 if (scp) {
457 center = scp->position();
458 } else {
459 center = _handles->rotationCenter().position();
460 }
462 double length_change;
463 if (held_alt(event)) {
464 // Scale by "one pixel". It means shrink/grow 1px for the larger dimension
465 // of the bounding box.
466 length_change = 1.0 / _desktop->current_zoom() * dir;
467 } else {
468 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
469 length_change = prefs->getDoubleLimited("/options/defaultscale/value", 2, 1, 1000);
470 length_change *= dir;
471 }
472 double scale = (maxext + length_change) / maxext;
474 Geom::Matrix m = Geom::Translate(-center) * Geom::Scale(scale) * Geom::Translate(center);
475 transform(m);
476 signal_commit.emit(COMMIT_KEYBOARD_SCALE_UNIFORM);
477 return true;
478 }
480 bool ControlPointSelection::_keyboardFlip(Geom::Dim2 d)
481 {
482 if (empty()) return false;
484 Geom::Scale scale_transform(1, 1);
485 if (d == Geom::X) {
486 scale_transform = Geom::Scale(-1, 1);
487 } else {
488 scale_transform = Geom::Scale(1, -1);
489 }
491 SelectableControlPoint *scp =
492 dynamic_cast<SelectableControlPoint*>(ControlPoint::mouseovered_point);
493 Geom::Point center = scp ? scp->position() : _handles->rotationCenter().position();
495 Geom::Matrix m = Geom::Translate(-center) * scale_transform * Geom::Translate(center);
496 transform(m);
497 signal_commit.emit(d == Geom::X ? COMMIT_FLIP_X : COMMIT_FLIP_Y);
498 return true;
499 }
501 void ControlPointSelection::_commitHandlesTransform(CommitEvent ce)
502 {
503 _updateBounds();
504 _updateTransformHandles(true);
505 signal_commit.emit(ce);
506 }
508 bool ControlPointSelection::event(GdkEvent *event)
509 {
510 // implement generic event handling that should apply for all control point selections here;
511 // for example, keyboard moves and transformations. This way this functionality doesn't need
512 // to be duplicated in many places
513 // Later split out so that it can be reused in object selection
515 switch (event->type) {
516 case GDK_KEY_PRESS:
517 // do not handle key events if the selection is empty
518 if (empty()) break;
520 switch(shortcut_key(event->key)) {
521 // moves
522 case GDK_Up:
523 case GDK_KP_Up:
524 case GDK_KP_8:
525 return _keyboardMove(event->key, Geom::Point(0, 1));
526 case GDK_Down:
527 case GDK_KP_Down:
528 case GDK_KP_2:
529 return _keyboardMove(event->key, Geom::Point(0, -1));
530 case GDK_Right:
531 case GDK_KP_Right:
532 case GDK_KP_6:
533 return _keyboardMove(event->key, Geom::Point(1, 0));
534 case GDK_Left:
535 case GDK_KP_Left:
536 case GDK_KP_4:
537 return _keyboardMove(event->key, Geom::Point(-1, 0));
539 // rotates
540 case GDK_bracketleft:
541 return _keyboardRotate(event->key, 1);
542 case GDK_bracketright:
543 return _keyboardRotate(event->key, -1);
545 // scaling
546 case GDK_less:
547 case GDK_comma:
548 return _keyboardScale(event->key, -1);
549 case GDK_greater:
550 case GDK_period:
551 return _keyboardScale(event->key, 1);
553 // TODO: skewing
555 // flipping
556 // NOTE: H is horizontal flip, while Shift+H switches transform handle mode!
557 case GDK_h:
558 case GDK_H:
559 if (held_shift(event->key)) {
560 toggleTransformHandlesMode();
561 return true;
562 }
563 // any modifiers except shift should cause no action
564 if (held_any_modifiers(event->key)) break;
565 return _keyboardFlip(Geom::X);
566 case GDK_v:
567 case GDK_V:
568 if (held_any_modifiers(event->key)) break;
569 return _keyboardFlip(Geom::Y);
570 default: break;
571 }
572 break;
573 default: break;
574 }
575 return false;
576 }
578 } // namespace UI
579 } // namespace Inkscape
581 /*
582 Local Variables:
583 mode:c++
584 c-file-style:"stroustrup"
585 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
586 indent-tabs-mode:nil
587 fill-column:99
588 End:
589 */
590 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :