1 /** @file
2 * @brief Helper object for transforming selected items
3 */
4 /* Authors:
5 * Lauris Kaplinski <lauris@kaplinski.com>
6 * bulia byak <buliabyak@users.sf.net>
7 * Carl Hetherington <inkscape@carlh.net>
8 * Diederik van Lierop <mail@diedenrezi.nl>
9 *
10 * Copyright (C) 1999-2002 Lauris Kaplinski
11 * Copyright (C) 1999-2008 Authors
12 *
13 * Released under GNU GPL, read the file 'COPYING' for more information
14 */
16 #ifdef HAVE_CONFIG_H
17 # include <config.h>
18 #endif
19 #include <cstring>
20 #include <string>
22 #include <2geom/transforms.h>
23 #include <gdk/gdkkeysyms.h>
24 #include "document.h"
25 #include "sp-namedview.h"
26 #include "desktop.h"
27 #include "desktop-handles.h"
28 #include "desktop-style.h"
29 #include "knot.h"
30 #include "snap.h"
31 #include "selection.h"
32 #include "select-context.h"
33 #include "sp-item.h"
34 #include "sp-item-transform.h"
35 #include "seltrans-handles.h"
36 #include "seltrans.h"
37 #include "selection-chemistry.h"
38 #include "sp-metrics.h"
39 #include "verbs.h"
40 #include <glibmm/i18n.h>
41 #include "display/sp-ctrlline.h"
42 #include "preferences.h"
43 #include "xml/repr.h"
44 #include "mod360.h"
45 #include <2geom/angle.h>
46 #include "display/snap-indicator.h"
49 static void sp_remove_handles(SPKnot *knot[], gint num);
51 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data);
52 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint state, gpointer data);
53 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data);
54 static void sp_sel_trans_handle_new_event(SPKnot *knot, Geom::Point *position, guint32 state, gpointer data);
55 static gboolean sp_sel_trans_handle_request(SPKnot *knot, Geom::Point *p, guint state, gboolean *data);
57 extern GdkPixbuf *handles[];
59 static gboolean sp_seltrans_handle_event(SPKnot *knot, GdkEvent *event, gpointer)
60 {
61 switch (event->type) {
62 case GDK_MOTION_NOTIFY:
63 break;
64 case GDK_KEY_PRESS:
65 if (get_group0_keyval (&event->key) == GDK_space) {
66 /* stamping mode: both mode(show content and outline) operation with knot */
67 if (!SP_KNOT_IS_GRABBED(knot)) {
68 return FALSE;
69 }
70 SPDesktop *desktop = knot->desktop;
71 Inkscape::SelTrans *seltrans = SP_SELECT_CONTEXT(desktop->event_context)->_seltrans;
72 seltrans->stamp();
73 return TRUE;
74 }
75 break;
76 default:
77 break;
78 }
80 return FALSE;
81 }
83 Inkscape::SelTrans::SelTrans(SPDesktop *desktop) :
84 _desktop(desktop),
85 _selcue(desktop),
86 _state(STATE_SCALE),
87 _show(SHOW_CONTENT),
88 _grabbed(false),
89 _show_handles(true),
90 _bbox(),
91 _approximate_bbox(),
92 _absolute_affine(Geom::Scale(1,1)),
93 _opposite(Geom::Point(0,0)),
94 _opposite_for_specpoints(Geom::Point(0,0)),
95 _opposite_for_bboxpoints(Geom::Point(0,0)),
96 _origin_for_specpoints(Geom::Point(0,0)),
97 _origin_for_bboxpoints(Geom::Point(0,0)),
98 _chandle(NULL),
99 _stamp_cache(NULL),
100 _message_context(desktop->messageStack())
101 {
102 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
103 int prefs_bbox = prefs->getBool("/tools/bounding_box");
104 _snap_bbox_type = !prefs_bbox ?
105 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
107 g_return_if_fail(desktop != NULL);
109 for (int i = 0; i < 8; i++) {
110 _shandle[i] = NULL;
111 _rhandle[i] = NULL;
112 }
114 _updateVolatileState();
115 _current_relative_affine.setIdentity();
117 _center_is_set = false; // reread _center from items, or set to bbox midpoint
119 _updateHandles();
121 _selection = sp_desktop_selection(desktop);
123 _norm = sp_canvas_item_new(sp_desktop_controls(desktop),
124 SP_TYPE_CTRL,
125 "anchor", GTK_ANCHOR_CENTER,
126 "mode", SP_CTRL_MODE_COLOR,
127 "shape", SP_CTRL_SHAPE_BITMAP,
128 "size", 13.0,
129 "filled", TRUE,
130 "fill_color", 0x00000000,
131 "stroked", TRUE,
132 "stroke_color", 0x000000a0,
133 "pixbuf", handles[12],
134 NULL);
136 _grip = sp_canvas_item_new(sp_desktop_controls(desktop),
137 SP_TYPE_CTRL,
138 "anchor", GTK_ANCHOR_CENTER,
139 "mode", SP_CTRL_MODE_XOR,
140 "shape", SP_CTRL_SHAPE_CROSS,
141 "size", 7.0,
142 "filled", TRUE,
143 "fill_color", 0xffffff7f,
144 "stroked", TRUE,
145 "stroke_color", 0xffffffff,
146 "pixbuf", handles[12],
147 NULL);
149 sp_canvas_item_hide(_grip);
150 sp_canvas_item_hide(_norm);
152 for (int i = 0; i < 4; i++) {
153 _l[i] = sp_canvas_item_new(sp_desktop_controls(desktop), SP_TYPE_CTRLLINE, NULL);
154 sp_canvas_item_hide(_l[i]);
155 }
157 _sel_changed_connection = _selection->connectChanged(
158 sigc::mem_fun(*this, &Inkscape::SelTrans::_selChanged)
159 );
161 _sel_modified_connection = _selection->connectModified(
162 sigc::mem_fun(*this, &Inkscape::SelTrans::_selModified)
163 );
164 }
166 Inkscape::SelTrans::~SelTrans()
167 {
168 _sel_changed_connection.disconnect();
169 _sel_modified_connection.disconnect();
171 for (unsigned int i = 0; i < 8; i++) {
172 if (_shandle[i]) {
173 g_object_unref(G_OBJECT(_shandle[i]));
174 _shandle[i] = NULL;
175 }
176 if (_rhandle[i]) {
177 g_object_unref(G_OBJECT(_rhandle[i]));
178 _rhandle[i] = NULL;
179 }
180 }
181 if (_chandle) {
182 g_object_unref(G_OBJECT(_chandle));
183 _chandle = NULL;
184 }
186 if (_norm) {
187 gtk_object_destroy(GTK_OBJECT(_norm));
188 _norm = NULL;
189 }
190 if (_grip) {
191 gtk_object_destroy(GTK_OBJECT(_grip));
192 _grip = NULL;
193 }
194 for (int i = 0; i < 4; i++) {
195 if (_l[i]) {
196 gtk_object_destroy(GTK_OBJECT(_l[i]));
197 _l[i] = NULL;
198 }
199 }
201 for (unsigned i = 0; i < _items.size(); i++) {
202 sp_object_unref(SP_OBJECT(_items[i]), NULL);
203 }
205 _items.clear();
206 _items_const.clear();
207 _items_affines.clear();
208 _items_centers.clear();
209 }
211 void Inkscape::SelTrans::resetState()
212 {
213 _state = STATE_SCALE;
214 }
216 void Inkscape::SelTrans::increaseState()
217 {
218 if (_state == STATE_SCALE) {
219 _state = STATE_ROTATE;
220 } else {
221 _state = STATE_SCALE;
222 }
224 _center_is_set = true; // no need to reread center
226 _updateHandles();
227 }
229 void Inkscape::SelTrans::setCenter(Geom::Point const &p)
230 {
231 _center = p;
232 _center_is_set = true;
234 // Write the new center position into all selected items
235 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
236 SPItem *it = (SPItem*)SP_OBJECT(l->data);
237 it->setCenter(p);
238 // only set the value; updating repr and document_done will be done once, on ungrab
239 }
241 _updateHandles();
242 }
244 void Inkscape::SelTrans::grab(Geom::Point const &p, gdouble x, gdouble y, bool show_handles, bool translating)
245 {
246 // While dragging a handle, we will either scale, skew, or rotate and the "translating" parameter will be false
247 // When dragging the selected item itself however, we will translate the selection and that parameter will be true
248 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
249 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
251 g_return_if_fail(!_grabbed);
253 _grabbed = true;
254 _show_handles = show_handles;
255 _updateVolatileState();
256 _current_relative_affine.setIdentity();
258 _changed = false;
260 if (_empty) {
261 return;
262 }
264 for (GSList const *l = selection->itemList(); l; l = l->next) {
265 SPItem *it = (SPItem *)sp_object_ref(SP_OBJECT(l->data), NULL);
266 _items.push_back(it);
267 _items_const.push_back(it);
268 _items_affines.push_back(sp_item_i2d_affine(it));
269 _items_centers.push_back(it->getCenter()); // for content-dragging, we need to remember original centers
270 }
272 _handle_x = x;
273 _handle_y = y;
275 // The selector tool should snap the bbox, special snappoints, and path nodes
276 // (The special points are the handles, center, rotation axis, font baseline, ends of spiral, etc.)
278 // First, determine the bounding box
279 _bbox = selection->bounds(_snap_bbox_type);
280 _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX); // Used for correctly scaling the strokewidth
281 _geometric_bbox = selection->bounds(SPItem::GEOMETRIC_BBOX);
283 _point = p;
284 if (_geometric_bbox) {
285 _point_geom = _geometric_bbox->min() + _geometric_bbox->dimensions() * Geom::Scale(x, y);
286 } else {
287 _point_geom = p;
288 }
290 // Next, get all points to consider for snapping
291 SnapManager const &m = _desktop->namedview->snap_manager;
292 Inkscape::SnapPreferences local_snapprefs = m.snapprefs;
293 local_snapprefs.setSnapToItemNode(true); // We should get at least the cusp nodes here. This might
294 // have been turned off because (for example) the user only want paths as a snap target, not nodes
295 // but as a snap source we still need some nodes though!
296 _snap_points.clear();
297 _snap_points = selection->getSnapPoints(&local_snapprefs);
298 std::vector<std::pair<Geom::Point, int> > snap_points_hull = selection->getSnapPointsConvexHull(&local_snapprefs);
299 if (_snap_points.size() > 200) {
300 /* Snapping a huge number of nodes will take way too long, so limit the number of snappable nodes
301 An average user would rarely ever try to snap such a large number of nodes anyway, because
302 (s)he could hardly discern which node would be snapping */
303 if (prefs->getBool("/options/snapclosestonly/value", false)) {
304 _keepClosestPointOnly(_snap_points, p);
305 } else {
306 _snap_points = snap_points_hull;
307 }
308 // Unfortunately, by now we will have lost the font-baseline snappoints :-(
309 }
311 // Find bbox hulling all special points, which excludes stroke width. Here we need to include the
312 // path nodes, for example because a rectangle which has been converted to a path doesn't have
313 // any other special points
314 Geom::Rect snap_points_bbox;
315 if ( snap_points_hull.empty() == false ) {
316 std::vector<std::pair<Geom::Point, int> >::iterator i = snap_points_hull.begin();
317 snap_points_bbox = Geom::Rect((*i).first, (*i).first);
318 i++;
319 while (i != snap_points_hull.end()) {
320 snap_points_bbox.expandTo((*i).first);
321 i++;
322 }
323 }
325 _bbox_points.clear();
326 _bbox_points_for_translating.clear();
327 // Collect the bounding box's corners and midpoints for each selected item
328 if (m.snapprefs.getSnapModeBBox()) {
329 bool mp = m.snapprefs.getSnapBBoxMidpoints();
330 bool emp = m.snapprefs.getSnapBBoxEdgeMidpoints();
331 // Preferably we'd use the bbox of each selected item, instead of the bbox of the selection as a whole; for translations
332 // this is easy to do, but when snapping the visual bbox while scaling we will have to compensate for the scaling of the
333 // stroke width. (see get_scale_transform_with_stroke()). This however is currently only implemented for a single bbox.
334 // That's why we have both _bbox_points_for_translating and _bbox_points.
335 getBBoxPoints(selection->bounds(_snap_bbox_type), &_bbox_points, false, true, emp, mp);
336 if (((_items.size() > 0) && (_items.size() < 50)) || prefs->getBool("/options/snapclosestonly/value", false)) {
337 // More than 50 items will produce at least 200 bbox points, which might make Inkscape crawl
338 // (see the comment a few lines above). In that case we will use the bbox of the selection as a whole
339 for (unsigned i = 0; i < _items.size(); i++) {
340 getBBoxPoints(sp_item_bbox_desktop(_items[i], _snap_bbox_type), &_bbox_points_for_translating, false, true, emp, mp);
341 }
342 } else {
343 _bbox_points_for_translating = _bbox_points; // use the bbox points of the selection as a whole
344 }
345 }
347 if (_bbox) {
348 // There are two separate "opposites" (i.e. opposite w.r.t. the handle being dragged):
349 // - one for snapping the boundingbox, which can be either visual or geometric
350 // - one for snapping the special points
351 // The "opposite" in case of a geometric boundingbox always coincides with the "opposite" for the special points
352 // These distinct "opposites" are needed in the snapmanager to avoid bugs such as #sf1540195 (in which
353 // a box is caught between two guides)
354 _opposite_for_bboxpoints = _bbox->min() + _bbox->dimensions() * Geom::Scale(1-x, 1-y);
355 _opposite_for_specpoints = snap_points_bbox.min() + snap_points_bbox.dimensions() * Geom::Scale(1-x, 1-y);
356 _opposite = _opposite_for_bboxpoints;
357 }
359 // When snapping the node closest to the mouse pointer is absolutely preferred over the closest snap
360 // (i.e. when weight == 1), then we will not even try to snap to other points and discard those other
361 // points immediately.
363 if (prefs->getBool("/options/snapclosestonly/value", false)) {
364 if (m.snapprefs.getSnapModeNode()) {
365 _keepClosestPointOnly(_snap_points, p);
366 } else {
367 _snap_points.clear(); // don't keep any point
368 }
370 if (m.snapprefs.getSnapModeBBox()) {
371 _keepClosestPointOnly(_bbox_points, p);
372 _keepClosestPointOnly(_bbox_points_for_translating, p);
373 } else {
374 _bbox_points.clear(); // don't keep any point
375 _bbox_points_for_translating.clear();
376 }
378 // Each of the three vectors of snappoints now contains either one snappoint or none at all.
379 if (_snap_points.size() > 1 || _bbox_points.size() > 1 || _bbox_points_for_translating.size() > 1) {
380 g_warning("Incorrect assumption encountered while finding the snap source; nothing serious, but please report to Diederik");
381 }
383 // Now let's reduce this to a single closest snappoint
384 Geom::Coord dsp = _snap_points.size() == 1 ? Geom::L2((_snap_points.at(0)).first - p) : NR_HUGE;
385 Geom::Coord dbbp = _bbox_points.size() == 1 ? Geom::L2((_bbox_points.at(0)).first - p) : NR_HUGE;
386 Geom::Coord dbbpft = _bbox_points_for_translating.size() == 1 ? Geom::L2((_bbox_points_for_translating.at(0)).first - p) : NR_HUGE;
388 if (translating) {
389 _bbox_points.clear();
390 if (dsp > dbbpft) {
391 _snap_points.clear();
392 } else {
393 _bbox_points_for_translating.clear();
394 }
395 } else {
396 _bbox_points_for_translating.clear();
397 if (dsp > dbbp) {
398 _snap_points.clear();
399 } else {
400 _bbox_points.clear();
401 }
402 }
404 if ((_snap_points.size() + _bbox_points.size() + _bbox_points_for_translating.size()) > 1) {
405 g_warning("Checking number of snap sources failed; nothing serious, but please report to Diederik");
406 }
408 // Optionally, show the snap source
409 if (!(_state == STATE_ROTATE && x != 0.5 && y != 0.5)) { // but not when we're dragging a rotation handle, because that won't snap
410 // Now either _bbox_points or _snap_points has a single element, the other one has zero..... or both have zero elements
411 g_assert((_snap_points.size() + _bbox_points.size() + _bbox_points_for_translating.size()) == 1);
412 if (m.snapprefs.getSnapEnabledGlobally()) {
413 if (_bbox_points.size() == 1) {
414 _desktop->snapindicator->set_new_snapsource(_bbox_points.at(0));
415 } else if (_bbox_points_for_translating.size() == 1) {
416 _desktop->snapindicator->set_new_snapsource(_bbox_points_for_translating.at(0));
417 } else if (_snap_points.size() == 1){
418 _desktop->snapindicator->set_new_snapsource(_snap_points.at(0));
419 }
420 }
421 }
422 }
424 if ((x != -1) && (y != -1)) {
425 sp_canvas_item_show(_norm);
426 sp_canvas_item_show(_grip);
427 }
429 if (_show == SHOW_OUTLINE) {
430 for (int i = 0; i < 4; i++)
431 sp_canvas_item_show(_l[i]);
432 }
434 _updateHandles();
435 g_return_if_fail(_stamp_cache == NULL);
436 }
438 void Inkscape::SelTrans::transform(Geom::Matrix const &rel_affine, Geom::Point const &norm)
439 {
440 g_return_if_fail(_grabbed);
441 g_return_if_fail(!_empty);
443 Geom::Matrix const affine( Geom::Translate(-norm) * rel_affine * Geom::Translate(norm) );
445 if (_show == SHOW_CONTENT) {
446 // update the content
447 for (unsigned i = 0; i < _items.size(); i++) {
448 SPItem &item = *_items[i];
449 Geom::Matrix const &prev_transform = _items_affines[i];
450 sp_item_set_i2d_affine(&item, prev_transform * affine);
451 }
452 } else {
453 if (_bbox) {
454 Geom::Point p[4];
455 /* update the outline */
456 for (unsigned i = 0 ; i < 4 ; i++) {
457 p[i] = _bbox->corner(i) * affine;
458 }
459 for (unsigned i = 0 ; i < 4 ; i++) {
460 sp_ctrlline_set_coords(SP_CTRLLINE(_l[i]), p[i], p[(i+1)%4]);
461 }
462 }
463 }
465 _current_relative_affine = affine;
466 _changed = true;
467 _updateHandles();
468 }
470 void Inkscape::SelTrans::ungrab()
471 {
472 g_return_if_fail(_grabbed);
473 _grabbed = false;
474 _show_handles = true;
476 _desktop->snapindicator->remove_snapsource();
478 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
479 _updateVolatileState();
481 for (unsigned i = 0; i < _items.size(); i++) {
482 sp_object_unref(SP_OBJECT(_items[i]), NULL);
483 }
485 sp_canvas_item_hide(_norm);
486 sp_canvas_item_hide(_grip);
488 if (_show == SHOW_OUTLINE) {
489 for (int i = 0; i < 4; i++)
490 sp_canvas_item_hide(_l[i]);
491 }
493 if (_stamp_cache) {
494 g_slist_free(_stamp_cache);
495 _stamp_cache = NULL;
496 }
498 _message_context.clear();
500 if (!_empty && _changed) {
501 sp_selection_apply_affine(selection, _current_relative_affine, (_show == SHOW_OUTLINE)? true : false);
502 if (_center) {
503 *_center *= _current_relative_affine;
504 _center_is_set = true;
505 }
507 // If dragging showed content live, sp_selection_apply_affine cannot change the centers
508 // appropriately - it does not know the original positions of the centers (all objects already have
509 // the new bboxes). So we need to reset the centers from our saved array.
510 if (_show != SHOW_OUTLINE && !_current_relative_affine.isTranslation()) {
511 for (unsigned i = 0; i < _items_centers.size(); i++) {
512 SPItem *currentItem = _items[i];
513 if (currentItem->isCenterSet()) { // only if it's already set
514 currentItem->setCenter (_items_centers[i] * _current_relative_affine);
515 SP_OBJECT(currentItem)->updateRepr();
516 }
517 }
518 }
520 _items.clear();
521 _items_const.clear();
522 _items_affines.clear();
523 _items_centers.clear();
525 if (_current_relative_affine.isTranslation()) {
526 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
527 _("Move"));
528 } else if (_current_relative_affine.without_translation().isScale()) {
529 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
530 _("Scale"));
531 } else if (_current_relative_affine.without_translation().isRotation()) {
532 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
533 _("Rotate"));
534 } else {
535 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
536 _("Skew"));
537 }
539 } else {
541 if (_center_is_set) {
542 // we were dragging center; update reprs and commit undoable action
543 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
544 SPItem *it = (SPItem*)SP_OBJECT(l->data);
545 SP_OBJECT(it)->updateRepr();
546 }
547 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
548 _("Set center"));
549 }
551 _items.clear();
552 _items_const.clear();
553 _items_affines.clear();
554 _items_centers.clear();
555 _updateHandles();
556 }
557 }
559 /* fixme: This is really bad, as we compare positions for each stamp (Lauris) */
560 /* fixme: IMHO the best way to keep sort cache would be to implement timestamping at last */
562 void Inkscape::SelTrans::stamp()
563 {
564 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
566 bool fixup = !_grabbed;
567 if ( fixup && _stamp_cache ) {
568 // TODO - give a proper fix. Simple temproary work-around for the grab() issue
569 g_slist_free(_stamp_cache);
570 _stamp_cache = NULL;
571 }
573 /* stamping mode */
574 if (!_empty) {
575 GSList *l;
576 if (_stamp_cache) {
577 l = _stamp_cache;
578 } else {
579 /* Build cache */
580 l = g_slist_copy((GSList *) selection->itemList());
581 l = g_slist_sort(l, (GCompareFunc) sp_object_compare_position);
582 _stamp_cache = l;
583 }
585 while (l) {
586 SPItem *original_item = SP_ITEM(l->data);
587 Inkscape::XML::Node *original_repr = SP_OBJECT_REPR(original_item);
589 // remember the position of the item
590 gint pos = original_repr->position();
591 // remember parent
592 Inkscape::XML::Node *parent = sp_repr_parent(original_repr);
594 Inkscape::XML::Node *copy_repr = original_repr->duplicate(parent->document());
596 // add the new repr to the parent
597 parent->appendChild(copy_repr);
598 // move to the saved position
599 copy_repr->setPosition(pos > 0 ? pos : 0);
601 SPItem *copy_item = (SPItem *) sp_desktop_document(_desktop)->getObjectByRepr(copy_repr);
603 Geom::Matrix const *new_affine;
604 if (_show == SHOW_OUTLINE) {
605 Geom::Matrix const i2d(sp_item_i2d_affine(original_item));
606 Geom::Matrix const i2dnew( i2d * _current_relative_affine );
607 sp_item_set_i2d_affine(copy_item, i2dnew);
608 new_affine = ©_item->transform;
609 } else {
610 new_affine = &original_item->transform;
611 }
613 sp_item_write_transform(copy_item, copy_repr, *new_affine);
615 if ( copy_item->isCenterSet() && _center ) {
616 copy_item->setCenter(*_center * _current_relative_affine);
617 }
619 Inkscape::GC::release(copy_repr);
620 l = l->next;
621 }
622 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
623 _("Stamp"));
624 }
626 if ( fixup && _stamp_cache ) {
627 // TODO - give a proper fix. Simple temproary work-around for the grab() issue
628 g_slist_free(_stamp_cache);
629 _stamp_cache = NULL;
630 }
631 }
633 void Inkscape::SelTrans::_updateHandles()
634 {
635 if ( !_show_handles || _empty )
636 {
637 sp_remove_handles(_shandle, 8);
638 sp_remove_handles(_rhandle, 8);
639 sp_remove_handles(&_chandle, 1);
640 return;
641 }
643 // center handle
644 if ( _chandle == NULL ) {
645 _chandle = sp_knot_new(_desktop, _("<b>Center</b> of rotation and skewing: drag to reposition; scaling with Shift also uses this center"));
647 _chandle->setShape (SP_CTRL_SHAPE_BITMAP);
648 _chandle->setSize (13);
649 _chandle->setAnchor (handle_center.anchor);
650 _chandle->setMode (SP_CTRL_MODE_XOR);
651 _chandle->setFill(0x00000000, 0x00000000, 0x00000000);
652 _chandle->setStroke(0x000000ff, 0xff0000b0, 0xff0000b0);
653 _chandle->setPixbuf(handles[handle_center.control]);
654 sp_knot_update_ctrl(_chandle);
656 g_signal_connect(G_OBJECT(_chandle), "request",
657 G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle_center);
658 g_signal_connect(G_OBJECT(_chandle), "moved",
659 G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle_center);
660 g_signal_connect(G_OBJECT(_chandle), "grabbed",
661 G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle_center);
662 g_signal_connect(G_OBJECT(_chandle), "ungrabbed",
663 G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle_center);
664 g_signal_connect(G_OBJECT(_chandle), "clicked",
665 G_CALLBACK(sp_sel_trans_handle_click), (gpointer) &handle_center);
666 }
668 sp_remove_handles(&_chandle, 1);
669 if ( _state == STATE_SCALE ) {
670 sp_remove_handles(_rhandle, 8);
671 _showHandles(_shandle, handles_scale, 8,
672 _("<b>Squeeze or stretch</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"),
673 _("<b>Scale</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"));
674 } else {
675 sp_remove_handles(_shandle, 8);
676 _showHandles(_rhandle, handles_rotate, 8,
677 _("<b>Skew</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to skew around the opposite side"),
678 _("<b>Rotate</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to rotate around the opposite corner"));
679 }
681 if (!_center_is_set) {
682 _center = _desktop->selection->center();
683 _center_is_set = true;
684 }
686 if ( _state == STATE_SCALE || !_center ) {
687 sp_knot_hide(_chandle);
688 } else {
689 sp_knot_show(_chandle);
690 sp_knot_moveto(_chandle, *_center);
691 }
692 }
694 void Inkscape::SelTrans::_updateVolatileState()
695 {
696 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
697 _empty = selection->isEmpty();
699 if (_empty) {
700 return;
701 }
703 //Update the bboxes
704 _bbox = selection->bounds(_snap_bbox_type);
705 _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX);
707 if (!_bbox) {
708 _empty = true;
709 return;
710 }
712 _strokewidth = stroke_average_width (selection->itemList());
713 }
715 static void sp_remove_handles(SPKnot *knot[], gint num)
716 {
717 for (int i = 0; i < num; i++) {
718 if (knot[i] != NULL) {
719 sp_knot_hide(knot[i]);
720 }
721 }
722 }
724 void Inkscape::SelTrans::_showHandles(SPKnot *knot[], SPSelTransHandle const handle[], gint num,
725 gchar const *even_tip, gchar const *odd_tip)
726 {
727 g_return_if_fail( !_empty );
729 for (int i = 0; i < num; i++) {
730 if (knot[i] == NULL) {
731 knot[i] = sp_knot_new(_desktop, i % 2 ? even_tip : odd_tip);
733 knot[i]->setShape (SP_CTRL_SHAPE_BITMAP);
734 knot[i]->setSize (13);
735 knot[i]->setAnchor (handle[i].anchor);
736 knot[i]->setMode (SP_CTRL_MODE_XOR);
737 knot[i]->setFill(0x000000ff, 0x00ff6600, 0x00ff6600); // inversion, green, green
738 knot[i]->setStroke(0x000000ff, 0x000000ff, 0x000000ff); // inversion
739 knot[i]->setPixbuf(handles[handle[i].control]);
740 sp_knot_update_ctrl(knot[i]);
742 g_signal_connect(G_OBJECT(knot[i]), "request",
743 G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle[i]);
744 g_signal_connect(G_OBJECT(knot[i]), "moved",
745 G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle[i]);
746 g_signal_connect(G_OBJECT(knot[i]), "grabbed",
747 G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle[i]);
748 g_signal_connect(G_OBJECT(knot[i]), "ungrabbed",
749 G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle[i]);
750 g_signal_connect(G_OBJECT(knot[i]), "event", G_CALLBACK(sp_seltrans_handle_event), (gpointer) &handle[i]);
751 }
752 sp_knot_show(knot[i]);
754 Geom::Point const handle_pt(handle[i].x, handle[i].y);
755 // shouldn't have nullary bbox, but knots
756 g_assert(_bbox);
757 Geom::Point p( _bbox->min()
758 + ( _bbox->dimensions()
759 * Geom::Scale(handle_pt) ) );
761 sp_knot_moveto(knot[i], p);
762 }
763 }
765 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data)
766 {
767 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleGrab(
768 knot, state, *(SPSelTransHandle const *) data
769 );
770 }
772 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint /*state*/, gpointer /*data*/)
773 {
774 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->ungrab();
775 }
777 static void sp_sel_trans_handle_new_event(SPKnot *knot, Geom::Point *position, guint state, gpointer data)
778 {
779 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleNewEvent(
780 knot, position, state, *(SPSelTransHandle const *) data
781 );
782 }
784 static gboolean sp_sel_trans_handle_request(SPKnot *knot, Geom::Point *position, guint state, gboolean *data)
785 {
786 return SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleRequest(
787 knot, position, state, *(SPSelTransHandle const *) data
788 );
789 }
791 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data)
792 {
793 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleClick(
794 knot, state, *(SPSelTransHandle const *) data
795 );
796 }
798 void Inkscape::SelTrans::handleClick(SPKnot */*knot*/, guint state, SPSelTransHandle const &handle)
799 {
800 switch (handle.anchor) {
801 case GTK_ANCHOR_CENTER:
802 if (state & GDK_SHIFT_MASK) {
803 // Unset the center position for all selected items
804 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
805 SPItem *it = (SPItem*)(SP_OBJECT(l->data));
806 it->unsetCenter();
807 SP_OBJECT(it)->updateRepr();
808 _center_is_set = false; // center has changed
809 _updateHandles();
810 }
811 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
812 _("Reset center"));
813 }
814 break;
815 default:
816 break;
817 }
818 }
820 void Inkscape::SelTrans::handleGrab(SPKnot *knot, guint /*state*/, SPSelTransHandle const &handle)
821 {
822 switch (handle.anchor) {
823 case GTK_ANCHOR_CENTER:
824 g_object_set(G_OBJECT(_grip),
825 "shape", SP_CTRL_SHAPE_BITMAP,
826 "size", 13.0,
827 NULL);
828 sp_canvas_item_show(_grip);
829 break;
830 default:
831 g_object_set(G_OBJECT(_grip),
832 "shape", SP_CTRL_SHAPE_CROSS,
833 "size", 7.0,
834 NULL);
835 sp_canvas_item_show(_norm);
836 sp_canvas_item_show(_grip);
838 break;
839 }
841 grab(sp_knot_position(knot), handle.x, handle.y, FALSE, FALSE);
842 }
845 void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const &handle)
846 {
847 if (!SP_KNOT_IS_GRABBED(knot)) {
848 return;
849 }
851 // in case items have been unhooked from the document, don't
852 // try to continue processing events for them.
853 for (unsigned int i = 0; i < _items.size(); i++) {
854 if (!SP_OBJECT_DOCUMENT(SP_OBJECT(_items[i])) ) {
855 return;
856 }
857 }
859 handle.action(this, handle, *position, state);
860 }
863 gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const &handle)
864 {
865 if (!SP_KNOT_IS_GRABBED(knot)) {
866 return TRUE;
867 }
869 knot->desktop->setPosition(*position);
871 // When holding shift while rotating or skewing, the transformation will be
872 // relative to the point opposite of the handle; otherwise it will be relative
873 // to the center as set for the selection
874 if ((!(state & GDK_SHIFT_MASK) == !(_state == STATE_ROTATE)) && (&handle != &handle_center)) {
875 _origin = _opposite;
876 _origin_for_bboxpoints = _opposite_for_bboxpoints;
877 _origin_for_specpoints = _opposite_for_specpoints;
878 } else if (_center) {
879 _origin = *_center;
880 _origin_for_bboxpoints = *_center;
881 _origin_for_specpoints = *_center;
882 } else {
883 // FIXME
884 return TRUE;
885 }
886 if (handle.request(this, handle, *position, state)) {
887 sp_knot_set_position(knot, *position, state);
888 SP_CTRL(_grip)->moveto(*position);
889 SP_CTRL(_norm)->moveto(_origin);
890 }
892 return TRUE;
893 }
896 void Inkscape::SelTrans::_selChanged(Inkscape::Selection */*selection*/)
897 {
898 if (!_grabbed) {
899 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
900 // reread in case it changed on the fly:
901 int prefs_bbox = prefs->getBool("/tools/bounding_box");
902 _snap_bbox_type = !prefs_bbox ?
903 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
904 //SPItem::APPROXIMATE_BBOX will be replaced by SPItem::VISUAL_BBOX, as soon as the latter is implemented properly
906 _updateVolatileState();
907 _current_relative_affine.setIdentity();
908 _center_is_set = false; // center(s) may have changed
909 _updateHandles();
910 }
911 }
913 void Inkscape::SelTrans::_selModified(Inkscape::Selection */*selection*/, guint /*flags*/)
914 {
915 if (!_grabbed) {
916 _updateVolatileState();
917 _current_relative_affine.setIdentity();
919 // reset internal flag
920 _changed = false;
922 _center_is_set = false; // center(s) may have changed
924 _updateHandles();
925 }
926 }
928 /*
929 * handlers for handle move-request
930 */
932 /** Returns -1 or 1 according to the sign of x. Returns 1 for 0 and NaN. */
933 static double sign(double const x)
934 {
935 return ( x < 0
936 ? -1
937 : 1 );
938 }
940 gboolean sp_sel_trans_scale_request(Inkscape::SelTrans *seltrans,
941 SPSelTransHandle const &, Geom::Point &pt, guint state)
942 {
943 return seltrans->scaleRequest(pt, state);
944 }
946 gboolean sp_sel_trans_stretch_request(Inkscape::SelTrans *seltrans,
947 SPSelTransHandle const &handle, Geom::Point &pt, guint state)
948 {
949 return seltrans->stretchRequest(handle, pt, state);
950 }
952 gboolean sp_sel_trans_skew_request(Inkscape::SelTrans *seltrans,
953 SPSelTransHandle const &handle, Geom::Point &pt, guint state)
954 {
955 return seltrans->skewRequest(handle, pt, state);
956 }
958 gboolean sp_sel_trans_rotate_request(Inkscape::SelTrans *seltrans,
959 SPSelTransHandle const &, Geom::Point &pt, guint state)
960 {
961 return seltrans->rotateRequest(pt, state);
962 }
964 gboolean sp_sel_trans_center_request(Inkscape::SelTrans *seltrans,
965 SPSelTransHandle const &, Geom::Point &pt, guint state)
966 {
967 return seltrans->centerRequest(pt, state);
968 }
970 gboolean Inkscape::SelTrans::scaleRequest(Geom::Point &pt, guint state)
971 {
973 // Calculate the scale factors, which can be either visual or geometric
974 // depending on which type of bbox is currently being used (see preferences -> selector tool)
975 Geom::Scale default_scale = calcScaleFactors(_point, pt, _origin);
977 // Find the scale factors for the geometric bbox
978 Geom::Point pt_geom = _getGeomHandlePos(pt);
979 Geom::Scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
981 _absolute_affine = Geom::identity(); //Initialize the scaler
983 if (state & GDK_MOD1_MASK) { // scale by an integer multiplier/divider
984 // We're scaling either the visual or the geometric bbox here (see the comment above)
985 for ( unsigned int i = 0 ; i < 2 ; i++ ) {
986 if (fabs(default_scale[i]) > 1) {
987 default_scale[i] = round(default_scale[i]);
988 } else if (default_scale[i] != 0) {
989 default_scale[i] = 1/round(1/(MIN(default_scale[i], 10)));
990 }
991 }
992 // Update the knot position
993 pt = _calcAbsAffineDefault(default_scale);
994 // When scaling by an integer, snapping is not needed
995 } else {
996 // In all other cases we should try to snap now
997 SnapManager &m = _desktop->namedview->snap_manager;
998 m.setup(_desktop, false, _items_const);
1000 Inkscape::SnappedPoint bb, sn;
1001 Geom::Coord bd(NR_HUGE);
1002 Geom::Coord sd(NR_HUGE);
1004 if ((state & GDK_CONTROL_MASK) || _desktop->isToolboxButtonActive ("lock")) {
1005 // Scale is locked to a 1:1 aspect ratio, so that s[X] must be made to equal s[Y].
1006 //
1007 // The aspect-ratio must be locked before snapping
1008 if (fabs(default_scale[Geom::X]) > fabs(default_scale[Geom::Y])) {
1009 default_scale[Geom::X] = fabs(default_scale[Geom::Y]) * sign(default_scale[Geom::X]);
1010 geom_scale[Geom::X] = fabs(geom_scale[Geom::Y]) * sign(geom_scale[Geom::X]);
1011 } else {
1012 default_scale[Geom::Y] = fabs(default_scale[Geom::X]) * sign(default_scale[Geom::Y]);
1013 geom_scale[Geom::Y] = fabs(geom_scale[Geom::X]) * sign(geom_scale[Geom::Y]);
1014 }
1016 // Snap along a suitable constraint vector from the origin.
1017 bb = m.constrainedSnapScale(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, default_scale, _origin_for_bboxpoints);
1018 sn = m.constrainedSnapScale(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, geom_scale, _origin_for_specpoints);
1020 /* Choose the smaller difference in scale. Since s[X] == s[Y] we can
1021 ** just compare difference in s[X].
1022 */
1023 bd = bb.getSnapped() ? fabs(bb.getTransformation()[Geom::X] - default_scale[Geom::X]) : NR_HUGE;
1024 sd = sn.getSnapped() ? fabs(sn.getTransformation()[Geom::X] - geom_scale[Geom::X]) : NR_HUGE;
1025 } else {
1026 /* Scale aspect ratio is unlocked */
1027 bb = m.freeSnapScale(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, default_scale, _origin_for_bboxpoints);
1028 sn = m.freeSnapScale(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, geom_scale, _origin_for_specpoints);
1030 /* Pick the snap that puts us closest to the original scale */
1031 bd = bb.getSnapped() ? fabs(Geom::L2(bb.getTransformation()) - Geom::L2(Geom::Point(default_scale[Geom::X], default_scale[Geom::Y]))) : NR_HUGE;
1032 sd = sn.getSnapped() ? fabs(Geom::L2(sn.getTransformation()) - Geom::L2(Geom::Point(geom_scale[Geom::X], geom_scale[Geom::Y]))) : NR_HUGE;
1033 }
1035 if (!(bb.getSnapped() || sn.getSnapped())) {
1036 // We didn't snap at all! Don't update the handle position, just calculate the new transformation
1037 _calcAbsAffineDefault(default_scale);
1038 _desktop->snapindicator->remove_snaptarget();
1039 } else if (bd < sd) {
1040 // We snapped the bbox (which is either visual or geometric)
1041 _desktop->snapindicator->set_new_snaptarget(bb);
1042 default_scale = Geom::Scale(bb.getTransformation());
1043 // Calculate the new transformation and update the handle position
1044 pt = _calcAbsAffineDefault(default_scale);
1045 } else {
1046 _desktop->snapindicator->set_new_snaptarget(sn);
1047 // We snapped the special points (e.g. nodes), which are not at the visual bbox
1048 // The handle location however (pt) might however be at the visual bbox, so we
1049 // will have to calculate pt taking the stroke width into account
1050 geom_scale = Geom::Scale(sn.getTransformation());
1051 pt = _calcAbsAffineGeom(geom_scale);
1052 }
1053 }
1055 /* Status text */
1056 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1057 _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1058 100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1060 return TRUE;
1061 }
1063 gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1064 {
1065 Geom::Dim2 axis, perp;
1066 switch (handle.cursor) {
1067 case GDK_TOP_SIDE:
1068 case GDK_BOTTOM_SIDE:
1069 axis = Geom::Y;
1070 perp = Geom::X;
1071 break;
1072 case GDK_LEFT_SIDE:
1073 case GDK_RIGHT_SIDE:
1074 axis = Geom::X;
1075 perp = Geom::Y;
1076 break;
1077 default:
1078 g_assert_not_reached();
1079 return TRUE;
1080 };
1082 // Calculate the scale factors, which can be either visual or geometric
1083 // depending on which type of bbox is currently being used (see preferences -> selector tool)
1084 Geom::Scale default_scale = calcScaleFactors(_point, pt, _origin);
1085 default_scale[perp] = 1;
1087 // Find the scale factors for the geometric bbox
1088 Geom::Point pt_geom = _getGeomHandlePos(pt);
1089 Geom::Scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
1090 geom_scale[perp] = 1;
1092 _absolute_affine = Geom::identity(); //Initialize the scaler
1094 if (state & GDK_MOD1_MASK) { // stretch by an integer multiplier/divider
1095 if (fabs(default_scale[axis]) > 1) {
1096 default_scale[axis] = round(default_scale[axis]);
1097 } else if (default_scale[axis] != 0) {
1098 default_scale[axis] = 1/round(1/(MIN(default_scale[axis], 10)));
1099 }
1100 // Calculate the new transformation and update the handle position
1101 pt = _calcAbsAffineDefault(default_scale);
1102 // When stretching by an integer, snapping is not needed
1103 } else {
1104 // In all other cases we should try to snap now
1106 SnapManager &m = _desktop->namedview->snap_manager;
1107 m.setup(_desktop, false, _items_const);
1109 Inkscape::SnappedPoint bb, sn;
1110 g_assert(bb.getSnapped() == false); // Check initialization to catch any regression
1111 Geom::Coord bd(NR_HUGE);
1112 Geom::Coord sd(NR_HUGE);
1114 bool symmetrical = state & GDK_CONTROL_MASK;
1116 bb = m.constrainedSnapStretch(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, Geom::Coord(default_scale[axis]), _origin_for_bboxpoints, Geom::Dim2(axis), symmetrical);
1117 sn = m.constrainedSnapStretch(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, Geom::Coord(geom_scale[axis]), _origin_for_specpoints, Geom::Dim2(axis), symmetrical);
1119 if (bb.getSnapped()) {
1120 // We snapped the bbox (which is either visual or geometric)
1121 bd = fabs(bb.getTransformation()[axis] - default_scale[axis]);
1122 default_scale[axis] = bb.getTransformation()[axis];
1123 }
1125 if (sn.getSnapped()) {
1126 sd = fabs(sn.getTransformation()[axis] - geom_scale[axis]);
1127 geom_scale[axis] = sn.getTransformation()[axis];
1128 }
1130 if (symmetrical) {
1131 // on ctrl, apply symmetrical scaling instead of stretching
1132 // Preserve aspect ratio, but never flip in the dimension not being edited (by using fabs())
1133 default_scale[perp] = fabs(default_scale[axis]);
1134 geom_scale[perp] = fabs(geom_scale[axis]);
1135 }
1137 if (!(bb.getSnapped() || sn.getSnapped())) {
1138 // We didn't snap at all! Don't update the handle position, just calculate the new transformation
1139 _calcAbsAffineDefault(default_scale);
1140 _desktop->snapindicator->remove_snaptarget();
1141 } else if (bd < sd) {
1142 _desktop->snapindicator->set_new_snaptarget(bb);
1143 // Calculate the new transformation and update the handle position
1144 pt = _calcAbsAffineDefault(default_scale);
1145 } else {
1146 _desktop->snapindicator->set_new_snaptarget(sn);
1147 // We snapped the special points (e.g. nodes), which are not at the visual bbox
1148 // The handle location however (pt) might however be at the visual bbox, so we
1149 // will have to calculate pt taking the stroke width into account
1150 pt = _calcAbsAffineGeom(geom_scale);
1151 }
1152 }
1154 // status text
1155 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1156 _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1157 100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1159 return TRUE;
1160 }
1162 gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1163 {
1164 /* When skewing (or rotating):
1165 * 1) the stroke width will not change. This makes life much easier because we don't have to
1166 * account for that (like for scaling or stretching). As a consequence, all points will
1167 * have the same origin for the transformation and for the snapping.
1168 * 2) When holding shift, the transformation will be relative to the point opposite of
1169 * the handle; otherwise it will be relative to the center as set for the selection
1170 */
1172 Geom::Dim2 dim_a;
1173 Geom::Dim2 dim_b;
1175 switch (handle.cursor) {
1176 case GDK_SB_H_DOUBLE_ARROW:
1177 dim_a = Geom::Y;
1178 dim_b = Geom::X;
1179 break;
1180 case GDK_SB_V_DOUBLE_ARROW:
1181 dim_a = Geom::X;
1182 dim_b = Geom::Y;
1183 break;
1184 default:
1185 g_assert_not_reached();
1186 abort();
1187 break;
1188 }
1190 Geom::Point const initial_delta = _point - _origin;
1192 if (fabs(initial_delta[dim_a]) < 1e-15) {
1193 return false;
1194 }
1196 // Calculate the scale factors, which can be either visual or geometric
1197 // depending on which type of bbox is currently being used (see preferences -> selector tool)
1198 Geom::Scale scale = calcScaleFactors(_point, pt, _origin, false);
1199 Geom::Scale skew = calcScaleFactors(_point, pt, _origin, true);
1200 scale[dim_b] = 1;
1201 skew[dim_b] = 1;
1203 if (fabs(scale[dim_a]) < 1) {
1204 // Prevent shrinking of the selected object, while allowing mirroring
1205 scale[dim_a] = sign(scale[dim_a]);
1206 } else {
1207 // Allow expanding of the selected object by integer multiples
1208 scale[dim_a] = floor(scale[dim_a] + 0.5);
1209 }
1211 double radians = atan(skew[dim_a] / scale[dim_a]);
1213 if (state & GDK_CONTROL_MASK) {
1214 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1215 // Snap to defined angle increments
1216 int snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12);
1217 if (snaps) {
1218 double sections = floor(radians * snaps / M_PI + .5);
1219 if (fabs(sections) >= snaps / 2) {
1220 sections = sign(sections) * (snaps / 2 - 1);
1221 }
1222 radians = (M_PI / snaps) * sections;
1223 }
1224 skew[dim_a] = tan(radians) * scale[dim_a];
1225 } else {
1226 // Snap to objects, grids, guides
1228 SnapManager &m = _desktop->namedview->snap_manager;
1229 m.setup(_desktop, false, _items_const);
1231 Inkscape::Snapper::ConstraintLine const constraint(component_vectors[dim_b]);
1232 // When skewing, we cannot snap the corners of the bounding box, see the comment in "constrainedSnapSkew" for details
1233 Geom::Point const s(skew[dim_a], scale[dim_a]);
1234 Inkscape::SnappedPoint sn = m.constrainedSnapSkew(Inkscape::SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, constraint, s, _origin, Geom::Dim2(dim_b));
1236 if (sn.getSnapped()) {
1237 // We snapped something, so change the skew to reflect it
1238 Geom::Coord const sd = sn.getSnapped() ? sn.getTransformation()[0] : NR_HUGE;
1239 _desktop->snapindicator->set_new_snaptarget(sn);
1240 skew[dim_a] = sd;
1241 } else {
1242 _desktop->snapindicator->remove_snaptarget();
1243 }
1244 }
1246 // Update the handle position
1247 pt[dim_b] = initial_delta[dim_a] * skew[dim_a] + _point[dim_b];
1248 pt[dim_a] = initial_delta[dim_a] * scale[dim_a] + _origin[dim_a];
1250 // Calculate the relative affine
1251 _relative_affine = Geom::identity();
1252 _relative_affine[2*dim_a + dim_a] = (pt[dim_a] - _origin[dim_a]) / initial_delta[dim_a];
1253 _relative_affine[2*dim_a + (dim_b)] = (pt[dim_b] - _point[dim_b]) / initial_delta[dim_a];
1254 _relative_affine[2*(dim_b) + (dim_a)] = 0;
1255 _relative_affine[2*(dim_b) + (dim_b)] = 1;
1257 for (int i = 0; i < 2; i++) {
1258 if (fabs(_relative_affine[3*i]) < 1e-15) {
1259 _relative_affine[3*i] = 1e-15;
1260 }
1261 }
1263 // Update the status text
1264 double degrees = mod360symm(Geom::rad_to_deg(radians));
1265 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1266 // TRANSLATORS: don't modify the first ";"
1267 // (it will NOT be displayed as ";" - only the second one will be)
1268 _("<b>Skew</b>: %0.2f°; with <b>Ctrl</b> to snap angle"),
1269 degrees);
1271 return TRUE;
1272 }
1274 gboolean Inkscape::SelTrans::rotateRequest(Geom::Point &pt, guint state)
1275 {
1276 /* When rotating (or skewing):
1277 * 1) the stroke width will not change. This makes life much easier because we don't have to
1278 * account for that (like for scaling or stretching). As a consequence, all points will
1279 * have the same origin for the transformation and for the snapping.
1280 * 2) When holding shift, the transformation will be relative to the point opposite of
1281 * the handle; otherwise it will be relative to the center as set for the selection
1282 */
1284 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1285 int snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12);
1287 // rotate affine in rotate
1288 Geom::Point const d1 = _point - _origin;
1289 Geom::Point const d2 = pt - _origin;
1291 Geom::Coord const h1 = Geom::L2(d1); // initial radius
1292 if (h1 < 1e-15) return FALSE;
1293 Geom::Point q1 = d1 / h1; // normalized initial vector to handle
1294 Geom::Coord const h2 = Geom::L2(d2); // new radius
1295 if (fabs(h2) < 1e-15) return FALSE;
1296 Geom::Point q2 = d2 / h2; // normalized new vector to handle
1298 double radians;
1299 if (state & GDK_CONTROL_MASK) {
1300 // Snap to defined angle increments
1301 double cos_t = Geom::dot(q1, q2);
1302 double sin_t = Geom::dot(Geom::rot90(q1), q2);
1303 radians = atan2(sin_t, cos_t);
1304 if (snaps) {
1305 radians = ( M_PI / snaps ) * floor( radians * snaps / M_PI + .5 );
1306 }
1307 q1 = Geom::Point(1, 0);
1308 q2 = Geom::Point(cos(radians), sin(radians));
1309 } else {
1310 radians = atan2(Geom::dot(Geom::rot90(d1), d2),
1311 Geom::dot(d1, d2));
1312 }
1314 Geom::Rotate const r1(q1);
1315 Geom::Rotate const r2(q2);
1317 // Calculate the relative affine
1318 _relative_affine = r2 * r1.inverse();
1320 // Update the handle position
1321 pt = _point * Geom::Translate(-_origin) * _relative_affine * Geom::Translate(_origin);
1323 // Update the status text
1324 double degrees = mod360symm(Geom::rad_to_deg(radians));
1325 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1326 // TRANSLATORS: don't modify the first ";"
1327 // (it will NOT be displayed as ";" - only the second one will be)
1328 _("<b>Rotate</b>: %0.2f°; with <b>Ctrl</b> to snap angle"), degrees);
1330 return TRUE;
1331 }
1333 // Move the item's transformation center
1334 gboolean Inkscape::SelTrans::centerRequest(Geom::Point &pt, guint state)
1335 {
1336 SnapManager &m = _desktop->namedview->snap_manager;
1337 m.setup(_desktop);
1338 m.freeSnapReturnByRef(SnapPreferences::SNAPPOINT_NODE, pt, Inkscape::SNAPSOURCE_HANDLE);
1340 if (state & GDK_CONTROL_MASK) {
1341 if ( fabs(_point[Geom::X] - pt[Geom::X]) > fabs(_point[Geom::Y] - pt[Geom::Y]) ) {
1342 pt[Geom::Y] = _point[Geom::Y];
1343 } else {
1344 pt[Geom::X] = _point[Geom::X];
1345 }
1346 }
1348 if ( !(state & GDK_SHIFT_MASK) && _bbox ) {
1349 // screen pixels to snap center to bbox
1350 #define SNAP_DIST 5
1351 // FIXME: take from prefs
1352 double snap_dist = SNAP_DIST / _desktop->current_zoom();
1354 for (int i = 0; i < 2; i++) {
1355 if (fabs(pt[i] - _bbox->min()[i]) < snap_dist) {
1356 pt[i] = _bbox->min()[i];
1357 }
1358 if (fabs(pt[i] - _bbox->midpoint()[i]) < snap_dist) {
1359 pt[i] = _bbox->midpoint()[i];
1360 }
1361 if (fabs(pt[i] - _bbox->max()[i]) < snap_dist) {
1362 pt[i] = _bbox->max()[i];
1363 }
1364 }
1365 }
1367 // status text
1368 GString *xs = SP_PX_TO_METRIC_STRING(pt[Geom::X], _desktop->namedview->getDefaultMetric());
1369 GString *ys = SP_PX_TO_METRIC_STRING(pt[Geom::Y], _desktop->namedview->getDefaultMetric());
1370 _message_context.setF(Inkscape::NORMAL_MESSAGE, _("Move <b>center</b> to %s, %s"), xs->str, ys->str);
1371 g_string_free(xs, FALSE);
1372 g_string_free(ys, FALSE);
1374 return TRUE;
1375 }
1377 /*
1378 * handlers for handle movement
1379 *
1380 */
1382 void sp_sel_trans_stretch(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1383 {
1384 seltrans->stretch(handle, pt, state);
1385 }
1387 void sp_sel_trans_scale(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint state)
1388 {
1389 seltrans->scale(pt, state);
1390 }
1392 void sp_sel_trans_skew(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1393 {
1394 seltrans->skew(handle, pt, state);
1395 }
1397 void sp_sel_trans_rotate(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint state)
1398 {
1399 seltrans->rotate(pt, state);
1400 }
1402 void Inkscape::SelTrans::stretch(SPSelTransHandle const &/*handle*/, Geom::Point &/*pt*/, guint /*state*/)
1403 {
1404 transform(_absolute_affine, Geom::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1405 }
1407 void Inkscape::SelTrans::scale(Geom::Point &/*pt*/, guint /*state*/)
1408 {
1409 transform(_absolute_affine, Geom::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1410 }
1412 void Inkscape::SelTrans::skew(SPSelTransHandle const &/*handle*/, Geom::Point &/*pt*/, guint /*state*/)
1413 {
1414 transform(_relative_affine, _origin);
1415 }
1417 void Inkscape::SelTrans::rotate(Geom::Point &/*pt*/, guint /*state*/)
1418 {
1419 transform(_relative_affine, _origin);
1420 }
1422 void sp_sel_trans_center(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint /*state*/)
1423 {
1424 seltrans->setCenter(pt);
1425 }
1428 void Inkscape::SelTrans::moveTo(Geom::Point const &xy, guint state)
1429 {
1430 SnapManager &m = _desktop->namedview->snap_manager;
1432 /* The amount that we've moved by during this drag */
1433 Geom::Point dxy = xy - _point;
1435 bool const alt = (state & GDK_MOD1_MASK);
1436 bool const control = (state & GDK_CONTROL_MASK);
1437 bool const shift = (state & GDK_SHIFT_MASK);
1439 if (alt) {
1441 /* Alt pressed means keep offset: snap the moved distance to the grid.
1442 ** FIXME: this will snap to more than just the grid, nowadays.
1443 */
1445 m.setup(_desktop, true, _items_const);
1446 m.freeSnapReturnByRef(SnapPreferences::SNAPPOINT_NODE, dxy, Inkscape::SNAPSOURCE_UNDEFINED);
1448 } else if (shift) {
1449 if (control) { // shift & control: constrained movement without snapping
1450 if (fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y])) {
1451 dxy[Geom::Y] = 0;
1452 } else {
1453 dxy[Geom::X] = 0;
1454 }
1455 }
1456 } else { //!shift: with snapping
1458 /* We're snapping to things, possibly with a constraint to horizontal or
1459 ** vertical movement. Obtain a list of possible translations and then
1460 ** pick the smallest.
1461 */
1463 m.setup(_desktop, false, _items_const);
1465 /* This will be our list of possible translations */
1466 std::list<Inkscape::SnappedPoint> s;
1468 if (control) { // constrained movement with snapping
1470 /* Snap to things, and also constrain to horizontal or vertical movement */
1472 unsigned int dim = fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y]) ? Geom::X : Geom::Y;
1473 // When doing a constrained translation, all points will move in the same direction, i.e.
1474 // either horizontally or vertically. Therefore we only have to specify the direction of
1475 // the constraint-line once. The constraint lines are parallel, but might not be colinear.
1476 // Therefore we will have to set the point through which the constraint-line runs
1477 // individually for each point to be snapped; this will be handled however by _snapTransformed()
1478 s.push_back(m.constrainedSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_BBOX,
1479 _bbox_points_for_translating,
1480 _point,
1481 Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1482 dxy));
1484 s.push_back(m.constrainedSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_NODE,
1485 _snap_points,
1486 _point,
1487 Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1488 dxy));
1489 } else { // !control
1491 // Let's leave this timer code here for a while. I'll probably need it in the near future (Diederik van Lierop)
1492 /* GTimeVal starttime;
1493 GTimeVal endtime;
1494 g_get_current_time(&starttime); */
1496 /* Snap to things with no constraint */
1497 s.push_back(m.freeSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_BBOX, _bbox_points_for_translating, _point, dxy));
1498 s.push_back(m.freeSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, dxy));
1500 /*g_get_current_time(&endtime);
1501 double elapsed = ((((double)endtime.tv_sec - starttime.tv_sec) * G_USEC_PER_SEC + (endtime.tv_usec - starttime.tv_usec))) / 1000.0;
1502 std::cout << "Time spent snapping: " << elapsed << std::endl; */
1503 }
1505 /* Pick one */
1506 Inkscape::SnappedPoint best_snapped_point;
1507 for (std::list<Inkscape::SnappedPoint>::const_iterator i = s.begin(); i != s.end(); i++) {
1508 if (i->getSnapped()) {
1509 if (best_snapped_point.isOtherSnapBetter(*i, true)) {
1510 best_snapped_point = *i;
1511 dxy = i->getTransformation();
1512 }
1513 }
1514 }
1515 if (best_snapped_point.getSnapped()) {
1516 _desktop->snapindicator->set_new_snaptarget(best_snapped_point);
1517 } else {
1518 // We didn't snap, so remove any previous snap indicator
1519 _desktop->snapindicator->remove_snaptarget();
1520 if (control) {
1521 // If we didn't snap, then we should still constrain horizontally or vertically
1522 // (When we did snap, then this constraint has already been enforced by
1523 // calling constrainedSnapTranslation() above)
1524 if (fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y])) {
1525 dxy[Geom::Y] = 0;
1526 } else {
1527 dxy[Geom::X] = 0;
1528 }
1529 }
1530 }
1531 }
1533 Geom::Matrix const move((Geom::Translate(dxy)));
1534 Geom::Point const norm(0, 0);
1535 transform(move, norm);
1537 // status text
1538 GString *xs = SP_PX_TO_METRIC_STRING(dxy[Geom::X], _desktop->namedview->getDefaultMetric());
1539 GString *ys = SP_PX_TO_METRIC_STRING(dxy[Geom::Y], _desktop->namedview->getDefaultMetric());
1540 _message_context.setF(Inkscape::NORMAL_MESSAGE, _("<b>Move</b> by %s, %s; with <b>Ctrl</b> to restrict to horizontal/vertical; with <b>Shift</b> to disable snapping"), xs->str, ys->str);
1541 g_string_free(xs, TRUE);
1542 g_string_free(ys, TRUE);
1543 }
1545 // Given a location of a handle at the visual bounding box, find the corresponding location at the
1546 // geometrical bounding box
1547 Geom::Point Inkscape::SelTrans::_getGeomHandlePos(Geom::Point const &visual_handle_pos)
1548 {
1549 if ( _snap_bbox_type == SPItem::GEOMETRIC_BBOX) {
1550 // When the selector tool is using geometric bboxes, then the handle is already
1551 // located at one of the geometric bbox corners
1552 return visual_handle_pos;
1553 }
1555 if (!_geometric_bbox) {
1556 //_getGeomHandlePos() can only be used after _geometric_bbox has been defined!
1557 return visual_handle_pos;
1558 }
1560 // Using the Geom::Rect constructor below ensures that "min() < max()", which is important
1561 // because this will also hold for _bbox, and which is required for get_scale_transform_with_stroke()
1562 Geom::Rect new_bbox = Geom::Rect(_origin_for_bboxpoints, visual_handle_pos); // new visual bounding box
1563 // Please note that the new_bbox might in fact be just a single line, for example when stretching (in
1564 // which case the handle and origin will be aligned vertically or horizontally)
1565 Geom::Point normalized_handle_pos = (visual_handle_pos - new_bbox.min()) * Geom::Scale(new_bbox.dimensions()).inverse();
1567 // Calculate the absolute affine while taking into account the scaling of the stroke width
1568 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1569 bool transform_stroke = prefs->getBool("/options/transform/stroke", true);
1570 Geom::Matrix abs_affine = get_scale_transform_with_stroke (*_bbox, _strokewidth, transform_stroke,
1571 new_bbox.min()[Geom::X], new_bbox.min()[Geom::Y], new_bbox.max()[Geom::X], new_bbox.max()[Geom::Y]);
1573 // Calculate the scaled geometrical bbox
1574 Geom::Rect new_geom_bbox = Geom::Rect(_geometric_bbox->min() * abs_affine, _geometric_bbox->max() * abs_affine);
1575 // Find the location of the handle on this new geometrical bbox
1576 return normalized_handle_pos * Geom::Scale(new_geom_bbox.dimensions()) + new_geom_bbox.min(); //new position of the geometric handle
1577 }
1579 Geom::Scale Inkscape::calcScaleFactors(Geom::Point const &initial_point, Geom::Point const &new_point, Geom::Point const &origin, bool const skew)
1580 {
1581 // Work out the new scale factors for the bbox
1583 Geom::Point const initial_delta = initial_point - origin;
1584 Geom::Point const new_delta = new_point - origin;
1585 Geom::Point const offset = new_point - initial_point;
1586 Geom::Scale scale(1, 1);
1588 for ( unsigned int i = 0 ; i < 2 ; i++ ) {
1589 if ( fabs(initial_delta[i]) > 1e-6 ) {
1590 if (skew) {
1591 scale[i] = offset[1-i] / initial_delta[i];
1592 } else {
1593 scale[i] = new_delta[i] / initial_delta[i];
1594 }
1595 }
1596 }
1598 return scale;
1599 }
1601 // Only for scaling/stretching
1602 Geom::Point Inkscape::SelTrans::_calcAbsAffineDefault(Geom::Scale const default_scale)
1603 {
1604 Geom::Matrix abs_affine = Geom::Translate(-_origin) * Geom::Matrix(default_scale) * Geom::Translate(_origin);
1605 Geom::Point new_bbox_min = _approximate_bbox->min() * abs_affine;
1606 Geom::Point new_bbox_max = _approximate_bbox->max() * abs_affine;
1608 bool transform_stroke = false;
1609 gdouble strokewidth = 0;
1611 if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
1612 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1613 transform_stroke = prefs->getBool("/options/transform/stroke", true);
1614 strokewidth = _strokewidth;
1615 }
1617 _absolute_affine = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
1618 new_bbox_min[Geom::X], new_bbox_min[Geom::Y], new_bbox_max[Geom::X], new_bbox_max[Geom::Y]);
1620 // return the new handle position
1621 return ( _point - _origin ) * default_scale + _origin;
1622 }
1624 // Only for scaling/stretching
1625 Geom::Point Inkscape::SelTrans::_calcAbsAffineGeom(Geom::Scale const geom_scale)
1626 {
1627 _relative_affine = Geom::Matrix(geom_scale);
1628 _absolute_affine = Geom::Translate(-_origin_for_specpoints) * _relative_affine * Geom::Translate(_origin_for_specpoints);
1630 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1631 bool const transform_stroke = prefs->getBool("/options/transform/stroke", true);
1632 Geom::Rect visual_bbox = get_visual_bbox(_geometric_bbox, _absolute_affine, _strokewidth, transform_stroke);
1634 // return the new handle position
1635 return visual_bbox.min() + visual_bbox.dimensions() * Geom::Scale(_handle_x, _handle_y);
1636 }
1638 void Inkscape::SelTrans::_keepClosestPointOnly(std::vector<std::pair<Geom::Point, int> > &points, const Geom::Point &reference)
1639 {
1640 if (points.size() < 2) return;
1642 std::pair<Geom::Point, int> closest_point = std::make_pair(Geom::Point(NR_HUGE, NR_HUGE), SNAPSOURCE_UNDEFINED);
1643 Geom::Coord closest_dist = NR_HUGE;
1645 for(std::vector<std::pair<Geom::Point, int> >::const_iterator i = points.begin(); i != points.end(); i++) {
1646 Geom::Coord dist = Geom::L2((*i).first - reference);
1647 if (i == points.begin() || dist < closest_dist) {
1648 closest_point = *i;
1649 closest_dist = dist;
1650 }
1651 }
1653 points.clear();
1654 points.push_back(closest_point);
1655 }
1657 /*
1658 Local Variables:
1659 mode:c++
1660 c-file-style:"stroustrup"
1661 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1662 indent-tabs-mode:nil
1663 fill-column:99
1664 End:
1665 */
1666 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :