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 _snap_points.clear();
293 _snap_points = selection->getSnapPoints(&m.snapprefs);
294 std::vector<Inkscape::SnapCandidatePoint> snap_points_hull = selection->getSnapPointsConvexHull(&m.snapprefs);
295 if (_snap_points.size() > 200) {
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 if (prefs->getBool("/options/snapclosestonly/value", false)) {
300 _keepClosestPointOnly(_snap_points, p);
301 } else {
302 _snap_points = snap_points_hull;
303 }
304 // Unfortunately, by now we will have lost the font-baseline snappoints :-(
305 }
307 // Find bbox hulling all special points, which excludes stroke width. Here we need to include the
308 // path nodes, for example because a rectangle which has been converted to a path doesn't have
309 // any other special points
310 Geom::Rect snap_points_bbox;
311 if ( snap_points_hull.empty() == false ) {
312 std::vector<Inkscape::SnapCandidatePoint>::iterator i = snap_points_hull.begin();
313 snap_points_bbox = Geom::Rect((*i).getPoint(), (*i).getPoint());
314 i++;
315 while (i != snap_points_hull.end()) {
316 snap_points_bbox.expandTo((*i).getPoint());
317 i++;
318 }
319 }
321 _bbox_points.clear();
322 _bbox_points_for_translating.clear();
323 // Collect the bounding box's corners and midpoints for each selected item
324 if (m.snapprefs.getSnapModeBBox()) {
325 bool mp = m.snapprefs.getSnapBBoxMidpoints();
326 bool emp = m.snapprefs.getSnapBBoxEdgeMidpoints();
327 // Preferably we'd use the bbox of each selected item, instead of the bbox of the selection as a whole; for translations
328 // this is easy to do, but when snapping the visual bbox while scaling we will have to compensate for the scaling of the
329 // stroke width. (see get_scale_transform_with_stroke()). This however is currently only implemented for a single bbox.
330 // That's why we have both _bbox_points_for_translating and _bbox_points.
331 getBBoxPoints(selection->bounds(_snap_bbox_type), &_bbox_points, false, true, emp, mp);
332 if (((_items.size() > 0) && (_items.size() < 50)) || prefs->getBool("/options/snapclosestonly/value", false)) {
333 // More than 50 items will produce at least 200 bbox points, which might make Inkscape crawl
334 // (see the comment a few lines above). In that case we will use the bbox of the selection as a whole
335 for (unsigned i = 0; i < _items.size(); i++) {
336 getBBoxPoints(sp_item_bbox_desktop(_items[i], _snap_bbox_type), &_bbox_points_for_translating, false, true, emp, mp);
337 }
338 } else {
339 _bbox_points_for_translating = _bbox_points; // use the bbox points of the selection as a whole
340 }
341 }
343 if (_bbox) {
344 // There are two separate "opposites" (i.e. opposite w.r.t. the handle being dragged):
345 // - one for snapping the boundingbox, which can be either visual or geometric
346 // - one for snapping the special points
347 // The "opposite" in case of a geometric boundingbox always coincides with the "opposite" for the special points
348 // These distinct "opposites" are needed in the snapmanager to avoid bugs such as #sf1540195 (in which
349 // a box is caught between two guides)
350 _opposite_for_bboxpoints = _bbox->min() + _bbox->dimensions() * Geom::Scale(1-x, 1-y);
351 _opposite_for_specpoints = snap_points_bbox.min() + snap_points_bbox.dimensions() * Geom::Scale(1-x, 1-y);
352 _opposite = _opposite_for_bboxpoints;
353 }
355 // When snapping the node closest to the mouse pointer is absolutely preferred over the closest snap
356 // (i.e. when weight == 1), then we will not even try to snap to other points and discard those other
357 // points immediately.
359 if (prefs->getBool("/options/snapclosestonly/value", false)) {
360 if (m.snapprefs.getSnapModeNode()) {
361 _keepClosestPointOnly(_snap_points, p);
362 } else {
363 _snap_points.clear(); // don't keep any point
364 }
366 if (m.snapprefs.getSnapModeBBox()) {
367 _keepClosestPointOnly(_bbox_points, p);
368 _keepClosestPointOnly(_bbox_points_for_translating, p);
369 } else {
370 _bbox_points.clear(); // don't keep any point
371 _bbox_points_for_translating.clear();
372 }
374 // Each of the three vectors of snappoints now contains either one snappoint or none at all.
375 if (_snap_points.size() > 1 || _bbox_points.size() > 1 || _bbox_points_for_translating.size() > 1) {
376 g_warning("Incorrect assumption encountered while finding the snap source; nothing serious, but please report to Diederik");
377 }
379 // Now let's reduce this to a single closest snappoint
380 Geom::Coord dsp = _snap_points.size() == 1 ? Geom::L2((_snap_points.at(0)).getPoint() - p) : NR_HUGE;
381 Geom::Coord dbbp = _bbox_points.size() == 1 ? Geom::L2((_bbox_points.at(0)).getPoint() - p) : NR_HUGE;
382 Geom::Coord dbbpft = _bbox_points_for_translating.size() == 1 ? Geom::L2((_bbox_points_for_translating.at(0)).getPoint() - p) : NR_HUGE;
384 if (translating) {
385 _bbox_points.clear();
386 if (dsp > dbbpft) {
387 _snap_points.clear();
388 } else {
389 _bbox_points_for_translating.clear();
390 }
391 } else {
392 _bbox_points_for_translating.clear();
393 if (dsp > dbbp) {
394 _snap_points.clear();
395 } else {
396 _bbox_points.clear();
397 }
398 }
400 if ((_snap_points.size() + _bbox_points.size() + _bbox_points_for_translating.size()) > 1) {
401 g_warning("Checking number of snap sources failed; nothing serious, but please report to Diederik");
402 }
404 }
406 if ((x != -1) && (y != -1)) {
407 sp_canvas_item_show(_norm);
408 sp_canvas_item_show(_grip);
409 }
411 if (_show == SHOW_OUTLINE) {
412 for (int i = 0; i < 4; i++)
413 sp_canvas_item_show(_l[i]);
414 }
416 _updateHandles();
417 g_return_if_fail(_stamp_cache == NULL);
418 }
420 void Inkscape::SelTrans::transform(Geom::Matrix const &rel_affine, Geom::Point const &norm)
421 {
422 g_return_if_fail(_grabbed);
423 g_return_if_fail(!_empty);
425 Geom::Matrix const affine( Geom::Translate(-norm) * rel_affine * Geom::Translate(norm) );
427 if (_show == SHOW_CONTENT) {
428 // update the content
429 for (unsigned i = 0; i < _items.size(); i++) {
430 SPItem &item = *_items[i];
431 Geom::Matrix const &prev_transform = _items_affines[i];
432 sp_item_set_i2d_affine(&item, prev_transform * affine);
433 }
434 } else {
435 if (_bbox) {
436 Geom::Point p[4];
437 /* update the outline */
438 for (unsigned i = 0 ; i < 4 ; i++) {
439 p[i] = _bbox->corner(i) * affine;
440 }
441 for (unsigned i = 0 ; i < 4 ; i++) {
442 sp_ctrlline_set_coords(SP_CTRLLINE(_l[i]), p[i], p[(i+1)%4]);
443 }
444 }
445 }
447 _current_relative_affine = affine;
448 _changed = true;
449 _updateHandles();
450 }
452 void Inkscape::SelTrans::ungrab()
453 {
454 g_return_if_fail(_grabbed);
455 _grabbed = false;
456 _show_handles = true;
458 _desktop->snapindicator->remove_snapsource();
460 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
461 _updateVolatileState();
463 for (unsigned i = 0; i < _items.size(); i++) {
464 sp_object_unref(SP_OBJECT(_items[i]), NULL);
465 }
467 sp_canvas_item_hide(_norm);
468 sp_canvas_item_hide(_grip);
470 if (_show == SHOW_OUTLINE) {
471 for (int i = 0; i < 4; i++)
472 sp_canvas_item_hide(_l[i]);
473 }
475 if (_stamp_cache) {
476 g_slist_free(_stamp_cache);
477 _stamp_cache = NULL;
478 }
480 _message_context.clear();
482 if (!_empty && _changed) {
483 sp_selection_apply_affine(selection, _current_relative_affine, (_show == SHOW_OUTLINE)? true : false);
484 if (_center) {
485 *_center *= _current_relative_affine;
486 _center_is_set = true;
487 }
489 // If dragging showed content live, sp_selection_apply_affine cannot change the centers
490 // appropriately - it does not know the original positions of the centers (all objects already have
491 // the new bboxes). So we need to reset the centers from our saved array.
492 if (_show != SHOW_OUTLINE && !_current_relative_affine.isTranslation()) {
493 for (unsigned i = 0; i < _items_centers.size(); i++) {
494 SPItem *currentItem = _items[i];
495 if (currentItem->isCenterSet()) { // only if it's already set
496 currentItem->setCenter (_items_centers[i] * _current_relative_affine);
497 SP_OBJECT(currentItem)->updateRepr();
498 }
499 }
500 }
502 _items.clear();
503 _items_const.clear();
504 _items_affines.clear();
505 _items_centers.clear();
507 if (_current_relative_affine.isTranslation()) {
508 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
509 _("Move"));
510 } else if (_current_relative_affine.without_translation().isScale()) {
511 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
512 _("Scale"));
513 } else if (_current_relative_affine.without_translation().isRotation()) {
514 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
515 _("Rotate"));
516 } else {
517 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
518 _("Skew"));
519 }
521 } else {
523 if (_center_is_set) {
524 // we were dragging center; update reprs and commit undoable action
525 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
526 SPItem *it = (SPItem*)SP_OBJECT(l->data);
527 SP_OBJECT(it)->updateRepr();
528 }
529 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
530 _("Set center"));
531 }
533 _items.clear();
534 _items_const.clear();
535 _items_affines.clear();
536 _items_centers.clear();
537 _updateHandles();
538 }
539 }
541 /* fixme: This is really bad, as we compare positions for each stamp (Lauris) */
542 /* fixme: IMHO the best way to keep sort cache would be to implement timestamping at last */
544 void Inkscape::SelTrans::stamp()
545 {
546 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
548 bool fixup = !_grabbed;
549 if ( fixup && _stamp_cache ) {
550 // TODO - give a proper fix. Simple temproary work-around for the grab() issue
551 g_slist_free(_stamp_cache);
552 _stamp_cache = NULL;
553 }
555 /* stamping mode */
556 if (!_empty) {
557 GSList *l;
558 if (_stamp_cache) {
559 l = _stamp_cache;
560 } else {
561 /* Build cache */
562 l = g_slist_copy((GSList *) selection->itemList());
563 l = g_slist_sort(l, (GCompareFunc) sp_object_compare_position);
564 _stamp_cache = l;
565 }
567 while (l) {
568 SPItem *original_item = SP_ITEM(l->data);
569 Inkscape::XML::Node *original_repr = SP_OBJECT_REPR(original_item);
571 // remember the position of the item
572 gint pos = original_repr->position();
573 // remember parent
574 Inkscape::XML::Node *parent = sp_repr_parent(original_repr);
576 Inkscape::XML::Node *copy_repr = original_repr->duplicate(parent->document());
578 // add the new repr to the parent
579 parent->appendChild(copy_repr);
580 // move to the saved position
581 copy_repr->setPosition(pos > 0 ? pos : 0);
583 SPItem *copy_item = (SPItem *) sp_desktop_document(_desktop)->getObjectByRepr(copy_repr);
585 Geom::Matrix const *new_affine;
586 if (_show == SHOW_OUTLINE) {
587 Geom::Matrix const i2d(sp_item_i2d_affine(original_item));
588 Geom::Matrix const i2dnew( i2d * _current_relative_affine );
589 sp_item_set_i2d_affine(copy_item, i2dnew);
590 new_affine = ©_item->transform;
591 } else {
592 new_affine = &original_item->transform;
593 }
595 sp_item_write_transform(copy_item, copy_repr, *new_affine);
597 if ( copy_item->isCenterSet() && _center ) {
598 copy_item->setCenter(*_center * _current_relative_affine);
599 }
601 Inkscape::GC::release(copy_repr);
602 l = l->next;
603 }
604 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
605 _("Stamp"));
606 }
608 if ( fixup && _stamp_cache ) {
609 // TODO - give a proper fix. Simple temproary work-around for the grab() issue
610 g_slist_free(_stamp_cache);
611 _stamp_cache = NULL;
612 }
613 }
615 void Inkscape::SelTrans::_updateHandles()
616 {
617 if ( !_show_handles || _empty )
618 {
619 sp_remove_handles(_shandle, 8);
620 sp_remove_handles(_rhandle, 8);
621 sp_remove_handles(&_chandle, 1);
622 return;
623 }
625 // center handle
626 if ( _chandle == NULL ) {
627 _chandle = sp_knot_new(_desktop, _("<b>Center</b> of rotation and skewing: drag to reposition; scaling with Shift also uses this center"));
629 _chandle->setShape (SP_CTRL_SHAPE_BITMAP);
630 _chandle->setSize (13);
631 _chandle->setAnchor (handle_center.anchor);
632 _chandle->setMode (SP_CTRL_MODE_XOR);
633 _chandle->setFill(0x00000000, 0x00000000, 0x00000000);
634 _chandle->setStroke(0x000000ff, 0xff0000b0, 0xff0000b0);
635 _chandle->setPixbuf(handles[handle_center.control]);
636 sp_knot_update_ctrl(_chandle);
638 g_signal_connect(G_OBJECT(_chandle), "request",
639 G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle_center);
640 g_signal_connect(G_OBJECT(_chandle), "moved",
641 G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle_center);
642 g_signal_connect(G_OBJECT(_chandle), "grabbed",
643 G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle_center);
644 g_signal_connect(G_OBJECT(_chandle), "ungrabbed",
645 G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle_center);
646 g_signal_connect(G_OBJECT(_chandle), "clicked",
647 G_CALLBACK(sp_sel_trans_handle_click), (gpointer) &handle_center);
648 }
650 sp_remove_handles(&_chandle, 1);
651 if ( _state == STATE_SCALE ) {
652 sp_remove_handles(_rhandle, 8);
653 _showHandles(_shandle, handles_scale, 8,
654 _("<b>Squeeze or stretch</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"),
655 _("<b>Scale</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"));
656 } else {
657 sp_remove_handles(_shandle, 8);
658 _showHandles(_rhandle, handles_rotate, 8,
659 _("<b>Skew</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to skew around the opposite side"),
660 _("<b>Rotate</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to rotate around the opposite corner"));
661 }
663 if (!_center_is_set) {
664 _center = _desktop->selection->center();
665 _center_is_set = true;
666 }
668 if ( _state == STATE_SCALE || !_center ) {
669 sp_knot_hide(_chandle);
670 } else {
671 sp_knot_show(_chandle);
672 sp_knot_moveto(_chandle, *_center);
673 }
674 }
676 void Inkscape::SelTrans::_updateVolatileState()
677 {
678 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
679 _empty = selection->isEmpty();
681 if (_empty) {
682 return;
683 }
685 //Update the bboxes
686 _bbox = selection->bounds(_snap_bbox_type);
687 _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX);
689 if (!_bbox) {
690 _empty = true;
691 return;
692 }
694 _strokewidth = stroke_average_width (selection->itemList());
695 }
697 static void sp_remove_handles(SPKnot *knot[], gint num)
698 {
699 for (int i = 0; i < num; i++) {
700 if (knot[i] != NULL) {
701 sp_knot_hide(knot[i]);
702 }
703 }
704 }
706 void Inkscape::SelTrans::_showHandles(SPKnot *knot[], SPSelTransHandle const handle[], gint num,
707 gchar const *even_tip, gchar const *odd_tip)
708 {
709 g_return_if_fail( !_empty );
711 for (int i = 0; i < num; i++) {
712 if (knot[i] == NULL) {
713 knot[i] = sp_knot_new(_desktop, i % 2 ? even_tip : odd_tip);
715 knot[i]->setShape (SP_CTRL_SHAPE_BITMAP);
716 knot[i]->setSize (13);
717 knot[i]->setAnchor (handle[i].anchor);
718 knot[i]->setMode (SP_CTRL_MODE_XOR);
719 knot[i]->setFill(0x000000ff, 0x00ff6600, 0x00ff6600); // inversion, green, green
720 knot[i]->setStroke(0x000000ff, 0x000000ff, 0x000000ff); // inversion
721 knot[i]->setPixbuf(handles[handle[i].control]);
722 sp_knot_update_ctrl(knot[i]);
724 g_signal_connect(G_OBJECT(knot[i]), "request",
725 G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle[i]);
726 g_signal_connect(G_OBJECT(knot[i]), "moved",
727 G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle[i]);
728 g_signal_connect(G_OBJECT(knot[i]), "grabbed",
729 G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle[i]);
730 g_signal_connect(G_OBJECT(knot[i]), "ungrabbed",
731 G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle[i]);
732 g_signal_connect(G_OBJECT(knot[i]), "event", G_CALLBACK(sp_seltrans_handle_event), (gpointer) &handle[i]);
733 }
734 sp_knot_show(knot[i]);
736 Geom::Point const handle_pt(handle[i].x, handle[i].y);
737 // shouldn't have nullary bbox, but knots
738 g_assert(_bbox);
739 Geom::Point p( _bbox->min()
740 + ( _bbox->dimensions()
741 * Geom::Scale(handle_pt) ) );
743 sp_knot_moveto(knot[i], p);
744 }
745 }
747 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data)
748 {
749 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleGrab(
750 knot, state, *(SPSelTransHandle const *) data
751 );
752 }
754 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint /*state*/, gpointer /*data*/)
755 {
756 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->ungrab();
757 }
759 static void sp_sel_trans_handle_new_event(SPKnot *knot, Geom::Point *position, guint state, gpointer data)
760 {
761 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleNewEvent(
762 knot, position, state, *(SPSelTransHandle const *) data
763 );
764 }
766 static gboolean sp_sel_trans_handle_request(SPKnot *knot, Geom::Point *position, guint state, gboolean *data)
767 {
768 return SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleRequest(
769 knot, position, state, *(SPSelTransHandle const *) data
770 );
771 }
773 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data)
774 {
775 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleClick(
776 knot, state, *(SPSelTransHandle const *) data
777 );
778 }
780 void Inkscape::SelTrans::handleClick(SPKnot */*knot*/, guint state, SPSelTransHandle const &handle)
781 {
782 switch (handle.anchor) {
783 case GTK_ANCHOR_CENTER:
784 if (state & GDK_SHIFT_MASK) {
785 // Unset the center position for all selected items
786 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
787 SPItem *it = (SPItem*)(SP_OBJECT(l->data));
788 it->unsetCenter();
789 SP_OBJECT(it)->updateRepr();
790 _center_is_set = false; // center has changed
791 _updateHandles();
792 }
793 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
794 _("Reset center"));
795 }
796 break;
797 default:
798 break;
799 }
800 }
802 void Inkscape::SelTrans::handleGrab(SPKnot *knot, guint /*state*/, SPSelTransHandle const &handle)
803 {
804 switch (handle.anchor) {
805 case GTK_ANCHOR_CENTER:
806 g_object_set(G_OBJECT(_grip),
807 "shape", SP_CTRL_SHAPE_BITMAP,
808 "size", 13.0,
809 NULL);
810 sp_canvas_item_show(_grip);
811 break;
812 default:
813 g_object_set(G_OBJECT(_grip),
814 "shape", SP_CTRL_SHAPE_CROSS,
815 "size", 7.0,
816 NULL);
817 sp_canvas_item_show(_norm);
818 sp_canvas_item_show(_grip);
820 break;
821 }
823 grab(sp_knot_position(knot), handle.x, handle.y, FALSE, FALSE);
824 }
827 void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const &handle)
828 {
829 if (!SP_KNOT_IS_GRABBED(knot)) {
830 return;
831 }
833 // in case items have been unhooked from the document, don't
834 // try to continue processing events for them.
835 for (unsigned int i = 0; i < _items.size(); i++) {
836 if (!SP_OBJECT_DOCUMENT(SP_OBJECT(_items[i])) ) {
837 return;
838 }
839 }
841 handle.action(this, handle, *position, state);
842 }
845 gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const &handle)
846 {
847 if (!SP_KNOT_IS_GRABBED(knot)) {
848 return TRUE;
849 }
851 knot->desktop->setPosition(*position);
853 // When holding shift while rotating or skewing, the transformation will be
854 // relative to the point opposite of the handle; otherwise it will be relative
855 // to the center as set for the selection
856 if ((!(state & GDK_SHIFT_MASK) == !(_state == STATE_ROTATE)) && (&handle != &handle_center)) {
857 _origin = _opposite;
858 _origin_for_bboxpoints = _opposite_for_bboxpoints;
859 _origin_for_specpoints = _opposite_for_specpoints;
860 } else if (_center) {
861 _origin = *_center;
862 _origin_for_bboxpoints = *_center;
863 _origin_for_specpoints = *_center;
864 } else {
865 // FIXME
866 return TRUE;
867 }
868 if (handle.request(this, handle, *position, state)) {
869 sp_knot_set_position(knot, *position, state);
870 SP_CTRL(_grip)->moveto(*position);
871 if (&handle == &handle_center) {
872 SP_CTRL(_norm)->moveto(*position);
873 } else {
874 SP_CTRL(_norm)->moveto(_origin);
875 }
876 }
878 return TRUE;
879 }
882 void Inkscape::SelTrans::_selChanged(Inkscape::Selection */*selection*/)
883 {
884 if (!_grabbed) {
885 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
886 // reread in case it changed on the fly:
887 int prefs_bbox = prefs->getBool("/tools/bounding_box");
888 _snap_bbox_type = !prefs_bbox ?
889 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
890 //SPItem::APPROXIMATE_BBOX will be replaced by SPItem::VISUAL_BBOX, as soon as the latter is implemented properly
892 _updateVolatileState();
893 _current_relative_affine.setIdentity();
894 _center_is_set = false; // center(s) may have changed
895 _updateHandles();
896 }
897 }
899 void Inkscape::SelTrans::_selModified(Inkscape::Selection */*selection*/, guint /*flags*/)
900 {
901 if (!_grabbed) {
902 _updateVolatileState();
903 _current_relative_affine.setIdentity();
905 // reset internal flag
906 _changed = false;
908 _center_is_set = false; // center(s) may have changed
910 _updateHandles();
911 }
912 }
914 /*
915 * handlers for handle move-request
916 */
918 /** Returns -1 or 1 according to the sign of x. Returns 1 for 0 and NaN. */
919 static double sign(double const x)
920 {
921 return ( x < 0
922 ? -1
923 : 1 );
924 }
926 gboolean sp_sel_trans_scale_request(Inkscape::SelTrans *seltrans,
927 SPSelTransHandle const &, Geom::Point &pt, guint state)
928 {
929 return seltrans->scaleRequest(pt, state);
930 }
932 gboolean sp_sel_trans_stretch_request(Inkscape::SelTrans *seltrans,
933 SPSelTransHandle const &handle, Geom::Point &pt, guint state)
934 {
935 return seltrans->stretchRequest(handle, pt, state);
936 }
938 gboolean sp_sel_trans_skew_request(Inkscape::SelTrans *seltrans,
939 SPSelTransHandle const &handle, Geom::Point &pt, guint state)
940 {
941 return seltrans->skewRequest(handle, pt, state);
942 }
944 gboolean sp_sel_trans_rotate_request(Inkscape::SelTrans *seltrans,
945 SPSelTransHandle const &, Geom::Point &pt, guint state)
946 {
947 return seltrans->rotateRequest(pt, state);
948 }
950 gboolean sp_sel_trans_center_request(Inkscape::SelTrans *seltrans,
951 SPSelTransHandle const &, Geom::Point &pt, guint state)
952 {
953 return seltrans->centerRequest(pt, state);
954 }
956 gboolean Inkscape::SelTrans::scaleRequest(Geom::Point &pt, guint state)
957 {
959 // Calculate the scale factors, which can be either visual or geometric
960 // depending on which type of bbox is currently being used (see preferences -> selector tool)
961 Geom::Scale default_scale = calcScaleFactors(_point, pt, _origin);
963 // Find the scale factors for the geometric bbox
964 Geom::Point pt_geom = _getGeomHandlePos(pt);
965 Geom::Scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
967 _absolute_affine = Geom::identity(); //Initialize the scaler
969 if (state & GDK_MOD1_MASK) { // scale by an integer multiplier/divider
970 // We're scaling either the visual or the geometric bbox here (see the comment above)
971 for ( unsigned int i = 0 ; i < 2 ; i++ ) {
972 if (fabs(default_scale[i]) > 1) {
973 default_scale[i] = round(default_scale[i]);
974 } else if (default_scale[i] != 0) {
975 default_scale[i] = 1/round(1/(MIN(default_scale[i], 10)));
976 }
977 }
978 // Update the knot position
979 pt = _calcAbsAffineDefault(default_scale);
980 // When scaling by an integer, snapping is not needed
981 } else {
982 // In all other cases we should try to snap now
983 SnapManager &m = _desktop->namedview->snap_manager;
984 m.setup(_desktop, false, _items_const);
986 Inkscape::SnappedPoint bb, sn;
988 if ((state & GDK_CONTROL_MASK) || _desktop->isToolboxButtonActive ("lock")) {
989 // Scale is locked to a 1:1 aspect ratio, so that s[X] must be made to equal s[Y].
990 //
991 // The aspect-ratio must be locked before snapping
992 if (fabs(default_scale[Geom::X]) > fabs(default_scale[Geom::Y])) {
993 default_scale[Geom::X] = fabs(default_scale[Geom::Y]) * sign(default_scale[Geom::X]);
994 geom_scale[Geom::X] = fabs(geom_scale[Geom::Y]) * sign(geom_scale[Geom::X]);
995 } else {
996 default_scale[Geom::Y] = fabs(default_scale[Geom::X]) * sign(default_scale[Geom::Y]);
997 geom_scale[Geom::Y] = fabs(geom_scale[Geom::X]) * sign(geom_scale[Geom::Y]);
998 }
1000 // Snap along a suitable constraint vector from the origin.
1001 bb = m.constrainedSnapScale(_bbox_points, _point, default_scale, _origin_for_bboxpoints);
1002 sn = m.constrainedSnapScale(_snap_points, _point, geom_scale, _origin_for_specpoints);
1003 } else {
1004 /* Scale aspect ratio is unlocked */
1005 bb = m.freeSnapScale(_bbox_points, _point, default_scale, _origin_for_bboxpoints);
1006 sn = m.freeSnapScale(_snap_points, _point, geom_scale, _origin_for_specpoints);
1007 }
1009 if (!(bb.getSnapped() || sn.getSnapped())) {
1010 // We didn't snap at all! Don't update the handle position, just calculate the new transformation
1011 _calcAbsAffineDefault(default_scale);
1012 _desktop->snapindicator->remove_snaptarget();
1013 } else if (bb.getSnapped() && !bb.isOtherSnapBetter(sn, false)) {
1014 // We snapped the bbox (which is either visual or geometric)
1015 _desktop->snapindicator->set_new_snaptarget(bb);
1016 default_scale = Geom::Scale(bb.getTransformation());
1017 // Calculate the new transformation and update the handle position
1018 pt = _calcAbsAffineDefault(default_scale);
1019 } else {
1020 _desktop->snapindicator->set_new_snaptarget(sn);
1021 // We snapped the special points (e.g. nodes), which are not at the visual bbox
1022 // The handle location however (pt) might however be at the visual bbox, so we
1023 // will have to calculate pt taking the stroke width into account
1024 geom_scale = Geom::Scale(sn.getTransformation());
1025 pt = _calcAbsAffineGeom(geom_scale);
1026 }
1027 m.unSetup();
1028 }
1030 /* Status text */
1031 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1032 _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1033 100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1035 return TRUE;
1036 }
1038 gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1039 {
1040 Geom::Dim2 axis, perp;
1041 switch (handle.cursor) {
1042 case GDK_TOP_SIDE:
1043 case GDK_BOTTOM_SIDE:
1044 axis = Geom::Y;
1045 perp = Geom::X;
1046 break;
1047 case GDK_LEFT_SIDE:
1048 case GDK_RIGHT_SIDE:
1049 axis = Geom::X;
1050 perp = Geom::Y;
1051 break;
1052 default:
1053 g_assert_not_reached();
1054 return TRUE;
1055 };
1057 // Calculate the scale factors, which can be either visual or geometric
1058 // depending on which type of bbox is currently being used (see preferences -> selector tool)
1059 Geom::Scale default_scale = calcScaleFactors(_point, pt, _origin);
1060 default_scale[perp] = 1;
1062 // Find the scale factors for the geometric bbox
1063 Geom::Point pt_geom = _getGeomHandlePos(pt);
1064 Geom::Scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
1065 geom_scale[perp] = 1;
1067 _absolute_affine = Geom::identity(); //Initialize the scaler
1069 if (state & GDK_MOD1_MASK) { // stretch by an integer multiplier/divider
1070 if (fabs(default_scale[axis]) > 1) {
1071 default_scale[axis] = round(default_scale[axis]);
1072 } else if (default_scale[axis] != 0) {
1073 default_scale[axis] = 1/round(1/(MIN(default_scale[axis], 10)));
1074 }
1075 // Calculate the new transformation and update the handle position
1076 pt = _calcAbsAffineDefault(default_scale);
1077 // When stretching by an integer, snapping is not needed
1078 } else {
1079 // In all other cases we should try to snap now
1081 SnapManager &m = _desktop->namedview->snap_manager;
1082 m.setup(_desktop, false, _items_const);
1084 Inkscape::SnappedPoint bb, sn;
1085 g_assert(bb.getSnapped() == false); // Check initialization to catch any regression
1087 bool symmetrical = state & GDK_CONTROL_MASK;
1089 bb = m.constrainedSnapStretch(_bbox_points, _point, Geom::Coord(default_scale[axis]), _origin_for_bboxpoints, Geom::Dim2(axis), symmetrical);
1090 sn = m.constrainedSnapStretch(_snap_points, _point, Geom::Coord(geom_scale[axis]), _origin_for_specpoints, Geom::Dim2(axis), symmetrical);
1092 if (bb.getSnapped()) {
1093 // We snapped the bbox (which is either visual or geometric)
1094 default_scale[axis] = bb.getTransformation()[axis];
1095 }
1097 if (sn.getSnapped()) {
1098 geom_scale[axis] = sn.getTransformation()[axis];
1099 }
1101 if (symmetrical) {
1102 // on ctrl, apply symmetrical scaling instead of stretching
1103 // Preserve aspect ratio, but never flip in the dimension not being edited (by using fabs())
1104 default_scale[perp] = fabs(default_scale[axis]);
1105 geom_scale[perp] = fabs(geom_scale[axis]);
1106 }
1108 if (!(bb.getSnapped() || sn.getSnapped())) {
1109 // We didn't snap at all! Don't update the handle position, just calculate the new transformation
1110 _calcAbsAffineDefault(default_scale);
1111 _desktop->snapindicator->remove_snaptarget();
1112 } else if (bb.getSnapped() && !bb.isOtherSnapBetter(sn, false)) {
1113 _desktop->snapindicator->set_new_snaptarget(bb);
1114 // Calculate the new transformation and update the handle position
1115 pt = _calcAbsAffineDefault(default_scale);
1116 } else {
1117 _desktop->snapindicator->set_new_snaptarget(sn);
1118 // We snapped the special points (e.g. nodes), which are not at the visual bbox
1119 // The handle location however (pt) might however be at the visual bbox, so we
1120 // will have to calculate pt taking the stroke width into account
1121 pt = _calcAbsAffineGeom(geom_scale);
1122 }
1124 m.unSetup();
1125 }
1127 // status text
1128 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1129 _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1130 100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1132 return TRUE;
1133 }
1135 gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1136 {
1137 /* When skewing (or rotating):
1138 * 1) the stroke width will not change. This makes life much easier because we don't have to
1139 * account for that (like for scaling or stretching). As a consequence, all points will
1140 * have the same origin for the transformation and for the snapping.
1141 * 2) When holding shift, the transformation will be relative to the point opposite of
1142 * the handle; otherwise it will be relative to the center as set for the selection
1143 */
1145 Geom::Dim2 dim_a;
1146 Geom::Dim2 dim_b;
1148 switch (handle.cursor) {
1149 case GDK_SB_H_DOUBLE_ARROW:
1150 dim_a = Geom::Y;
1151 dim_b = Geom::X;
1152 break;
1153 case GDK_SB_V_DOUBLE_ARROW:
1154 dim_a = Geom::X;
1155 dim_b = Geom::Y;
1156 break;
1157 default:
1158 g_assert_not_reached();
1159 abort();
1160 break;
1161 }
1163 Geom::Point const initial_delta = _point - _origin;
1165 if (fabs(initial_delta[dim_a]) < 1e-15) {
1166 return false;
1167 }
1169 // Calculate the scale factors, which can be either visual or geometric
1170 // depending on which type of bbox is currently being used (see preferences -> selector tool)
1171 Geom::Scale scale = calcScaleFactors(_point, pt, _origin, false);
1172 Geom::Scale skew = calcScaleFactors(_point, pt, _origin, true);
1173 scale[dim_b] = 1;
1174 skew[dim_b] = 1;
1176 if (fabs(scale[dim_a]) < 1) {
1177 // Prevent shrinking of the selected object, while allowing mirroring
1178 scale[dim_a] = sign(scale[dim_a]);
1179 } else {
1180 // Allow expanding of the selected object by integer multiples
1181 scale[dim_a] = floor(scale[dim_a] + 0.5);
1182 }
1184 double radians = atan(skew[dim_a] / scale[dim_a]);
1186 if (state & GDK_CONTROL_MASK) {
1187 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1188 // Snap to defined angle increments
1189 int snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12);
1190 if (snaps) {
1191 double sections = floor(radians * snaps / M_PI + .5);
1192 if (fabs(sections) >= snaps / 2) {
1193 sections = sign(sections) * (snaps / 2 - 1);
1194 }
1195 radians = (M_PI / snaps) * sections;
1196 }
1197 skew[dim_a] = tan(radians) * scale[dim_a];
1198 } else {
1199 // Snap to objects, grids, guides
1201 SnapManager &m = _desktop->namedview->snap_manager;
1202 m.setup(_desktop, false, _items_const);
1204 Inkscape::Snapper::SnapConstraint const constraint(component_vectors[dim_b]);
1205 // When skewing, we cannot snap the corners of the bounding box, see the comment in "constrainedSnapSkew" for details
1206 Geom::Point const s(skew[dim_a], scale[dim_a]);
1207 Inkscape::SnappedPoint sn = m.constrainedSnapSkew(_snap_points, _point, constraint, s, _origin, Geom::Dim2(dim_b));
1209 if (sn.getSnapped()) {
1210 // We snapped something, so change the skew to reflect it
1211 Geom::Coord const sd = sn.getSnapped() ? sn.getTransformation()[0] : NR_HUGE;
1212 _desktop->snapindicator->set_new_snaptarget(sn);
1213 skew[dim_a] = sd;
1214 } else {
1215 _desktop->snapindicator->remove_snaptarget();
1216 }
1218 m.unSetup();
1219 }
1221 // Update the handle position
1222 pt[dim_b] = initial_delta[dim_a] * skew[dim_a] + _point[dim_b];
1223 pt[dim_a] = initial_delta[dim_a] * scale[dim_a] + _origin[dim_a];
1225 // Calculate the relative affine
1226 _relative_affine = Geom::identity();
1227 _relative_affine[2*dim_a + dim_a] = (pt[dim_a] - _origin[dim_a]) / initial_delta[dim_a];
1228 _relative_affine[2*dim_a + (dim_b)] = (pt[dim_b] - _point[dim_b]) / initial_delta[dim_a];
1229 _relative_affine[2*(dim_b) + (dim_a)] = 0;
1230 _relative_affine[2*(dim_b) + (dim_b)] = 1;
1232 for (int i = 0; i < 2; i++) {
1233 if (fabs(_relative_affine[3*i]) < 1e-15) {
1234 _relative_affine[3*i] = 1e-15;
1235 }
1236 }
1238 // Update the status text
1239 double degrees = mod360symm(Geom::rad_to_deg(radians));
1240 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1241 // TRANSLATORS: don't modify the first ";"
1242 // (it will NOT be displayed as ";" - only the second one will be)
1243 _("<b>Skew</b>: %0.2f°; with <b>Ctrl</b> to snap angle"),
1244 degrees);
1246 return TRUE;
1247 }
1249 gboolean Inkscape::SelTrans::rotateRequest(Geom::Point &pt, guint state)
1250 {
1251 /* When rotating (or skewing):
1252 * 1) the stroke width will not change. This makes life much easier because we don't have to
1253 * account for that (like for scaling or stretching). As a consequence, all points will
1254 * have the same origin for the transformation and for the snapping.
1255 * 2) When holding shift, the transformation will be relative to the point opposite of
1256 * the handle; otherwise it will be relative to the center as set for the selection
1257 */
1259 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1260 int snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12);
1262 // rotate affine in rotate
1263 Geom::Point const d1 = _point - _origin;
1264 Geom::Point const d2 = pt - _origin;
1266 Geom::Coord const h1 = Geom::L2(d1); // initial radius
1267 if (h1 < 1e-15) return FALSE;
1268 Geom::Point q1 = d1 / h1; // normalized initial vector to handle
1269 Geom::Coord const h2 = Geom::L2(d2); // new radius
1270 if (fabs(h2) < 1e-15) return FALSE;
1271 Geom::Point q2 = d2 / h2; // normalized new vector to handle
1273 Geom::Rotate r1(q1);
1274 Geom::Rotate r2(q2);
1276 double radians = atan2(Geom::dot(Geom::rot90(d1), d2), Geom::dot(d1, d2));;
1277 if (state & GDK_CONTROL_MASK) {
1278 // Snap to defined angle increments
1279 double cos_t = Geom::dot(q1, q2);
1280 double sin_t = Geom::dot(Geom::rot90(q1), q2);
1281 radians = atan2(sin_t, cos_t);
1282 if (snaps) {
1283 radians = ( M_PI / snaps ) * floor( radians * snaps / M_PI + .5 );
1284 }
1285 r1 = Geom::Rotate(0); //q1 = Geom::Point(1, 0);
1286 r2 = Geom::Rotate(radians); //q2 = Geom::Point(cos(radians), sin(radians));
1287 } else {
1288 SnapManager &m = _desktop->namedview->snap_manager;
1289 m.setup(_desktop, false, _items_const);
1290 // When rotating, we cannot snap the corners of the bounding box, see the comment in "constrainedSnapRotate" for details
1291 Inkscape::SnappedPoint sn = m.constrainedSnapRotate(_snap_points, _point, radians, _origin);
1292 m.unSetup();
1294 if (sn.getSnapped()) {
1295 _desktop->snapindicator->set_new_snaptarget(sn);
1296 // We snapped something, so change the rotation to reflect it
1297 radians = sn.getTransformation()[0];
1298 r1 = Geom::Rotate(0);
1299 r2 = Geom::Rotate(radians);
1300 } else {
1301 _desktop->snapindicator->remove_snaptarget();
1302 }
1304 }
1307 // Calculate the relative affine
1308 _relative_affine = r2 * r1.inverse();
1310 // Update the handle position
1311 pt = _point * Geom::Translate(-_origin) * _relative_affine * Geom::Translate(_origin);
1313 // Update the status text
1314 double degrees = mod360symm(Geom::rad_to_deg(radians));
1315 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1316 // TRANSLATORS: don't modify the first ";"
1317 // (it will NOT be displayed as ";" - only the second one will be)
1318 _("<b>Rotate</b>: %0.2f°; with <b>Ctrl</b> to snap angle"), degrees);
1320 return TRUE;
1321 }
1323 // Move the item's transformation center
1324 gboolean Inkscape::SelTrans::centerRequest(Geom::Point &pt, guint state)
1325 {
1326 // When dragging the transformation center while multiple items have been selected, then those
1327 // items will share a single center. While dragging that single center, it should never snap to the
1328 // centers of any of the selected objects. Therefore we will have to pass the list of selected items
1329 // to the snapper, to avoid self-snapping of the rotation center
1330 GSList *items = (GSList *) const_cast<Selection *>(_selection)->itemList();
1331 SnapManager &m = _desktop->namedview->snap_manager;
1332 m.setup(_desktop);
1333 m.setRotationCenterSource(items);
1335 if (state & GDK_CONTROL_MASK) { // with Ctrl, constrain to axes
1336 std::vector<Inkscape::Snapper::SnapConstraint> constraints;
1337 constraints.push_back(Inkscape::Snapper::SnapConstraint(_point, Geom::Point(1, 0)));
1338 constraints.push_back(Inkscape::Snapper::SnapConstraint(_point, Geom::Point(0, 1)));
1339 Inkscape::SnappedPoint sp = m.multipleConstrainedSnaps(Inkscape::SnapCandidatePoint(pt, Inkscape::SNAPSOURCE_ROTATION_CENTER), constraints, state & GDK_SHIFT_MASK);
1340 pt = sp.getPoint();
1341 }
1342 else {
1343 if (!(state & GDK_SHIFT_MASK)) { // Shift disables snapping
1344 m.freeSnapReturnByRef(pt, Inkscape::SNAPSOURCE_ROTATION_CENTER);
1345 }
1346 }
1348 m.unSetup();
1350 // status text
1351 GString *xs = SP_PX_TO_METRIC_STRING(pt[Geom::X], _desktop->namedview->getDefaultMetric());
1352 GString *ys = SP_PX_TO_METRIC_STRING(pt[Geom::Y], _desktop->namedview->getDefaultMetric());
1353 _message_context.setF(Inkscape::NORMAL_MESSAGE, _("Move <b>center</b> to %s, %s"), xs->str, ys->str);
1354 g_string_free(xs, FALSE);
1355 g_string_free(ys, FALSE);
1357 return TRUE;
1358 }
1360 /*
1361 * handlers for handle movement
1362 *
1363 */
1365 void sp_sel_trans_stretch(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1366 {
1367 seltrans->stretch(handle, pt, state);
1368 }
1370 void sp_sel_trans_scale(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint state)
1371 {
1372 seltrans->scale(pt, state);
1373 }
1375 void sp_sel_trans_skew(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1376 {
1377 seltrans->skew(handle, pt, state);
1378 }
1380 void sp_sel_trans_rotate(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint state)
1381 {
1382 seltrans->rotate(pt, state);
1383 }
1385 void Inkscape::SelTrans::stretch(SPSelTransHandle const &/*handle*/, Geom::Point &/*pt*/, guint /*state*/)
1386 {
1387 transform(_absolute_affine, Geom::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1388 }
1390 void Inkscape::SelTrans::scale(Geom::Point &/*pt*/, guint /*state*/)
1391 {
1392 transform(_absolute_affine, Geom::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1393 }
1395 void Inkscape::SelTrans::skew(SPSelTransHandle const &/*handle*/, Geom::Point &/*pt*/, guint /*state*/)
1396 {
1397 transform(_relative_affine, _origin);
1398 }
1400 void Inkscape::SelTrans::rotate(Geom::Point &/*pt*/, guint /*state*/)
1401 {
1402 transform(_relative_affine, _origin);
1403 }
1405 void sp_sel_trans_center(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint /*state*/)
1406 {
1407 seltrans->setCenter(pt);
1408 }
1411 void Inkscape::SelTrans::moveTo(Geom::Point const &xy, guint state)
1412 {
1413 SnapManager &m = _desktop->namedview->snap_manager;
1415 /* The amount that we've moved by during this drag */
1416 Geom::Point dxy = xy - _point;
1418 bool const alt = (state & GDK_MOD1_MASK);
1419 bool const control = (state & GDK_CONTROL_MASK);
1420 bool const shift = (state & GDK_SHIFT_MASK);
1422 if (alt) {
1424 // Alt pressed means: move only by integer multiples of the grid spacing
1426 if (control) { // ... if also constrained to the orthogonal axes
1427 if (fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y])) {
1428 dxy[Geom::Y] = 0;
1429 } else {
1430 dxy[Geom::X] = 0;
1431 }
1432 }
1433 m.setup(_desktop, true, _items_const);
1434 dxy = m.multipleOfGridPitch(dxy, _point);
1435 m.unSetup();
1436 } else if (shift) {
1437 if (control) { // shift & control: constrained movement without snapping
1438 if (fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y])) {
1439 dxy[Geom::Y] = 0;
1440 } else {
1441 dxy[Geom::X] = 0;
1442 }
1443 }
1444 } else { //!shift: with snapping
1446 /* We're snapping to things, possibly with a constraint to horizontal or
1447 ** vertical movement. Obtain a list of possible translations and then
1448 ** pick the smallest.
1449 */
1451 m.setup(_desktop, false, _items_const);
1453 /* This will be our list of possible translations */
1454 std::list<Inkscape::SnappedPoint> s;
1456 if (control) { // constrained movement with snapping
1458 /* Snap to things, and also constrain to horizontal or vertical movement */
1460 unsigned int dim = fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y]) ? Geom::X : Geom::Y;
1461 // When doing a constrained translation, all points will move in the same direction, i.e.
1462 // either horizontally or vertically. Therefore we only have to specify the direction of
1463 // the constraint-line once. The constraint lines are parallel, but might not be colinear.
1464 // Therefore we will have to set the point through which the constraint-line runs
1465 // individually for each point to be snapped; this will be handled however by _snapTransformed()
1466 s.push_back(m.constrainedSnapTranslate(_bbox_points_for_translating,
1467 _point,
1468 Inkscape::Snapper::SnapConstraint(component_vectors[dim]),
1469 dxy));
1471 s.push_back(m.constrainedSnapTranslate(_snap_points,
1472 _point,
1473 Inkscape::Snapper::SnapConstraint(component_vectors[dim]),
1474 dxy));
1475 } else { // !control
1477 // Let's leave this timer code here for a while. I'll probably need it in the near future (Diederik van Lierop)
1478 /* GTimeVal starttime;
1479 GTimeVal endtime;
1480 g_get_current_time(&starttime); */
1482 /* Snap to things with no constraint */
1483 s.push_back(m.freeSnapTranslate(_bbox_points_for_translating, _point, dxy));
1484 s.push_back(m.freeSnapTranslate(_snap_points, _point, dxy));
1486 /*g_get_current_time(&endtime);
1487 double elapsed = ((((double)endtime.tv_sec - starttime.tv_sec) * G_USEC_PER_SEC + (endtime.tv_usec - starttime.tv_usec))) / 1000.0;
1488 std::cout << "Time spent snapping: " << elapsed << std::endl; */
1489 }
1490 m.unSetup();
1492 /* Pick one */
1493 Inkscape::SnappedPoint best_snapped_point;
1494 for (std::list<Inkscape::SnappedPoint>::const_iterator i = s.begin(); i != s.end(); i++) {
1495 if (i->getSnapped()) {
1496 if (best_snapped_point.isOtherSnapBetter(*i, true)) {
1497 best_snapped_point = *i;
1498 dxy = i->getTransformation();
1499 }
1500 }
1501 }
1503 if (best_snapped_point.getSnapped()) {
1504 _desktop->snapindicator->set_new_snaptarget(best_snapped_point);
1505 } else {
1506 // We didn't snap, so remove any previous snap indicator
1507 _desktop->snapindicator->remove_snaptarget();
1508 if (control) {
1509 // If we didn't snap, then we should still constrain horizontally or vertically
1510 // (When we did snap, then this constraint has already been enforced by
1511 // calling constrainedSnapTranslate() above)
1512 if (fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y])) {
1513 dxy[Geom::Y] = 0;
1514 } else {
1515 dxy[Geom::X] = 0;
1516 }
1517 }
1518 }
1519 }
1521 Geom::Matrix const move((Geom::Translate(dxy)));
1522 Geom::Point const norm(0, 0);
1523 transform(move, norm);
1525 // status text
1526 GString *xs = SP_PX_TO_METRIC_STRING(dxy[Geom::X], _desktop->namedview->getDefaultMetric());
1527 GString *ys = SP_PX_TO_METRIC_STRING(dxy[Geom::Y], _desktop->namedview->getDefaultMetric());
1528 _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);
1529 g_string_free(xs, TRUE);
1530 g_string_free(ys, TRUE);
1531 }
1533 // Given a location of a handle at the visual bounding box, find the corresponding location at the
1534 // geometrical bounding box
1535 Geom::Point Inkscape::SelTrans::_getGeomHandlePos(Geom::Point const &visual_handle_pos)
1536 {
1537 if ( _snap_bbox_type == SPItem::GEOMETRIC_BBOX) {
1538 // When the selector tool is using geometric bboxes, then the handle is already
1539 // located at one of the geometric bbox corners
1540 return visual_handle_pos;
1541 }
1543 if (!_geometric_bbox) {
1544 //_getGeomHandlePos() can only be used after _geometric_bbox has been defined!
1545 return visual_handle_pos;
1546 }
1548 // Using the Geom::Rect constructor below ensures that "min() < max()", which is important
1549 // because this will also hold for _bbox, and which is required for get_scale_transform_with_stroke()
1550 Geom::Rect new_bbox = Geom::Rect(_origin_for_bboxpoints, visual_handle_pos); // new visual bounding box
1551 // Please note that the new_bbox might in fact be just a single line, for example when stretching (in
1552 // which case the handle and origin will be aligned vertically or horizontally)
1553 Geom::Point normalized_handle_pos = (visual_handle_pos - new_bbox.min()) * Geom::Scale(new_bbox.dimensions()).inverse();
1555 // Calculate the absolute affine while taking into account the scaling of the stroke width
1556 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1557 bool transform_stroke = prefs->getBool("/options/transform/stroke", true);
1558 Geom::Matrix abs_affine = get_scale_transform_with_stroke (*_bbox, _strokewidth, transform_stroke,
1559 new_bbox.min()[Geom::X], new_bbox.min()[Geom::Y], new_bbox.max()[Geom::X], new_bbox.max()[Geom::Y]);
1561 // Calculate the scaled geometrical bbox
1562 Geom::Rect new_geom_bbox = Geom::Rect(_geometric_bbox->min() * abs_affine, _geometric_bbox->max() * abs_affine);
1563 // Find the location of the handle on this new geometrical bbox
1564 return normalized_handle_pos * Geom::Scale(new_geom_bbox.dimensions()) + new_geom_bbox.min(); //new position of the geometric handle
1565 }
1567 Geom::Scale Inkscape::calcScaleFactors(Geom::Point const &initial_point, Geom::Point const &new_point, Geom::Point const &origin, bool const skew)
1568 {
1569 // Work out the new scale factors for the bbox
1571 Geom::Point const initial_delta = initial_point - origin;
1572 Geom::Point const new_delta = new_point - origin;
1573 Geom::Point const offset = new_point - initial_point;
1574 Geom::Scale scale(1, 1);
1576 for ( unsigned int i = 0 ; i < 2 ; i++ ) {
1577 if ( fabs(initial_delta[i]) > 1e-6 ) {
1578 if (skew) {
1579 scale[i] = offset[1-i] / initial_delta[i];
1580 } else {
1581 scale[i] = new_delta[i] / initial_delta[i];
1582 }
1583 }
1584 }
1586 return scale;
1587 }
1589 // Only for scaling/stretching
1590 Geom::Point Inkscape::SelTrans::_calcAbsAffineDefault(Geom::Scale const default_scale)
1591 {
1592 Geom::Matrix abs_affine = Geom::Translate(-_origin) * Geom::Matrix(default_scale) * Geom::Translate(_origin);
1593 Geom::Point new_bbox_min = _approximate_bbox->min() * abs_affine;
1594 Geom::Point new_bbox_max = _approximate_bbox->max() * abs_affine;
1596 bool transform_stroke = false;
1597 gdouble strokewidth = 0;
1599 if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
1600 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1601 transform_stroke = prefs->getBool("/options/transform/stroke", true);
1602 strokewidth = _strokewidth;
1603 }
1605 _absolute_affine = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
1606 new_bbox_min[Geom::X], new_bbox_min[Geom::Y], new_bbox_max[Geom::X], new_bbox_max[Geom::Y]);
1608 // return the new handle position
1609 return ( _point - _origin ) * default_scale + _origin;
1610 }
1612 // Only for scaling/stretching
1613 Geom::Point Inkscape::SelTrans::_calcAbsAffineGeom(Geom::Scale const geom_scale)
1614 {
1615 _relative_affine = Geom::Matrix(geom_scale);
1616 _absolute_affine = Geom::Translate(-_origin_for_specpoints) * _relative_affine * Geom::Translate(_origin_for_specpoints);
1618 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1619 bool const transform_stroke = prefs->getBool("/options/transform/stroke", true);
1620 if (_geometric_bbox) {
1621 Geom::Rect visual_bbox = get_visual_bbox(_geometric_bbox, _absolute_affine, _strokewidth, transform_stroke);
1622 // return the new handle position
1623 return visual_bbox.min() + visual_bbox.dimensions() * Geom::Scale(_handle_x, _handle_y);
1624 }
1626 // Fall back scenario, in case we don't have a geometric bounding box at hand;
1627 // (Due to some bugs related to bounding boxes having at least one zero dimension; For more details
1628 // see https://bugs.launchpad.net/inkscape/+bug/318726)
1629 g_warning("No geometric bounding box has been calculated; this is a bug that needs fixing!");
1630 return _calcAbsAffineDefault(geom_scale); // this is bogus, but we must return _something_
1631 }
1633 void Inkscape::SelTrans::_keepClosestPointOnly(std::vector<Inkscape::SnapCandidatePoint> &points, const Geom::Point &reference)
1634 {
1635 if (points.size() < 2) return;
1637 Inkscape::SnapCandidatePoint closest_point = Inkscape::SnapCandidatePoint(Geom::Point(NR_HUGE, NR_HUGE), SNAPSOURCE_UNDEFINED, SNAPTARGET_UNDEFINED);
1638 Geom::Coord closest_dist = NR_HUGE;
1640 for(std::vector<Inkscape::SnapCandidatePoint>::const_iterator i = points.begin(); i != points.end(); i++) {
1641 Geom::Coord dist = Geom::L2((*i).getPoint() - reference);
1642 if (i == points.begin() || dist < closest_dist) {
1643 closest_point = *i;
1644 closest_dist = dist;
1645 }
1646 }
1648 closest_point.setSourceNum(-1);
1649 points.clear();
1650 points.push_back(closest_point);
1651 }
1653 /*
1654 Local Variables:
1655 mode:c++
1656 c-file-style:"stroustrup"
1657 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1658 indent-tabs-mode:nil
1659 fill-column:99
1660 End:
1661 */
1662 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :