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)
245 {
246 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
248 g_return_if_fail(!_grabbed);
250 _grabbed = true;
251 _show_handles = show_handles;
252 _updateVolatileState();
253 _current_relative_affine.setIdentity();
255 _changed = false;
257 if (_empty) {
258 return;
259 }
261 for (GSList const *l = selection->itemList(); l; l = l->next) {
262 SPItem *it = (SPItem *)sp_object_ref(SP_OBJECT(l->data), NULL);
263 _items.push_back(it);
264 _items_const.push_back(it);
265 _items_affines.push_back(sp_item_i2d_affine(it));
266 _items_centers.push_back(it->getCenter()); // for content-dragging, we need to remember original centers
267 }
269 _handle_x = x;
270 _handle_y = y;
272 // The selector tool should snap the bbox, special snappoints, and path nodes
273 // (The special points are the handles, center, rotation axis, font baseline, ends of spiral, etc.)
275 // First, determine the bounding box for snapping ...
276 _bbox = selection->bounds(_snap_bbox_type);
277 _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX); // Used for correctly scaling the strokewidth
278 _geometric_bbox = selection->bounds(SPItem::GEOMETRIC_BBOX);
279 _point = p;
280 if (_geometric_bbox) {
281 _point_geom = _geometric_bbox->min() + _geometric_bbox->dimensions() * Geom::Scale(x, y);
282 } else {
283 _point_geom = p;
284 }
286 // Next, get all points to consider for snapping
287 SnapManager const &m = _desktop->namedview->snap_manager;
288 Inkscape::SnapPreferences local_snapprefs = m.snapprefs;
289 local_snapprefs.setSnapToItemNode(true); // We should get at least the cusp nodes here. This might
290 // have been turned off because (for example) the user only want paths as a snap target, not nodes
291 // but as a snap source we still need some nodes though!
292 _snap_points.clear();
293 _snap_points = selection->getSnapPoints(&local_snapprefs);
294 std::vector<Geom::Point> snap_points_hull = selection->getSnapPointsConvexHull(&local_snapprefs);
295 if (_snap_points.size() > 100) {
296 /* Snapping a huge number of nodes will take way too long, so limit the number of snappable nodes
297 An average user would rarely ever try to snap such a large number of nodes anyway, because
298 (s)he could hardly discern which node would be snapping */
299 _snap_points = snap_points_hull;
300 // Unfortunately, by now we will have lost the font-baseline snappoints :-(
301 }
303 // Find bbox hulling all special points, which excludes stroke width. Here we need to include the
304 // path nodes, for example because a rectangle which has been converted to a path doesn't have
305 // any other special points
306 Geom::Rect snap_points_bbox;
307 if ( snap_points_hull.empty() == false ) {
308 std::vector<Geom::Point>::iterator i = snap_points_hull.begin();
309 snap_points_bbox = Geom::Rect(*i, *i);
310 i++;
311 while (i != snap_points_hull.end()) {
312 snap_points_bbox.expandTo(*i);
313 i++;
314 }
315 }
317 _bbox_points.clear();
318 if (_bbox) {
319 if (m.snapprefs.getSnapModeBBox()) {
320 getBBoxPoints(_bbox, &_bbox_points, true, m.snapprefs.getSnapBBoxEdgeMidpoints(), m.snapprefs.getSnapBBoxMidpoints());
321 }
322 // There are two separate "opposites" (i.e. opposite w.r.t. the handle being dragged):
323 // - one for snapping the boundingbox, which can be either visual or geometric
324 // - one for snapping the special points
325 // The "opposite" in case of a geometric boundingbox always coincides with the "opposite" for the special points
326 // These distinct "opposites" are needed in the snapmanager to avoid bugs such as #sf1540195 (in which
327 // a box is caught between two guides)
328 _opposite_for_bboxpoints = _bbox->min() + _bbox->dimensions() * Geom::Scale(1-x, 1-y);
329 _opposite_for_specpoints = snap_points_bbox.min() + snap_points_bbox.dimensions() * Geom::Scale(1-x, 1-y);
330 _opposite = _opposite_for_bboxpoints;
331 }
333 // When snapping the node closest to the mouse pointer is absolutely preferred over the closest snap
334 // (i.e. when weight == 1), then we will not even try to snap to other points and discard those other
335 // points immediately.
336 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
337 if (prefs->getBool("/options/snapclosestonly/value", false)) {
338 if (m.snapprefs.getSnapModeNode()) {
339 _keepClosestPointOnly(_snap_points, p);
340 } else {
341 _snap_points.clear(); // don't keep any point
342 }
344 if (m.snapprefs.getSnapModeBBox()) {
345 _keepClosestPointOnly(_bbox_points, p);
346 } else {
347 _bbox_points.clear(); // don't keep any point
348 }
350 g_assert(_bbox_points.size() < 2 && _snap_points.size() < 2);
351 if (_snap_points.size() == 1 && _bbox_points.size() == 1) { //both vectors can only have either one or zero elements
352 // So we have exactly one bbox corner and one node left; now find out which is closest and delete the other one
353 if (Geom::L2(_snap_points.at(0) - p) < Geom::L2(_bbox_points.at(0) - p)) {
354 _bbox_points.clear();
355 } else {
356 _snap_points.clear();
357 }
358 }
360 // Now either _bbox_points or _snap_points has a single element, the other one has zero..... or both have zero elements
361 g_assert((_bbox_points.size() + _snap_points.size()) < 2);
362 if (_bbox_points.size() == 1) {
363 _desktop->snapindicator->set_new_snapsource(_bbox_points.at(0));
364 } else if (_snap_points.size() == 1){
365 _desktop->snapindicator->set_new_snapsource(_snap_points.at(0));
366 }
367 }
369 // The lines below are useful for debugging any snapping issues, as they'll spit out all points that are considered for snapping
371 /*std::cout << "Number of snap points: " << _snap_points.size() << std::endl;
372 for (std::vector<Geom::Point>::const_iterator i = _snap_points.begin(); i != _snap_points.end(); i++)
373 {
374 std::cout << " " << *i << std::endl;
375 }
377 std::cout << "Number of bbox points: " << _bbox_points.size() << std::endl;
378 for (std::vector<Geom::Point>::const_iterator i = _bbox_points.begin(); i != _bbox_points.end(); i++)
379 {
380 std::cout << " " << *i << std::endl;
381 }*/
383 if ((x != -1) && (y != -1)) {
384 sp_canvas_item_show(_norm);
385 sp_canvas_item_show(_grip);
386 }
388 if (_show == SHOW_OUTLINE) {
389 for (int i = 0; i < 4; i++)
390 sp_canvas_item_show(_l[i]);
391 }
393 _updateHandles();
394 g_return_if_fail(_stamp_cache == NULL);
395 }
397 void Inkscape::SelTrans::transform(Geom::Matrix const &rel_affine, Geom::Point const &norm)
398 {
399 g_return_if_fail(_grabbed);
400 g_return_if_fail(!_empty);
402 Geom::Matrix const affine( Geom::Translate(-norm) * rel_affine * Geom::Translate(norm) );
404 if (_show == SHOW_CONTENT) {
405 // update the content
406 for (unsigned i = 0; i < _items.size(); i++) {
407 SPItem &item = *_items[i];
408 Geom::Matrix const &prev_transform = _items_affines[i];
409 sp_item_set_i2d_affine(&item, prev_transform * affine);
410 }
411 } else {
412 if (_bbox) {
413 Geom::Point p[4];
414 /* update the outline */
415 for (unsigned i = 0 ; i < 4 ; i++) {
416 p[i] = _bbox->corner(i) * affine;
417 }
418 for (unsigned i = 0 ; i < 4 ; i++) {
419 sp_ctrlline_set_coords(SP_CTRLLINE(_l[i]), p[i], p[(i+1)%4]);
420 }
421 }
422 }
424 _current_relative_affine = affine;
425 _changed = true;
426 _updateHandles();
427 }
429 void Inkscape::SelTrans::ungrab()
430 {
431 g_return_if_fail(_grabbed);
432 _grabbed = false;
433 _show_handles = true;
435 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
436 _updateVolatileState();
438 for (unsigned i = 0; i < _items.size(); i++) {
439 sp_object_unref(SP_OBJECT(_items[i]), NULL);
440 }
442 sp_canvas_item_hide(_norm);
443 sp_canvas_item_hide(_grip);
445 if (_show == SHOW_OUTLINE) {
446 for (int i = 0; i < 4; i++)
447 sp_canvas_item_hide(_l[i]);
448 }
450 if (_stamp_cache) {
451 g_slist_free(_stamp_cache);
452 _stamp_cache = NULL;
453 }
455 _message_context.clear();
457 if (!_empty && _changed) {
458 sp_selection_apply_affine(selection, _current_relative_affine, (_show == SHOW_OUTLINE)? true : false);
459 if (_center) {
460 *_center *= _current_relative_affine;
461 _center_is_set = true;
462 }
464 // If dragging showed content live, sp_selection_apply_affine cannot change the centers
465 // appropriately - it does not know the original positions of the centers (all objects already have
466 // the new bboxes). So we need to reset the centers from our saved array.
467 if (_show != SHOW_OUTLINE && !_current_relative_affine.isTranslation()) {
468 for (unsigned i = 0; i < _items_centers.size(); i++) {
469 SPItem *currentItem = _items[i];
470 if (currentItem->isCenterSet()) { // only if it's already set
471 currentItem->setCenter (_items_centers[i] * _current_relative_affine);
472 SP_OBJECT(currentItem)->updateRepr();
473 }
474 }
475 }
477 _items.clear();
478 _items_const.clear();
479 _items_affines.clear();
480 _items_centers.clear();
482 if (_current_relative_affine.isTranslation()) {
483 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
484 _("Move"));
485 } else if (_current_relative_affine.isScale()) {
486 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
487 _("Scale"));
488 } else if (_current_relative_affine.isRotation()) {
489 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
490 _("Rotate"));
491 } else {
492 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
493 _("Skew"));
494 }
496 } else {
498 if (_center_is_set) {
499 // we were dragging center; update reprs and commit undoable action
500 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
501 SPItem *it = (SPItem*)SP_OBJECT(l->data);
502 SP_OBJECT(it)->updateRepr();
503 }
504 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
505 _("Set center"));
506 }
508 _items.clear();
509 _items_const.clear();
510 _items_affines.clear();
511 _items_centers.clear();
512 _updateHandles();
513 }
514 }
516 /* fixme: This is really bad, as we compare positions for each stamp (Lauris) */
517 /* fixme: IMHO the best way to keep sort cache would be to implement timestamping at last */
519 void Inkscape::SelTrans::stamp()
520 {
521 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
523 bool fixup = !_grabbed;
524 if ( fixup && _stamp_cache ) {
525 // TODO - give a proper fix. Simple temproary work-around for the grab() issue
526 g_slist_free(_stamp_cache);
527 _stamp_cache = NULL;
528 }
530 /* stamping mode */
531 if (!_empty) {
532 GSList *l;
533 if (_stamp_cache) {
534 l = _stamp_cache;
535 } else {
536 /* Build cache */
537 l = g_slist_copy((GSList *) selection->itemList());
538 l = g_slist_sort(l, (GCompareFunc) sp_object_compare_position);
539 _stamp_cache = l;
540 }
542 while (l) {
543 SPItem *original_item = SP_ITEM(l->data);
544 Inkscape::XML::Node *original_repr = SP_OBJECT_REPR(original_item);
546 // remember the position of the item
547 gint pos = original_repr->position();
548 // remember parent
549 Inkscape::XML::Node *parent = sp_repr_parent(original_repr);
551 Inkscape::XML::Node *copy_repr = original_repr->duplicate(parent->document());
553 // add the new repr to the parent
554 parent->appendChild(copy_repr);
555 // move to the saved position
556 copy_repr->setPosition(pos > 0 ? pos : 0);
558 SPItem *copy_item = (SPItem *) sp_desktop_document(_desktop)->getObjectByRepr(copy_repr);
560 Geom::Matrix const *new_affine;
561 if (_show == SHOW_OUTLINE) {
562 Geom::Matrix const i2d(sp_item_i2d_affine(original_item));
563 Geom::Matrix const i2dnew( i2d * _current_relative_affine );
564 sp_item_set_i2d_affine(copy_item, i2dnew);
565 new_affine = ©_item->transform;
566 } else {
567 new_affine = &original_item->transform;
568 }
570 sp_item_write_transform(copy_item, copy_repr, *new_affine);
572 if ( copy_item->isCenterSet() && _center ) {
573 copy_item->setCenter(*_center * _current_relative_affine);
574 }
576 Inkscape::GC::release(copy_repr);
577 l = l->next;
578 }
579 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
580 _("Stamp"));
581 }
583 if ( fixup && _stamp_cache ) {
584 // TODO - give a proper fix. Simple temproary work-around for the grab() issue
585 g_slist_free(_stamp_cache);
586 _stamp_cache = NULL;
587 }
588 }
590 void Inkscape::SelTrans::_updateHandles()
591 {
592 if ( !_show_handles || _empty )
593 {
594 sp_remove_handles(_shandle, 8);
595 sp_remove_handles(_rhandle, 8);
596 sp_remove_handles(&_chandle, 1);
597 return;
598 }
600 // center handle
601 if ( _chandle == NULL ) {
602 _chandle = sp_knot_new(_desktop, _("<b>Center</b> of rotation and skewing: drag to reposition; scaling with Shift also uses this center"));
604 _chandle->setShape (SP_CTRL_SHAPE_BITMAP);
605 _chandle->setSize (13);
606 _chandle->setAnchor (handle_center.anchor);
607 _chandle->setMode (SP_CTRL_MODE_XOR);
608 _chandle->setFill(0x00000000, 0x00000000, 0x00000000);
609 _chandle->setStroke(0x000000ff, 0xff0000b0, 0xff0000b0);
610 _chandle->setPixbuf(handles[handle_center.control]);
611 sp_knot_update_ctrl(_chandle);
613 g_signal_connect(G_OBJECT(_chandle), "request",
614 G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle_center);
615 g_signal_connect(G_OBJECT(_chandle), "moved",
616 G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle_center);
617 g_signal_connect(G_OBJECT(_chandle), "grabbed",
618 G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle_center);
619 g_signal_connect(G_OBJECT(_chandle), "ungrabbed",
620 G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle_center);
621 g_signal_connect(G_OBJECT(_chandle), "clicked",
622 G_CALLBACK(sp_sel_trans_handle_click), (gpointer) &handle_center);
623 }
625 sp_remove_handles(&_chandle, 1);
626 if ( _state == STATE_SCALE ) {
627 sp_remove_handles(_rhandle, 8);
628 _showHandles(_shandle, handles_scale, 8,
629 _("<b>Squeeze or stretch</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"),
630 _("<b>Scale</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"));
631 } else {
632 sp_remove_handles(_shandle, 8);
633 _showHandles(_rhandle, handles_rotate, 8,
634 _("<b>Skew</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to skew around the opposite side"),
635 _("<b>Rotate</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to rotate around the opposite corner"));
636 }
638 if (!_center_is_set) {
639 _center = _desktop->selection->center();
640 _center_is_set = true;
641 }
643 if ( _state == STATE_SCALE || !_center ) {
644 sp_knot_hide(_chandle);
645 } else {
646 sp_knot_show(_chandle);
647 sp_knot_moveto(_chandle, *_center);
648 }
649 }
651 void Inkscape::SelTrans::_updateVolatileState()
652 {
653 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
654 _empty = selection->isEmpty();
656 if (_empty) {
657 return;
658 }
660 //Update the bboxes
661 _bbox = selection->bounds(_snap_bbox_type);
662 _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX);
664 if (!_bbox) {
665 _empty = true;
666 return;
667 }
669 _strokewidth = stroke_average_width (selection->itemList());
670 }
672 static void sp_remove_handles(SPKnot *knot[], gint num)
673 {
674 for (int i = 0; i < num; i++) {
675 if (knot[i] != NULL) {
676 sp_knot_hide(knot[i]);
677 }
678 }
679 }
681 void Inkscape::SelTrans::_showHandles(SPKnot *knot[], SPSelTransHandle const handle[], gint num,
682 gchar const *even_tip, gchar const *odd_tip)
683 {
684 g_return_if_fail( !_empty );
686 for (int i = 0; i < num; i++) {
687 if (knot[i] == NULL) {
688 knot[i] = sp_knot_new(_desktop, i % 2 ? even_tip : odd_tip);
690 knot[i]->setShape (SP_CTRL_SHAPE_BITMAP);
691 knot[i]->setSize (13);
692 knot[i]->setAnchor (handle[i].anchor);
693 knot[i]->setMode (SP_CTRL_MODE_XOR);
694 knot[i]->setFill(0x000000ff, 0x00ff6600, 0x00ff6600); // inversion, green, green
695 knot[i]->setStroke(0x000000ff, 0x000000ff, 0x000000ff); // inversion
696 knot[i]->setPixbuf(handles[handle[i].control]);
697 sp_knot_update_ctrl(knot[i]);
699 g_signal_connect(G_OBJECT(knot[i]), "request",
700 G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle[i]);
701 g_signal_connect(G_OBJECT(knot[i]), "moved",
702 G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle[i]);
703 g_signal_connect(G_OBJECT(knot[i]), "grabbed",
704 G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle[i]);
705 g_signal_connect(G_OBJECT(knot[i]), "ungrabbed",
706 G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle[i]);
707 g_signal_connect(G_OBJECT(knot[i]), "event", G_CALLBACK(sp_seltrans_handle_event), (gpointer) &handle[i]);
708 }
709 sp_knot_show(knot[i]);
711 Geom::Point const handle_pt(handle[i].x, handle[i].y);
712 // shouldn't have nullary bbox, but knots
713 g_assert(_bbox);
714 Geom::Point p( _bbox->min()
715 + ( _bbox->dimensions()
716 * Geom::Scale(handle_pt) ) );
718 sp_knot_moveto(knot[i], p);
719 }
720 }
722 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data)
723 {
724 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleGrab(
725 knot, state, *(SPSelTransHandle const *) data
726 );
727 }
729 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint /*state*/, gpointer /*data*/)
730 {
731 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->ungrab();
732 }
734 static void sp_sel_trans_handle_new_event(SPKnot *knot, Geom::Point *position, guint state, gpointer data)
735 {
736 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleNewEvent(
737 knot, position, state, *(SPSelTransHandle const *) data
738 );
739 }
741 static gboolean sp_sel_trans_handle_request(SPKnot *knot, Geom::Point *position, guint state, gboolean *data)
742 {
743 return SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleRequest(
744 knot, position, state, *(SPSelTransHandle const *) data
745 );
746 }
748 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data)
749 {
750 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleClick(
751 knot, state, *(SPSelTransHandle const *) data
752 );
753 }
755 void Inkscape::SelTrans::handleClick(SPKnot */*knot*/, guint state, SPSelTransHandle const &handle)
756 {
757 switch (handle.anchor) {
758 case GTK_ANCHOR_CENTER:
759 if (state & GDK_SHIFT_MASK) {
760 // Unset the center position for all selected items
761 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
762 SPItem *it = (SPItem*)(SP_OBJECT(l->data));
763 it->unsetCenter();
764 SP_OBJECT(it)->updateRepr();
765 _center_is_set = false; // center has changed
766 _updateHandles();
767 }
768 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
769 _("Reset center"));
770 }
771 break;
772 default:
773 break;
774 }
775 }
777 void Inkscape::SelTrans::handleGrab(SPKnot *knot, guint /*state*/, SPSelTransHandle const &handle)
778 {
779 switch (handle.anchor) {
780 case GTK_ANCHOR_CENTER:
781 g_object_set(G_OBJECT(_grip),
782 "shape", SP_CTRL_SHAPE_BITMAP,
783 "size", 13.0,
784 NULL);
785 sp_canvas_item_show(_grip);
786 break;
787 default:
788 g_object_set(G_OBJECT(_grip),
789 "shape", SP_CTRL_SHAPE_CROSS,
790 "size", 7.0,
791 NULL);
792 sp_canvas_item_show(_norm);
793 sp_canvas_item_show(_grip);
795 break;
796 }
798 grab(sp_knot_position(knot), handle.x, handle.y, FALSE);
799 }
802 void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const &handle)
803 {
804 if (!SP_KNOT_IS_GRABBED(knot)) {
805 return;
806 }
808 // in case items have been unhooked from the document, don't
809 // try to continue processing events for them.
810 for (unsigned int i = 0; i < _items.size(); i++) {
811 if (!SP_OBJECT_DOCUMENT(SP_OBJECT(_items[i])) ) {
812 return;
813 }
814 }
816 handle.action(this, handle, *position, state);
817 }
820 gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const &handle)
821 {
822 if (!SP_KNOT_IS_GRABBED(knot)) {
823 return TRUE;
824 }
826 knot->desktop->setPosition(*position);
828 // When holding shift while rotating or skewing, the transformation will be
829 // relative to the point opposite of the handle; otherwise it will be relative
830 // to the center as set for the selection
831 if ((!(state & GDK_SHIFT_MASK) == !(_state == STATE_ROTATE)) && (&handle != &handle_center)) {
832 _origin = _opposite;
833 _origin_for_bboxpoints = _opposite_for_bboxpoints;
834 _origin_for_specpoints = _opposite_for_specpoints;
835 } else if (_center) {
836 _origin = *_center;
837 _origin_for_bboxpoints = *_center;
838 _origin_for_specpoints = *_center;
839 } else {
840 // FIXME
841 return TRUE;
842 }
843 if (handle.request(this, handle, *position, state)) {
844 sp_knot_set_position(knot, *position, state);
845 SP_CTRL(_grip)->moveto(*position);
846 SP_CTRL(_norm)->moveto(_origin);
847 }
849 return TRUE;
850 }
853 void Inkscape::SelTrans::_selChanged(Inkscape::Selection */*selection*/)
854 {
855 if (!_grabbed) {
856 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
857 // reread in case it changed on the fly:
858 int prefs_bbox = prefs->getBool("/tools/bounding_box");
859 _snap_bbox_type = !prefs_bbox ?
860 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
861 //SPItem::APPROXIMATE_BBOX will be replaced by SPItem::VISUAL_BBOX, as soon as the latter is implemented properly
863 _updateVolatileState();
864 _current_relative_affine.setIdentity();
865 _center_is_set = false; // center(s) may have changed
866 _updateHandles();
867 }
868 }
870 void Inkscape::SelTrans::_selModified(Inkscape::Selection */*selection*/, guint /*flags*/)
871 {
872 if (!_grabbed) {
873 _updateVolatileState();
874 _current_relative_affine.setIdentity();
876 // reset internal flag
877 _changed = false;
879 _center_is_set = false; // center(s) may have changed
881 _updateHandles();
882 }
883 }
885 /*
886 * handlers for handle move-request
887 */
889 /** Returns -1 or 1 according to the sign of x. Returns 1 for 0 and NaN. */
890 static double sign(double const x)
891 {
892 return ( x < 0
893 ? -1
894 : 1 );
895 }
897 gboolean sp_sel_trans_scale_request(Inkscape::SelTrans *seltrans,
898 SPSelTransHandle const &, Geom::Point &pt, guint state)
899 {
900 return seltrans->scaleRequest(pt, state);
901 }
903 gboolean sp_sel_trans_stretch_request(Inkscape::SelTrans *seltrans,
904 SPSelTransHandle const &handle, Geom::Point &pt, guint state)
905 {
906 return seltrans->stretchRequest(handle, pt, state);
907 }
909 gboolean sp_sel_trans_skew_request(Inkscape::SelTrans *seltrans,
910 SPSelTransHandle const &handle, Geom::Point &pt, guint state)
911 {
912 return seltrans->skewRequest(handle, pt, state);
913 }
915 gboolean sp_sel_trans_rotate_request(Inkscape::SelTrans *seltrans,
916 SPSelTransHandle const &, Geom::Point &pt, guint state)
917 {
918 return seltrans->rotateRequest(pt, state);
919 }
921 gboolean sp_sel_trans_center_request(Inkscape::SelTrans *seltrans,
922 SPSelTransHandle const &, Geom::Point &pt, guint state)
923 {
924 return seltrans->centerRequest(pt, state);
925 }
927 gboolean Inkscape::SelTrans::scaleRequest(Geom::Point &pt, guint state)
928 {
930 // Calculate the scale factors, which can be either visual or geometric
931 // depending on which type of bbox is currently being used (see preferences -> selector tool)
932 Geom::Scale default_scale = calcScaleFactors(_point, pt, _origin);
934 // Find the scale factors for the geometric bbox
935 Geom::Point pt_geom = _getGeomHandlePos(pt);
936 Geom::Scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
938 _absolute_affine = Geom::identity(); //Initialize the scaler
940 if (state & GDK_MOD1_MASK) { // scale by an integer multiplier/divider
941 // We're scaling either the visual or the geometric bbox here (see the comment above)
942 for ( unsigned int i = 0 ; i < 2 ; i++ ) {
943 if (fabs(default_scale[i]) > 1) {
944 default_scale[i] = round(default_scale[i]);
945 } else if (default_scale[i] != 0) {
946 default_scale[i] = 1/round(1/(MIN(default_scale[i], 10)));
947 }
948 }
949 // Update the knot position
950 pt = _calcAbsAffineDefault(default_scale);
951 // When scaling by an integer, snapping is not needed
952 } else {
953 // In all other cases we should try to snap now
954 SnapManager &m = _desktop->namedview->snap_manager;
955 m.setup(_desktop, false, _items_const);
957 Inkscape::SnappedPoint bb, sn;
958 Geom::Coord bd(NR_HUGE);
959 Geom::Coord sd(NR_HUGE);
961 if ((state & GDK_CONTROL_MASK) || _desktop->isToolboxButtonActive ("lock")) {
962 // Scale is locked to a 1:1 aspect ratio, so that s[X] must be made to equal s[Y].
963 //
964 // The aspect-ratio must be locked before snapping
965 if (fabs(default_scale[Geom::X]) > fabs(default_scale[Geom::Y])) {
966 default_scale[Geom::X] = fabs(default_scale[Geom::Y]) * sign(default_scale[Geom::X]);
967 geom_scale[Geom::X] = fabs(geom_scale[Geom::Y]) * sign(geom_scale[Geom::X]);
968 } else {
969 default_scale[Geom::Y] = fabs(default_scale[Geom::X]) * sign(default_scale[Geom::Y]);
970 geom_scale[Geom::Y] = fabs(geom_scale[Geom::X]) * sign(geom_scale[Geom::Y]);
971 }
973 // Snap along a suitable constraint vector from the origin.
974 bb = m.constrainedSnapScale(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, default_scale, _origin_for_bboxpoints);
975 sn = m.constrainedSnapScale(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, geom_scale, _origin_for_specpoints);
977 /* Choose the smaller difference in scale. Since s[X] == s[Y] we can
978 ** just compare difference in s[X].
979 */
980 bd = bb.getSnapped() ? fabs(bb.getTransformation()[Geom::X] - default_scale[Geom::X]) : NR_HUGE;
981 sd = sn.getSnapped() ? fabs(sn.getTransformation()[Geom::X] - geom_scale[Geom::X]) : NR_HUGE;
982 } else {
983 /* Scale aspect ratio is unlocked */
984 bb = m.freeSnapScale(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, default_scale, _origin_for_bboxpoints);
985 sn = m.freeSnapScale(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, geom_scale, _origin_for_specpoints);
987 /* Pick the snap that puts us closest to the original scale */
988 bd = bb.getSnapped() ? fabs(Geom::L2(bb.getTransformation()) - Geom::L2(Geom::Point(default_scale[Geom::X], default_scale[Geom::Y]))) : NR_HUGE;
989 sd = sn.getSnapped() ? fabs(Geom::L2(sn.getTransformation()) - Geom::L2(Geom::Point(geom_scale[Geom::X], geom_scale[Geom::Y]))) : NR_HUGE;
990 }
992 if (!(bb.getSnapped() || sn.getSnapped())) {
993 // We didn't snap at all! Don't update the handle position, just calculate the new transformation
994 _calcAbsAffineDefault(default_scale);
995 _desktop->snapindicator->remove_snaptarget();
996 } else if (bd < sd) {
997 // We snapped the bbox (which is either visual or geometric)
998 _desktop->snapindicator->set_new_snaptarget(bb);
999 default_scale = Geom::Scale(bb.getTransformation());
1000 // Calculate the new transformation and update the handle position
1001 pt = _calcAbsAffineDefault(default_scale);
1002 } else {
1003 _desktop->snapindicator->set_new_snaptarget(sn);
1004 // We snapped the special points (e.g. nodes), which are not at the visual bbox
1005 // The handle location however (pt) might however be at the visual bbox, so we
1006 // will have to calculate pt taking the stroke width into account
1007 geom_scale = Geom::Scale(sn.getTransformation());
1008 pt = _calcAbsAffineGeom(geom_scale);
1009 }
1010 }
1012 /* Status text */
1013 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1014 _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1015 100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1017 return TRUE;
1018 }
1020 gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1021 {
1022 Geom::Dim2 axis, perp;
1023 switch (handle.cursor) {
1024 case GDK_TOP_SIDE:
1025 case GDK_BOTTOM_SIDE:
1026 axis = Geom::Y;
1027 perp = Geom::X;
1028 break;
1029 case GDK_LEFT_SIDE:
1030 case GDK_RIGHT_SIDE:
1031 axis = Geom::X;
1032 perp = Geom::Y;
1033 break;
1034 default:
1035 g_assert_not_reached();
1036 return TRUE;
1037 };
1039 // Calculate the scale factors, which can be either visual or geometric
1040 // depending on which type of bbox is currently being used (see preferences -> selector tool)
1041 Geom::Scale default_scale = calcScaleFactors(_point, pt, _origin);
1042 default_scale[perp] = 1;
1044 // Find the scale factors for the geometric bbox
1045 Geom::Point pt_geom = _getGeomHandlePos(pt);
1046 Geom::Scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
1047 geom_scale[perp] = 1;
1049 _absolute_affine = Geom::identity(); //Initialize the scaler
1051 if (state & GDK_MOD1_MASK) { // stretch by an integer multiplier/divider
1052 if (fabs(default_scale[axis]) > 1) {
1053 default_scale[axis] = round(default_scale[axis]);
1054 } else if (default_scale[axis] != 0) {
1055 default_scale[axis] = 1/round(1/(MIN(default_scale[axis], 10)));
1056 }
1057 // Calculate the new transformation and update the handle position
1058 pt = _calcAbsAffineDefault(default_scale);
1059 // When stretching by an integer, snapping is not needed
1060 } else {
1061 // In all other cases we should try to snap now
1063 SnapManager &m = _desktop->namedview->snap_manager;
1064 m.setup(_desktop, false, _items_const);
1066 Inkscape::SnappedPoint bb, sn;
1067 g_assert(bb.getSnapped() == false); // Check initialization to catch any regression
1068 Geom::Coord bd(NR_HUGE);
1069 Geom::Coord sd(NR_HUGE);
1071 bool symmetrical = state & GDK_CONTROL_MASK;
1073 bb = m.constrainedSnapStretch(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, Geom::Coord(default_scale[axis]), _origin_for_bboxpoints, Geom::Dim2(axis), symmetrical);
1074 sn = m.constrainedSnapStretch(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, Geom::Coord(geom_scale[axis]), _origin_for_specpoints, Geom::Dim2(axis), symmetrical);
1076 if (bb.getSnapped()) {
1077 // We snapped the bbox (which is either visual or geometric)
1078 bd = fabs(bb.getTransformation()[axis] - default_scale[axis]);
1079 default_scale[axis] = bb.getTransformation()[axis];
1080 }
1082 if (sn.getSnapped()) {
1083 sd = fabs(sn.getTransformation()[axis] - geom_scale[axis]);
1084 geom_scale[axis] = sn.getTransformation()[axis];
1085 }
1087 if (symmetrical) {
1088 // on ctrl, apply symmetrical scaling instead of stretching
1089 // Preserve aspect ratio, but never flip in the dimension not being edited (by using fabs())
1090 default_scale[perp] = fabs(default_scale[axis]);
1091 geom_scale[perp] = fabs(geom_scale[axis]);
1092 }
1094 if (!(bb.getSnapped() || sn.getSnapped())) {
1095 // We didn't snap at all! Don't update the handle position, just calculate the new transformation
1096 _calcAbsAffineDefault(default_scale);
1097 _desktop->snapindicator->remove_snaptarget();
1098 } else if (bd < sd) {
1099 _desktop->snapindicator->set_new_snaptarget(bb);
1100 // Calculate the new transformation and update the handle position
1101 pt = _calcAbsAffineDefault(default_scale);
1102 } else {
1103 _desktop->snapindicator->set_new_snaptarget(sn);
1104 // We snapped the special points (e.g. nodes), which are not at the visual bbox
1105 // The handle location however (pt) might however be at the visual bbox, so we
1106 // will have to calculate pt taking the stroke width into account
1107 pt = _calcAbsAffineGeom(geom_scale);
1108 }
1109 }
1111 // status text
1112 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1113 _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1114 100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1116 return TRUE;
1117 }
1119 gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1120 {
1121 /* When skewing (or rotating):
1122 * 1) the stroke width will not change. This makes life much easier because we don't have to
1123 * account for that (like for scaling or stretching). As a consequence, all points will
1124 * have the same origin for the transformation and for the snapping.
1125 * 2) When holding shift, the transformation will be relative to the point opposite of
1126 * the handle; otherwise it will be relative to the center as set for the selection
1127 */
1129 Geom::Dim2 dim_a;
1130 Geom::Dim2 dim_b;
1132 switch (handle.cursor) {
1133 case GDK_SB_H_DOUBLE_ARROW:
1134 dim_a = Geom::Y;
1135 dim_b = Geom::X;
1136 break;
1137 case GDK_SB_V_DOUBLE_ARROW:
1138 dim_a = Geom::X;
1139 dim_b = Geom::Y;
1140 break;
1141 default:
1142 g_assert_not_reached();
1143 abort();
1144 break;
1145 }
1147 Geom::Point const initial_delta = _point - _origin;
1149 if (fabs(initial_delta[dim_a]) < 1e-15) {
1150 return false;
1151 }
1153 // Calculate the scale factors, which can be either visual or geometric
1154 // depending on which type of bbox is currently being used (see preferences -> selector tool)
1155 Geom::Scale scale = calcScaleFactors(_point, pt, _origin, false);
1156 Geom::Scale skew = calcScaleFactors(_point, pt, _origin, true);
1157 scale[dim_b] = 1;
1158 skew[dim_b] = 1;
1160 if (fabs(scale[dim_a]) < 1) {
1161 // Prevent shrinking of the selected object, while allowing mirroring
1162 scale[dim_a] = sign(scale[dim_a]);
1163 } else {
1164 // Allow expanding of the selected object by integer multiples
1165 scale[dim_a] = floor(scale[dim_a] + 0.5);
1166 }
1168 double radians = atan(skew[dim_a] / scale[dim_a]);
1170 if (state & GDK_CONTROL_MASK) {
1171 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1172 // Snap to defined angle increments
1173 int snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12);
1174 if (snaps) {
1175 double sections = floor(radians * snaps / M_PI + .5);
1176 if (fabs(sections) >= snaps / 2) {
1177 sections = sign(sections) * (snaps / 2 - 1);
1178 }
1179 radians = (M_PI / snaps) * sections;
1180 }
1181 skew[dim_a] = tan(radians) * scale[dim_a];
1182 } else {
1183 // Snap to objects, grids, guides
1185 SnapManager &m = _desktop->namedview->snap_manager;
1186 m.setup(_desktop, false, _items_const);
1188 Inkscape::Snapper::ConstraintLine const constraint(component_vectors[dim_b]);
1189 // When skewing, we cannot snap the corners of the bounding box, see the comment in "constrainedSnapSkew" for details
1190 Geom::Point const s(skew[dim_a], scale[dim_a]);
1191 Inkscape::SnappedPoint sn = m.constrainedSnapSkew(Inkscape::SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, constraint, s, _origin, Geom::Dim2(dim_b));
1193 if (sn.getSnapped()) {
1194 // We snapped something, so change the skew to reflect it
1195 Geom::Coord const sd = sn.getSnapped() ? sn.getTransformation()[0] : NR_HUGE;
1196 _desktop->snapindicator->set_new_snaptarget(sn);
1197 skew[dim_a] = sd;
1198 } else {
1199 _desktop->snapindicator->remove_snaptarget();
1200 }
1201 }
1203 // Update the handle position
1204 pt[dim_b] = initial_delta[dim_a] * skew[dim_a] + _point[dim_b];
1205 pt[dim_a] = initial_delta[dim_a] * scale[dim_a] + _origin[dim_a];
1207 // Calculate the relative affine
1208 _relative_affine = Geom::identity();
1209 _relative_affine[2*dim_a + dim_a] = (pt[dim_a] - _origin[dim_a]) / initial_delta[dim_a];
1210 _relative_affine[2*dim_a + (dim_b)] = (pt[dim_b] - _point[dim_b]) / initial_delta[dim_a];
1211 _relative_affine[2*(dim_b) + (dim_a)] = 0;
1212 _relative_affine[2*(dim_b) + (dim_b)] = 1;
1214 for (int i = 0; i < 2; i++) {
1215 if (fabs(_relative_affine[3*i]) < 1e-15) {
1216 _relative_affine[3*i] = 1e-15;
1217 }
1218 }
1220 // Update the status text
1221 double degrees = mod360symm(Geom::rad_to_deg(radians));
1222 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1223 // TRANSLATORS: don't modify the first ";"
1224 // (it will NOT be displayed as ";" - only the second one will be)
1225 _("<b>Skew</b>: %0.2f°; with <b>Ctrl</b> to snap angle"),
1226 degrees);
1228 return TRUE;
1229 }
1231 gboolean Inkscape::SelTrans::rotateRequest(Geom::Point &pt, guint state)
1232 {
1233 /* When rotating (or skewing):
1234 * 1) the stroke width will not change. This makes life much easier because we don't have to
1235 * account for that (like for scaling or stretching). As a consequence, all points will
1236 * have the same origin for the transformation and for the snapping.
1237 * 2) When holding shift, the transformation will be relative to the point opposite of
1238 * the handle; otherwise it will be relative to the center as set for the selection
1239 */
1241 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1242 int snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12);
1244 // rotate affine in rotate
1245 Geom::Point const d1 = _point - _origin;
1246 Geom::Point const d2 = pt - _origin;
1248 Geom::Coord const h1 = Geom::L2(d1); // initial radius
1249 if (h1 < 1e-15) return FALSE;
1250 Geom::Point q1 = d1 / h1; // normalized initial vector to handle
1251 Geom::Coord const h2 = Geom::L2(d2); // new radius
1252 if (fabs(h2) < 1e-15) return FALSE;
1253 Geom::Point q2 = d2 / h2; // normalized new vector to handle
1255 double radians;
1256 if (state & GDK_CONTROL_MASK) {
1257 // Snap to defined angle increments
1258 double cos_t = Geom::dot(q1, q2);
1259 double sin_t = Geom::dot(Geom::rot90(q1), q2);
1260 radians = atan2(sin_t, cos_t);
1261 if (snaps) {
1262 radians = ( M_PI / snaps ) * floor( radians * snaps / M_PI + .5 );
1263 }
1264 q1 = Geom::Point(1, 0);
1265 q2 = Geom::Point(cos(radians), sin(radians));
1266 } else {
1267 radians = atan2(Geom::dot(Geom::rot90(d1), d2),
1268 Geom::dot(d1, d2));
1269 }
1271 Geom::Rotate const r1(q1);
1272 Geom::Rotate const r2(q2);
1274 // Calculate the relative affine
1275 _relative_affine = r2 * r1.inverse();
1277 // Update the handle position
1278 pt = _point * Geom::Translate(-_origin) * _relative_affine * Geom::Translate(_origin);
1280 // Update the status text
1281 double degrees = mod360symm(Geom::rad_to_deg(radians));
1282 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1283 // TRANSLATORS: don't modify the first ";"
1284 // (it will NOT be displayed as ";" - only the second one will be)
1285 _("<b>Rotate</b>: %0.2f°; with <b>Ctrl</b> to snap angle"), degrees);
1287 return TRUE;
1288 }
1290 gboolean Inkscape::SelTrans::centerRequest(Geom::Point &pt, guint state)
1291 {
1292 SnapManager &m = _desktop->namedview->snap_manager;
1293 m.setup(_desktop);
1294 m.freeSnapReturnByRef(SnapPreferences::SNAPPOINT_NODE, pt);
1296 if (state & GDK_CONTROL_MASK) {
1297 if ( fabs(_point[Geom::X] - pt[Geom::X]) > fabs(_point[Geom::Y] - pt[Geom::Y]) ) {
1298 pt[Geom::Y] = _point[Geom::Y];
1299 } else {
1300 pt[Geom::X] = _point[Geom::X];
1301 }
1302 }
1304 if ( !(state & GDK_SHIFT_MASK) && _bbox ) {
1305 // screen pixels to snap center to bbox
1306 #define SNAP_DIST 5
1307 // FIXME: take from prefs
1308 double snap_dist = SNAP_DIST / _desktop->current_zoom();
1310 for (int i = 0; i < 2; i++) {
1311 if (fabs(pt[i] - _bbox->min()[i]) < snap_dist) {
1312 pt[i] = _bbox->min()[i];
1313 }
1314 if (fabs(pt[i] - _bbox->midpoint()[i]) < snap_dist) {
1315 pt[i] = _bbox->midpoint()[i];
1316 }
1317 if (fabs(pt[i] - _bbox->max()[i]) < snap_dist) {
1318 pt[i] = _bbox->max()[i];
1319 }
1320 }
1321 }
1323 // status text
1324 GString *xs = SP_PX_TO_METRIC_STRING(pt[Geom::X], _desktop->namedview->getDefaultMetric());
1325 GString *ys = SP_PX_TO_METRIC_STRING(pt[Geom::Y], _desktop->namedview->getDefaultMetric());
1326 _message_context.setF(Inkscape::NORMAL_MESSAGE, _("Move <b>center</b> to %s, %s"), xs->str, ys->str);
1327 g_string_free(xs, FALSE);
1328 g_string_free(ys, FALSE);
1330 return TRUE;
1331 }
1333 /*
1334 * handlers for handle movement
1335 *
1336 */
1338 void sp_sel_trans_stretch(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1339 {
1340 seltrans->stretch(handle, pt, state);
1341 }
1343 void sp_sel_trans_scale(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint state)
1344 {
1345 seltrans->scale(pt, state);
1346 }
1348 void sp_sel_trans_skew(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1349 {
1350 seltrans->skew(handle, pt, state);
1351 }
1353 void sp_sel_trans_rotate(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint state)
1354 {
1355 seltrans->rotate(pt, state);
1356 }
1358 void Inkscape::SelTrans::stretch(SPSelTransHandle const &/*handle*/, Geom::Point &/*pt*/, guint /*state*/)
1359 {
1360 transform(_absolute_affine, Geom::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1361 }
1363 void Inkscape::SelTrans::scale(Geom::Point &/*pt*/, guint /*state*/)
1364 {
1365 transform(_absolute_affine, Geom::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1366 }
1368 void Inkscape::SelTrans::skew(SPSelTransHandle const &/*handle*/, Geom::Point &/*pt*/, guint /*state*/)
1369 {
1370 transform(_relative_affine, _origin);
1371 }
1373 void Inkscape::SelTrans::rotate(Geom::Point &/*pt*/, guint /*state*/)
1374 {
1375 transform(_relative_affine, _origin);
1376 }
1378 void sp_sel_trans_center(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint /*state*/)
1379 {
1380 seltrans->setCenter(pt);
1381 }
1384 void Inkscape::SelTrans::moveTo(Geom::Point const &xy, guint state)
1385 {
1386 SnapManager &m = _desktop->namedview->snap_manager;
1387 m.setup(_desktop, true, _items_const);
1389 /* The amount that we've moved by during this drag */
1390 Geom::Point dxy = xy - _point;
1392 bool const alt = (state & GDK_MOD1_MASK);
1393 bool const control = (state & GDK_CONTROL_MASK);
1394 bool const shift = (state & GDK_SHIFT_MASK);
1396 if (alt) {
1398 /* Alt pressed means keep offset: snap the moved distance to the grid.
1399 ** FIXME: this will snap to more than just the grid, nowadays.
1400 */
1402 m.freeSnapReturnByRef(SnapPreferences::SNAPPOINT_NODE, dxy);
1404 } else if (!shift) {
1406 /* We're snapping to things, possibly with a constraint to horizontal or
1407 ** vertical movement. Obtain a list of possible translations and then
1408 ** pick the smallest.
1409 */
1411 /* This will be our list of possible translations */
1412 std::list<Inkscape::SnappedPoint> s;
1414 if (control) {
1416 /* Snap to things, and also constrain to horizontal or vertical movement */
1418 for (unsigned int dim = 0; dim < 2; dim++) {
1419 // When doing a constrained translation, all points will move in the same direction, i.e.
1420 // either horizontally or vertically. Therefore we only have to specify the direction of
1421 // the constraint-line once. The constraint lines are parallel, but might not be colinear.
1422 // Therefore we will have to set the point through which the constraint-line runs
1423 // individually for each point to be snapped; this will be handled however by _snapTransformed()
1424 s.push_back(m.constrainedSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_BBOX,
1425 _bbox_points,
1426 _point,
1427 Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1428 dxy));
1430 s.push_back(m.constrainedSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_NODE,
1431 _snap_points,
1432 _point,
1433 Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1434 dxy));
1435 }
1437 } else {
1439 // Let's leave this timer code here for a while. I'll probably need it in the near future (Diederik van Lierop)
1440 /* GTimeVal starttime;
1441 GTimeVal endtime;
1442 g_get_current_time(&starttime); */
1444 /* Snap to things with no constraint */
1445 s.push_back(m.freeSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, dxy));
1446 s.push_back(m.freeSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, dxy));
1448 /*g_get_current_time(&endtime);
1449 double elapsed = ((((double)endtime.tv_sec - starttime.tv_sec) * G_USEC_PER_SEC + (endtime.tv_usec - starttime.tv_usec))) / 1000.0;
1450 std::cout << "Time spent snapping: " << elapsed << std::endl; */
1451 }
1453 /* Pick one */
1454 Inkscape::SnappedPoint best_snapped_point;
1455 for (std::list<Inkscape::SnappedPoint>::const_iterator i = s.begin(); i != s.end(); i++) {
1456 if (i->getSnapped()) {
1457 if (best_snapped_point.isOtherSnapBetter(*i, true)) {
1458 best_snapped_point = *i;
1459 dxy = i->getTransformation();
1460 }
1461 }
1462 }
1463 if (best_snapped_point.getSnapped()) {
1464 _desktop->snapindicator->set_new_snaptarget(best_snapped_point);
1465 } else {
1466 // We didn't snap, so remove any previous snap indicator
1467 _desktop->snapindicator->remove_snaptarget();
1468 if (control) {
1469 // If we didn't snap, then we should still constrain horizontally or vertically
1470 // (When we did snap, then this constraint has already been enforced by
1471 // calling constrainedSnapTranslation() above)
1472 if (fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y])) {
1473 dxy[Geom::Y] = 0;
1474 } else {
1475 dxy[Geom::X] = 0;
1476 }
1477 }
1478 }
1479 }
1481 Geom::Matrix const move((Geom::Translate(dxy)));
1482 Geom::Point const norm(0, 0);
1483 transform(move, norm);
1485 // status text
1486 GString *xs = SP_PX_TO_METRIC_STRING(dxy[Geom::X], _desktop->namedview->getDefaultMetric());
1487 GString *ys = SP_PX_TO_METRIC_STRING(dxy[Geom::Y], _desktop->namedview->getDefaultMetric());
1488 _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);
1489 g_string_free(xs, TRUE);
1490 g_string_free(ys, TRUE);
1491 }
1493 // Given a location of a handle at the visual bounding box, find the corresponding location at the
1494 // geometrical bounding box
1495 Geom::Point Inkscape::SelTrans::_getGeomHandlePos(Geom::Point const &visual_handle_pos)
1496 {
1497 if ( _snap_bbox_type == SPItem::GEOMETRIC_BBOX) {
1498 // When the selector tool is using geometric bboxes, then the handle is already
1499 // located at one of the geometric bbox corners
1500 return visual_handle_pos;
1501 }
1503 if (!_geometric_bbox) {
1504 //_getGeomHandlePos() can only be used after _geometric_bbox has been defined!
1505 return visual_handle_pos;
1506 }
1508 // Using the Geom::Rect constructor below ensures that "min() < max()", which is important
1509 // because this will also hold for _bbox, and which is required for get_scale_transform_with_stroke()
1510 Geom::Rect new_bbox = Geom::Rect(_origin_for_bboxpoints, visual_handle_pos); // new visual bounding box
1511 // Please note that the new_bbox might in fact be just a single line, for example when stretching (in
1512 // which case the handle and origin will be aligned vertically or horizontally)
1513 Geom::Point normalized_handle_pos = (visual_handle_pos - new_bbox.min()) * Geom::Scale(new_bbox.dimensions()).inverse();
1515 // Calculate the absolute affine while taking into account the scaling of the stroke width
1516 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1517 bool transform_stroke = prefs->getBool("/options/transform/stroke", true);
1518 Geom::Matrix abs_affine = get_scale_transform_with_stroke (*_bbox, _strokewidth, transform_stroke,
1519 new_bbox.min()[Geom::X], new_bbox.min()[Geom::Y], new_bbox.max()[Geom::X], new_bbox.max()[Geom::Y]);
1521 // Calculate the scaled geometrical bbox
1522 Geom::Rect new_geom_bbox = Geom::Rect(_geometric_bbox->min() * abs_affine, _geometric_bbox->max() * abs_affine);
1523 // Find the location of the handle on this new geometrical bbox
1524 return normalized_handle_pos * Geom::Scale(new_geom_bbox.dimensions()) + new_geom_bbox.min(); //new position of the geometric handle
1525 }
1527 Geom::Scale Inkscape::calcScaleFactors(Geom::Point const &initial_point, Geom::Point const &new_point, Geom::Point const &origin, bool const skew)
1528 {
1529 // Work out the new scale factors for the bbox
1531 Geom::Point const initial_delta = initial_point - origin;
1532 Geom::Point const new_delta = new_point - origin;
1533 Geom::Point const offset = new_point - initial_point;
1534 Geom::Scale scale(1, 1);
1536 for ( unsigned int i = 0 ; i < 2 ; i++ ) {
1537 if ( fabs(initial_delta[i]) > 1e-6 ) {
1538 if (skew) {
1539 scale[i] = offset[1-i] / initial_delta[i];
1540 } else {
1541 scale[i] = new_delta[i] / initial_delta[i];
1542 }
1543 }
1544 }
1546 return scale;
1547 }
1549 // Only for scaling/stretching
1550 Geom::Point Inkscape::SelTrans::_calcAbsAffineDefault(Geom::Scale const default_scale)
1551 {
1552 Geom::Matrix abs_affine = Geom::Translate(-_origin) * Geom::Matrix(default_scale) * Geom::Translate(_origin);
1553 Geom::Point new_bbox_min = _approximate_bbox->min() * abs_affine;
1554 Geom::Point new_bbox_max = _approximate_bbox->max() * abs_affine;
1556 bool transform_stroke = false;
1557 gdouble strokewidth = 0;
1559 if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
1560 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1561 transform_stroke = prefs->getBool("/options/transform/stroke", true);
1562 strokewidth = _strokewidth;
1563 }
1565 _absolute_affine = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
1566 new_bbox_min[Geom::X], new_bbox_min[Geom::Y], new_bbox_max[Geom::X], new_bbox_max[Geom::Y]);
1568 // return the new handle position
1569 return ( _point - _origin ) * default_scale + _origin;
1570 }
1572 // Only for scaling/stretching
1573 Geom::Point Inkscape::SelTrans::_calcAbsAffineGeom(Geom::Scale const geom_scale)
1574 {
1575 _relative_affine = Geom::Matrix(geom_scale);
1576 _absolute_affine = Geom::Translate(-_origin_for_specpoints) * _relative_affine * Geom::Translate(_origin_for_specpoints);
1578 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1579 bool const transform_stroke = prefs->getBool("/options/transform/stroke", true);
1580 Geom::Rect visual_bbox = get_visual_bbox(_geometric_bbox, _absolute_affine, _strokewidth, transform_stroke);
1582 // return the new handle position
1583 return visual_bbox.min() + visual_bbox.dimensions() * Geom::Scale(_handle_x, _handle_y);
1584 }
1586 void Inkscape::SelTrans::_keepClosestPointOnly(std::vector<Geom::Point> &points, const Geom::Point &reference)
1587 {
1588 if (points.size() < 2) return;
1590 Geom::Point closest_point = Geom::Point(NR_HUGE, NR_HUGE);
1591 Geom::Coord closest_dist = NR_HUGE;
1593 for(std::vector<Geom::Point>::const_iterator i = points.begin(); i != points.end(); i++) {
1594 Geom::Coord dist = Geom::L2(*i - reference);
1595 if (i == points.begin() || dist < closest_dist) {
1596 closest_point = *i;
1597 closest_dist = dist;
1598 }
1599 }
1601 points.clear();
1602 points.push_back(closest_point);
1603 }
1605 /*
1606 Local Variables:
1607 mode:c++
1608 c-file-style:"stroustrup"
1609 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1610 indent-tabs-mode:nil
1611 fill-column:99
1612 End:
1613 */
1614 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :