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 (m.snapprefs.getSnapEnabledGlobally()) {
363 if (_bbox_points.size() == 1) {
364 _desktop->snapindicator->set_new_snapsource(_bbox_points.at(0));
365 } else if (_snap_points.size() == 1){
366 _desktop->snapindicator->set_new_snapsource(_snap_points.at(0));
367 }
368 }
369 }
371 sp_canvas_set_snap_delay_active(_desktop->canvas, true);
373 // The lines below are useful for debugging any snapping issues, as they'll spit out all points that are considered for snapping
375 /*std::cout << "Number of snap points: " << _snap_points.size() << std::endl;
376 for (std::vector<Geom::Point>::const_iterator i = _snap_points.begin(); i != _snap_points.end(); i++)
377 {
378 std::cout << " " << *i << std::endl;
379 }
381 std::cout << "Number of bbox points: " << _bbox_points.size() << std::endl;
382 for (std::vector<Geom::Point>::const_iterator i = _bbox_points.begin(); i != _bbox_points.end(); i++)
383 {
384 std::cout << " " << *i << std::endl;
385 }*/
387 if ((x != -1) && (y != -1)) {
388 sp_canvas_item_show(_norm);
389 sp_canvas_item_show(_grip);
390 }
392 if (_show == SHOW_OUTLINE) {
393 for (int i = 0; i < 4; i++)
394 sp_canvas_item_show(_l[i]);
395 }
397 _updateHandles();
398 g_return_if_fail(_stamp_cache == NULL);
399 }
401 void Inkscape::SelTrans::transform(Geom::Matrix const &rel_affine, Geom::Point const &norm)
402 {
403 g_return_if_fail(_grabbed);
404 g_return_if_fail(!_empty);
406 Geom::Matrix const affine( Geom::Translate(-norm) * rel_affine * Geom::Translate(norm) );
408 if (_show == SHOW_CONTENT) {
409 // update the content
410 for (unsigned i = 0; i < _items.size(); i++) {
411 SPItem &item = *_items[i];
412 Geom::Matrix const &prev_transform = _items_affines[i];
413 sp_item_set_i2d_affine(&item, prev_transform * affine);
414 }
415 } else {
416 if (_bbox) {
417 Geom::Point p[4];
418 /* update the outline */
419 for (unsigned i = 0 ; i < 4 ; i++) {
420 p[i] = _bbox->corner(i) * affine;
421 }
422 for (unsigned i = 0 ; i < 4 ; i++) {
423 sp_ctrlline_set_coords(SP_CTRLLINE(_l[i]), p[i], p[(i+1)%4]);
424 }
425 }
426 }
428 _current_relative_affine = affine;
429 _changed = true;
430 _updateHandles();
431 }
433 void Inkscape::SelTrans::ungrab()
434 {
435 g_return_if_fail(_grabbed);
436 _grabbed = false;
437 _show_handles = true;
439 sp_canvas_set_snap_delay_active(_desktop->canvas, false);
441 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
442 _updateVolatileState();
444 for (unsigned i = 0; i < _items.size(); i++) {
445 sp_object_unref(SP_OBJECT(_items[i]), NULL);
446 }
448 sp_canvas_item_hide(_norm);
449 sp_canvas_item_hide(_grip);
451 if (_show == SHOW_OUTLINE) {
452 for (int i = 0; i < 4; i++)
453 sp_canvas_item_hide(_l[i]);
454 }
456 if (_stamp_cache) {
457 g_slist_free(_stamp_cache);
458 _stamp_cache = NULL;
459 }
461 _message_context.clear();
463 if (!_empty && _changed) {
464 sp_selection_apply_affine(selection, _current_relative_affine, (_show == SHOW_OUTLINE)? true : false);
465 if (_center) {
466 *_center *= _current_relative_affine;
467 _center_is_set = true;
468 }
470 // If dragging showed content live, sp_selection_apply_affine cannot change the centers
471 // appropriately - it does not know the original positions of the centers (all objects already have
472 // the new bboxes). So we need to reset the centers from our saved array.
473 if (_show != SHOW_OUTLINE && !_current_relative_affine.isTranslation()) {
474 for (unsigned i = 0; i < _items_centers.size(); i++) {
475 SPItem *currentItem = _items[i];
476 if (currentItem->isCenterSet()) { // only if it's already set
477 currentItem->setCenter (_items_centers[i] * _current_relative_affine);
478 SP_OBJECT(currentItem)->updateRepr();
479 }
480 }
481 }
483 _items.clear();
484 _items_const.clear();
485 _items_affines.clear();
486 _items_centers.clear();
488 if (_current_relative_affine.isTranslation()) {
489 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
490 _("Move"));
491 } else if (_current_relative_affine.isScale()) {
492 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
493 _("Scale"));
494 } else if (_current_relative_affine.isRotation()) {
495 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
496 _("Rotate"));
497 } else {
498 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
499 _("Skew"));
500 }
502 } else {
504 if (_center_is_set) {
505 // we were dragging center; update reprs and commit undoable action
506 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
507 SPItem *it = (SPItem*)SP_OBJECT(l->data);
508 SP_OBJECT(it)->updateRepr();
509 }
510 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
511 _("Set center"));
512 }
514 _items.clear();
515 _items_const.clear();
516 _items_affines.clear();
517 _items_centers.clear();
518 _updateHandles();
519 }
520 }
522 /* fixme: This is really bad, as we compare positions for each stamp (Lauris) */
523 /* fixme: IMHO the best way to keep sort cache would be to implement timestamping at last */
525 void Inkscape::SelTrans::stamp()
526 {
527 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
529 bool fixup = !_grabbed;
530 if ( fixup && _stamp_cache ) {
531 // TODO - give a proper fix. Simple temproary work-around for the grab() issue
532 g_slist_free(_stamp_cache);
533 _stamp_cache = NULL;
534 }
536 /* stamping mode */
537 if (!_empty) {
538 GSList *l;
539 if (_stamp_cache) {
540 l = _stamp_cache;
541 } else {
542 /* Build cache */
543 l = g_slist_copy((GSList *) selection->itemList());
544 l = g_slist_sort(l, (GCompareFunc) sp_object_compare_position);
545 _stamp_cache = l;
546 }
548 while (l) {
549 SPItem *original_item = SP_ITEM(l->data);
550 Inkscape::XML::Node *original_repr = SP_OBJECT_REPR(original_item);
552 // remember the position of the item
553 gint pos = original_repr->position();
554 // remember parent
555 Inkscape::XML::Node *parent = sp_repr_parent(original_repr);
557 Inkscape::XML::Node *copy_repr = original_repr->duplicate(parent->document());
559 // add the new repr to the parent
560 parent->appendChild(copy_repr);
561 // move to the saved position
562 copy_repr->setPosition(pos > 0 ? pos : 0);
564 SPItem *copy_item = (SPItem *) sp_desktop_document(_desktop)->getObjectByRepr(copy_repr);
566 Geom::Matrix const *new_affine;
567 if (_show == SHOW_OUTLINE) {
568 Geom::Matrix const i2d(sp_item_i2d_affine(original_item));
569 Geom::Matrix const i2dnew( i2d * _current_relative_affine );
570 sp_item_set_i2d_affine(copy_item, i2dnew);
571 new_affine = ©_item->transform;
572 } else {
573 new_affine = &original_item->transform;
574 }
576 sp_item_write_transform(copy_item, copy_repr, *new_affine);
578 if ( copy_item->isCenterSet() && _center ) {
579 copy_item->setCenter(*_center * _current_relative_affine);
580 }
582 Inkscape::GC::release(copy_repr);
583 l = l->next;
584 }
585 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
586 _("Stamp"));
587 }
589 if ( fixup && _stamp_cache ) {
590 // TODO - give a proper fix. Simple temproary work-around for the grab() issue
591 g_slist_free(_stamp_cache);
592 _stamp_cache = NULL;
593 }
594 }
596 void Inkscape::SelTrans::_updateHandles()
597 {
598 if ( !_show_handles || _empty )
599 {
600 sp_remove_handles(_shandle, 8);
601 sp_remove_handles(_rhandle, 8);
602 sp_remove_handles(&_chandle, 1);
603 return;
604 }
606 // center handle
607 if ( _chandle == NULL ) {
608 _chandle = sp_knot_new(_desktop, _("<b>Center</b> of rotation and skewing: drag to reposition; scaling with Shift also uses this center"));
610 _chandle->setShape (SP_CTRL_SHAPE_BITMAP);
611 _chandle->setSize (13);
612 _chandle->setAnchor (handle_center.anchor);
613 _chandle->setMode (SP_CTRL_MODE_XOR);
614 _chandle->setFill(0x00000000, 0x00000000, 0x00000000);
615 _chandle->setStroke(0x000000ff, 0xff0000b0, 0xff0000b0);
616 _chandle->setPixbuf(handles[handle_center.control]);
617 sp_knot_update_ctrl(_chandle);
619 g_signal_connect(G_OBJECT(_chandle), "request",
620 G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle_center);
621 g_signal_connect(G_OBJECT(_chandle), "moved",
622 G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle_center);
623 g_signal_connect(G_OBJECT(_chandle), "grabbed",
624 G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle_center);
625 g_signal_connect(G_OBJECT(_chandle), "ungrabbed",
626 G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle_center);
627 g_signal_connect(G_OBJECT(_chandle), "clicked",
628 G_CALLBACK(sp_sel_trans_handle_click), (gpointer) &handle_center);
629 }
631 sp_remove_handles(&_chandle, 1);
632 if ( _state == STATE_SCALE ) {
633 sp_remove_handles(_rhandle, 8);
634 _showHandles(_shandle, handles_scale, 8,
635 _("<b>Squeeze or stretch</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"),
636 _("<b>Scale</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"));
637 } else {
638 sp_remove_handles(_shandle, 8);
639 _showHandles(_rhandle, handles_rotate, 8,
640 _("<b>Skew</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to skew around the opposite side"),
641 _("<b>Rotate</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to rotate around the opposite corner"));
642 }
644 if (!_center_is_set) {
645 _center = _desktop->selection->center();
646 _center_is_set = true;
647 }
649 if ( _state == STATE_SCALE || !_center ) {
650 sp_knot_hide(_chandle);
651 } else {
652 sp_knot_show(_chandle);
653 sp_knot_moveto(_chandle, *_center);
654 }
655 }
657 void Inkscape::SelTrans::_updateVolatileState()
658 {
659 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
660 _empty = selection->isEmpty();
662 if (_empty) {
663 return;
664 }
666 //Update the bboxes
667 _bbox = selection->bounds(_snap_bbox_type);
668 _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX);
670 if (!_bbox) {
671 _empty = true;
672 return;
673 }
675 _strokewidth = stroke_average_width (selection->itemList());
676 }
678 static void sp_remove_handles(SPKnot *knot[], gint num)
679 {
680 for (int i = 0; i < num; i++) {
681 if (knot[i] != NULL) {
682 sp_knot_hide(knot[i]);
683 }
684 }
685 }
687 void Inkscape::SelTrans::_showHandles(SPKnot *knot[], SPSelTransHandle const handle[], gint num,
688 gchar const *even_tip, gchar const *odd_tip)
689 {
690 g_return_if_fail( !_empty );
692 for (int i = 0; i < num; i++) {
693 if (knot[i] == NULL) {
694 knot[i] = sp_knot_new(_desktop, i % 2 ? even_tip : odd_tip);
696 knot[i]->setShape (SP_CTRL_SHAPE_BITMAP);
697 knot[i]->setSize (13);
698 knot[i]->setAnchor (handle[i].anchor);
699 knot[i]->setMode (SP_CTRL_MODE_XOR);
700 knot[i]->setFill(0x000000ff, 0x00ff6600, 0x00ff6600); // inversion, green, green
701 knot[i]->setStroke(0x000000ff, 0x000000ff, 0x000000ff); // inversion
702 knot[i]->setPixbuf(handles[handle[i].control]);
703 sp_knot_update_ctrl(knot[i]);
705 g_signal_connect(G_OBJECT(knot[i]), "request",
706 G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle[i]);
707 g_signal_connect(G_OBJECT(knot[i]), "moved",
708 G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle[i]);
709 g_signal_connect(G_OBJECT(knot[i]), "grabbed",
710 G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle[i]);
711 g_signal_connect(G_OBJECT(knot[i]), "ungrabbed",
712 G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle[i]);
713 g_signal_connect(G_OBJECT(knot[i]), "event", G_CALLBACK(sp_seltrans_handle_event), (gpointer) &handle[i]);
714 }
715 sp_knot_show(knot[i]);
717 Geom::Point const handle_pt(handle[i].x, handle[i].y);
718 // shouldn't have nullary bbox, but knots
719 g_assert(_bbox);
720 Geom::Point p( _bbox->min()
721 + ( _bbox->dimensions()
722 * Geom::Scale(handle_pt) ) );
724 sp_knot_moveto(knot[i], p);
725 }
726 }
728 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data)
729 {
730 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleGrab(
731 knot, state, *(SPSelTransHandle const *) data
732 );
733 }
735 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint /*state*/, gpointer /*data*/)
736 {
737 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->ungrab();
738 }
740 static void sp_sel_trans_handle_new_event(SPKnot *knot, Geom::Point *position, guint state, gpointer data)
741 {
742 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleNewEvent(
743 knot, position, state, *(SPSelTransHandle const *) data
744 );
745 }
747 static gboolean sp_sel_trans_handle_request(SPKnot *knot, Geom::Point *position, guint state, gboolean *data)
748 {
749 return SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleRequest(
750 knot, position, state, *(SPSelTransHandle const *) data
751 );
752 }
754 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data)
755 {
756 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleClick(
757 knot, state, *(SPSelTransHandle const *) data
758 );
759 }
761 void Inkscape::SelTrans::handleClick(SPKnot */*knot*/, guint state, SPSelTransHandle const &handle)
762 {
763 switch (handle.anchor) {
764 case GTK_ANCHOR_CENTER:
765 if (state & GDK_SHIFT_MASK) {
766 // Unset the center position for all selected items
767 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
768 SPItem *it = (SPItem*)(SP_OBJECT(l->data));
769 it->unsetCenter();
770 SP_OBJECT(it)->updateRepr();
771 _center_is_set = false; // center has changed
772 _updateHandles();
773 }
774 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
775 _("Reset center"));
776 }
777 break;
778 default:
779 break;
780 }
781 }
783 void Inkscape::SelTrans::handleGrab(SPKnot *knot, guint /*state*/, SPSelTransHandle const &handle)
784 {
785 switch (handle.anchor) {
786 case GTK_ANCHOR_CENTER:
787 g_object_set(G_OBJECT(_grip),
788 "shape", SP_CTRL_SHAPE_BITMAP,
789 "size", 13.0,
790 NULL);
791 sp_canvas_item_show(_grip);
792 break;
793 default:
794 g_object_set(G_OBJECT(_grip),
795 "shape", SP_CTRL_SHAPE_CROSS,
796 "size", 7.0,
797 NULL);
798 sp_canvas_item_show(_norm);
799 sp_canvas_item_show(_grip);
801 break;
802 }
804 grab(sp_knot_position(knot), handle.x, handle.y, FALSE);
805 }
808 void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const &handle)
809 {
810 if (!SP_KNOT_IS_GRABBED(knot)) {
811 return;
812 }
814 // in case items have been unhooked from the document, don't
815 // try to continue processing events for them.
816 for (unsigned int i = 0; i < _items.size(); i++) {
817 if (!SP_OBJECT_DOCUMENT(SP_OBJECT(_items[i])) ) {
818 return;
819 }
820 }
822 handle.action(this, handle, *position, state);
823 }
826 gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const &handle)
827 {
828 if (!SP_KNOT_IS_GRABBED(knot)) {
829 return TRUE;
830 }
832 knot->desktop->setPosition(*position);
834 // When holding shift while rotating or skewing, the transformation will be
835 // relative to the point opposite of the handle; otherwise it will be relative
836 // to the center as set for the selection
837 if ((!(state & GDK_SHIFT_MASK) == !(_state == STATE_ROTATE)) && (&handle != &handle_center)) {
838 _origin = _opposite;
839 _origin_for_bboxpoints = _opposite_for_bboxpoints;
840 _origin_for_specpoints = _opposite_for_specpoints;
841 } else if (_center) {
842 _origin = *_center;
843 _origin_for_bboxpoints = *_center;
844 _origin_for_specpoints = *_center;
845 } else {
846 // FIXME
847 return TRUE;
848 }
849 if (handle.request(this, handle, *position, state)) {
850 sp_knot_set_position(knot, *position, state);
851 SP_CTRL(_grip)->moveto(*position);
852 SP_CTRL(_norm)->moveto(_origin);
853 }
855 return TRUE;
856 }
859 void Inkscape::SelTrans::_selChanged(Inkscape::Selection */*selection*/)
860 {
861 if (!_grabbed) {
862 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
863 // reread in case it changed on the fly:
864 int prefs_bbox = prefs->getBool("/tools/bounding_box");
865 _snap_bbox_type = !prefs_bbox ?
866 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
867 //SPItem::APPROXIMATE_BBOX will be replaced by SPItem::VISUAL_BBOX, as soon as the latter is implemented properly
869 _updateVolatileState();
870 _current_relative_affine.setIdentity();
871 _center_is_set = false; // center(s) may have changed
872 _updateHandles();
873 }
874 }
876 void Inkscape::SelTrans::_selModified(Inkscape::Selection */*selection*/, guint /*flags*/)
877 {
878 if (!_grabbed) {
879 _updateVolatileState();
880 _current_relative_affine.setIdentity();
882 // reset internal flag
883 _changed = false;
885 _center_is_set = false; // center(s) may have changed
887 _updateHandles();
888 }
889 }
891 /*
892 * handlers for handle move-request
893 */
895 /** Returns -1 or 1 according to the sign of x. Returns 1 for 0 and NaN. */
896 static double sign(double const x)
897 {
898 return ( x < 0
899 ? -1
900 : 1 );
901 }
903 gboolean sp_sel_trans_scale_request(Inkscape::SelTrans *seltrans,
904 SPSelTransHandle const &, Geom::Point &pt, guint state)
905 {
906 return seltrans->scaleRequest(pt, state);
907 }
909 gboolean sp_sel_trans_stretch_request(Inkscape::SelTrans *seltrans,
910 SPSelTransHandle const &handle, Geom::Point &pt, guint state)
911 {
912 return seltrans->stretchRequest(handle, pt, state);
913 }
915 gboolean sp_sel_trans_skew_request(Inkscape::SelTrans *seltrans,
916 SPSelTransHandle const &handle, Geom::Point &pt, guint state)
917 {
918 return seltrans->skewRequest(handle, pt, state);
919 }
921 gboolean sp_sel_trans_rotate_request(Inkscape::SelTrans *seltrans,
922 SPSelTransHandle const &, Geom::Point &pt, guint state)
923 {
924 return seltrans->rotateRequest(pt, state);
925 }
927 gboolean sp_sel_trans_center_request(Inkscape::SelTrans *seltrans,
928 SPSelTransHandle const &, Geom::Point &pt, guint state)
929 {
930 return seltrans->centerRequest(pt, state);
931 }
933 gboolean Inkscape::SelTrans::scaleRequest(Geom::Point &pt, guint state)
934 {
936 // Calculate the scale factors, which can be either visual or geometric
937 // depending on which type of bbox is currently being used (see preferences -> selector tool)
938 Geom::Scale default_scale = calcScaleFactors(_point, pt, _origin);
940 // Find the scale factors for the geometric bbox
941 Geom::Point pt_geom = _getGeomHandlePos(pt);
942 Geom::Scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
944 _absolute_affine = Geom::identity(); //Initialize the scaler
946 if (state & GDK_MOD1_MASK) { // scale by an integer multiplier/divider
947 // We're scaling either the visual or the geometric bbox here (see the comment above)
948 for ( unsigned int i = 0 ; i < 2 ; i++ ) {
949 if (fabs(default_scale[i]) > 1) {
950 default_scale[i] = round(default_scale[i]);
951 } else if (default_scale[i] != 0) {
952 default_scale[i] = 1/round(1/(MIN(default_scale[i], 10)));
953 }
954 }
955 // Update the knot position
956 pt = _calcAbsAffineDefault(default_scale);
957 // When scaling by an integer, snapping is not needed
958 } else {
959 // In all other cases we should try to snap now
960 SnapManager &m = _desktop->namedview->snap_manager;
961 m.setup(_desktop, false, _items_const);
963 Inkscape::SnappedPoint bb, sn;
964 Geom::Coord bd(NR_HUGE);
965 Geom::Coord sd(NR_HUGE);
967 if ((state & GDK_CONTROL_MASK) || _desktop->isToolboxButtonActive ("lock")) {
968 // Scale is locked to a 1:1 aspect ratio, so that s[X] must be made to equal s[Y].
969 //
970 // The aspect-ratio must be locked before snapping
971 if (fabs(default_scale[Geom::X]) > fabs(default_scale[Geom::Y])) {
972 default_scale[Geom::X] = fabs(default_scale[Geom::Y]) * sign(default_scale[Geom::X]);
973 geom_scale[Geom::X] = fabs(geom_scale[Geom::Y]) * sign(geom_scale[Geom::X]);
974 } else {
975 default_scale[Geom::Y] = fabs(default_scale[Geom::X]) * sign(default_scale[Geom::Y]);
976 geom_scale[Geom::Y] = fabs(geom_scale[Geom::X]) * sign(geom_scale[Geom::Y]);
977 }
979 // Snap along a suitable constraint vector from the origin.
980 bb = m.constrainedSnapScale(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, default_scale, _origin_for_bboxpoints);
981 sn = m.constrainedSnapScale(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, geom_scale, _origin_for_specpoints);
983 /* Choose the smaller difference in scale. Since s[X] == s[Y] we can
984 ** just compare difference in s[X].
985 */
986 bd = bb.getSnapped() ? fabs(bb.getTransformation()[Geom::X] - default_scale[Geom::X]) : NR_HUGE;
987 sd = sn.getSnapped() ? fabs(sn.getTransformation()[Geom::X] - geom_scale[Geom::X]) : NR_HUGE;
988 } else {
989 /* Scale aspect ratio is unlocked */
990 bb = m.freeSnapScale(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, default_scale, _origin_for_bboxpoints);
991 sn = m.freeSnapScale(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, geom_scale, _origin_for_specpoints);
993 /* Pick the snap that puts us closest to the original scale */
994 bd = bb.getSnapped() ? fabs(Geom::L2(bb.getTransformation()) - Geom::L2(Geom::Point(default_scale[Geom::X], default_scale[Geom::Y]))) : NR_HUGE;
995 sd = sn.getSnapped() ? fabs(Geom::L2(sn.getTransformation()) - Geom::L2(Geom::Point(geom_scale[Geom::X], geom_scale[Geom::Y]))) : NR_HUGE;
996 }
998 if (!(bb.getSnapped() || sn.getSnapped())) {
999 // We didn't snap at all! Don't update the handle position, just calculate the new transformation
1000 _calcAbsAffineDefault(default_scale);
1001 _desktop->snapindicator->remove_snaptarget();
1002 } else if (bd < sd) {
1003 // We snapped the bbox (which is either visual or geometric)
1004 _desktop->snapindicator->set_new_snaptarget(bb);
1005 default_scale = Geom::Scale(bb.getTransformation());
1006 // Calculate the new transformation and update the handle position
1007 pt = _calcAbsAffineDefault(default_scale);
1008 } else {
1009 _desktop->snapindicator->set_new_snaptarget(sn);
1010 // We snapped the special points (e.g. nodes), which are not at the visual bbox
1011 // The handle location however (pt) might however be at the visual bbox, so we
1012 // will have to calculate pt taking the stroke width into account
1013 geom_scale = Geom::Scale(sn.getTransformation());
1014 pt = _calcAbsAffineGeom(geom_scale);
1015 }
1016 }
1018 /* Status text */
1019 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1020 _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1021 100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1023 return TRUE;
1024 }
1026 gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1027 {
1028 Geom::Dim2 axis, perp;
1029 switch (handle.cursor) {
1030 case GDK_TOP_SIDE:
1031 case GDK_BOTTOM_SIDE:
1032 axis = Geom::Y;
1033 perp = Geom::X;
1034 break;
1035 case GDK_LEFT_SIDE:
1036 case GDK_RIGHT_SIDE:
1037 axis = Geom::X;
1038 perp = Geom::Y;
1039 break;
1040 default:
1041 g_assert_not_reached();
1042 return TRUE;
1043 };
1045 // Calculate the scale factors, which can be either visual or geometric
1046 // depending on which type of bbox is currently being used (see preferences -> selector tool)
1047 Geom::Scale default_scale = calcScaleFactors(_point, pt, _origin);
1048 default_scale[perp] = 1;
1050 // Find the scale factors for the geometric bbox
1051 Geom::Point pt_geom = _getGeomHandlePos(pt);
1052 Geom::Scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
1053 geom_scale[perp] = 1;
1055 _absolute_affine = Geom::identity(); //Initialize the scaler
1057 if (state & GDK_MOD1_MASK) { // stretch by an integer multiplier/divider
1058 if (fabs(default_scale[axis]) > 1) {
1059 default_scale[axis] = round(default_scale[axis]);
1060 } else if (default_scale[axis] != 0) {
1061 default_scale[axis] = 1/round(1/(MIN(default_scale[axis], 10)));
1062 }
1063 // Calculate the new transformation and update the handle position
1064 pt = _calcAbsAffineDefault(default_scale);
1065 // When stretching by an integer, snapping is not needed
1066 } else {
1067 // In all other cases we should try to snap now
1069 SnapManager &m = _desktop->namedview->snap_manager;
1070 m.setup(_desktop, false, _items_const);
1072 Inkscape::SnappedPoint bb, sn;
1073 g_assert(bb.getSnapped() == false); // Check initialization to catch any regression
1074 Geom::Coord bd(NR_HUGE);
1075 Geom::Coord sd(NR_HUGE);
1077 bool symmetrical = state & GDK_CONTROL_MASK;
1079 bb = m.constrainedSnapStretch(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, Geom::Coord(default_scale[axis]), _origin_for_bboxpoints, Geom::Dim2(axis), symmetrical);
1080 sn = m.constrainedSnapStretch(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, Geom::Coord(geom_scale[axis]), _origin_for_specpoints, Geom::Dim2(axis), symmetrical);
1082 if (bb.getSnapped()) {
1083 // We snapped the bbox (which is either visual or geometric)
1084 bd = fabs(bb.getTransformation()[axis] - default_scale[axis]);
1085 default_scale[axis] = bb.getTransformation()[axis];
1086 }
1088 if (sn.getSnapped()) {
1089 sd = fabs(sn.getTransformation()[axis] - geom_scale[axis]);
1090 geom_scale[axis] = sn.getTransformation()[axis];
1091 }
1093 if (symmetrical) {
1094 // on ctrl, apply symmetrical scaling instead of stretching
1095 // Preserve aspect ratio, but never flip in the dimension not being edited (by using fabs())
1096 default_scale[perp] = fabs(default_scale[axis]);
1097 geom_scale[perp] = fabs(geom_scale[axis]);
1098 }
1100 if (!(bb.getSnapped() || sn.getSnapped())) {
1101 // We didn't snap at all! Don't update the handle position, just calculate the new transformation
1102 _calcAbsAffineDefault(default_scale);
1103 _desktop->snapindicator->remove_snaptarget();
1104 } else if (bd < sd) {
1105 _desktop->snapindicator->set_new_snaptarget(bb);
1106 // Calculate the new transformation and update the handle position
1107 pt = _calcAbsAffineDefault(default_scale);
1108 } else {
1109 _desktop->snapindicator->set_new_snaptarget(sn);
1110 // We snapped the special points (e.g. nodes), which are not at the visual bbox
1111 // The handle location however (pt) might however be at the visual bbox, so we
1112 // will have to calculate pt taking the stroke width into account
1113 pt = _calcAbsAffineGeom(geom_scale);
1114 }
1115 }
1117 // status text
1118 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1119 _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1120 100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1122 return TRUE;
1123 }
1125 gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1126 {
1127 /* When skewing (or rotating):
1128 * 1) the stroke width will not change. This makes life much easier because we don't have to
1129 * account for that (like for scaling or stretching). As a consequence, all points will
1130 * have the same origin for the transformation and for the snapping.
1131 * 2) When holding shift, the transformation will be relative to the point opposite of
1132 * the handle; otherwise it will be relative to the center as set for the selection
1133 */
1135 Geom::Dim2 dim_a;
1136 Geom::Dim2 dim_b;
1138 switch (handle.cursor) {
1139 case GDK_SB_H_DOUBLE_ARROW:
1140 dim_a = Geom::Y;
1141 dim_b = Geom::X;
1142 break;
1143 case GDK_SB_V_DOUBLE_ARROW:
1144 dim_a = Geom::X;
1145 dim_b = Geom::Y;
1146 break;
1147 default:
1148 g_assert_not_reached();
1149 abort();
1150 break;
1151 }
1153 Geom::Point const initial_delta = _point - _origin;
1155 if (fabs(initial_delta[dim_a]) < 1e-15) {
1156 return false;
1157 }
1159 // Calculate the scale factors, which can be either visual or geometric
1160 // depending on which type of bbox is currently being used (see preferences -> selector tool)
1161 Geom::Scale scale = calcScaleFactors(_point, pt, _origin, false);
1162 Geom::Scale skew = calcScaleFactors(_point, pt, _origin, true);
1163 scale[dim_b] = 1;
1164 skew[dim_b] = 1;
1166 if (fabs(scale[dim_a]) < 1) {
1167 // Prevent shrinking of the selected object, while allowing mirroring
1168 scale[dim_a] = sign(scale[dim_a]);
1169 } else {
1170 // Allow expanding of the selected object by integer multiples
1171 scale[dim_a] = floor(scale[dim_a] + 0.5);
1172 }
1174 double radians = atan(skew[dim_a] / scale[dim_a]);
1176 if (state & GDK_CONTROL_MASK) {
1177 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1178 // Snap to defined angle increments
1179 int snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12);
1180 if (snaps) {
1181 double sections = floor(radians * snaps / M_PI + .5);
1182 if (fabs(sections) >= snaps / 2) {
1183 sections = sign(sections) * (snaps / 2 - 1);
1184 }
1185 radians = (M_PI / snaps) * sections;
1186 }
1187 skew[dim_a] = tan(radians) * scale[dim_a];
1188 } else {
1189 // Snap to objects, grids, guides
1191 SnapManager &m = _desktop->namedview->snap_manager;
1192 m.setup(_desktop, false, _items_const);
1194 Inkscape::Snapper::ConstraintLine const constraint(component_vectors[dim_b]);
1195 // When skewing, we cannot snap the corners of the bounding box, see the comment in "constrainedSnapSkew" for details
1196 Geom::Point const s(skew[dim_a], scale[dim_a]);
1197 Inkscape::SnappedPoint sn = m.constrainedSnapSkew(Inkscape::SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, constraint, s, _origin, Geom::Dim2(dim_b));
1199 if (sn.getSnapped()) {
1200 // We snapped something, so change the skew to reflect it
1201 Geom::Coord const sd = sn.getSnapped() ? sn.getTransformation()[0] : NR_HUGE;
1202 _desktop->snapindicator->set_new_snaptarget(sn);
1203 skew[dim_a] = sd;
1204 } else {
1205 _desktop->snapindicator->remove_snaptarget();
1206 }
1207 }
1209 // Update the handle position
1210 pt[dim_b] = initial_delta[dim_a] * skew[dim_a] + _point[dim_b];
1211 pt[dim_a] = initial_delta[dim_a] * scale[dim_a] + _origin[dim_a];
1213 // Calculate the relative affine
1214 _relative_affine = Geom::identity();
1215 _relative_affine[2*dim_a + dim_a] = (pt[dim_a] - _origin[dim_a]) / initial_delta[dim_a];
1216 _relative_affine[2*dim_a + (dim_b)] = (pt[dim_b] - _point[dim_b]) / initial_delta[dim_a];
1217 _relative_affine[2*(dim_b) + (dim_a)] = 0;
1218 _relative_affine[2*(dim_b) + (dim_b)] = 1;
1220 for (int i = 0; i < 2; i++) {
1221 if (fabs(_relative_affine[3*i]) < 1e-15) {
1222 _relative_affine[3*i] = 1e-15;
1223 }
1224 }
1226 // Update the status text
1227 double degrees = mod360symm(Geom::rad_to_deg(radians));
1228 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1229 // TRANSLATORS: don't modify the first ";"
1230 // (it will NOT be displayed as ";" - only the second one will be)
1231 _("<b>Skew</b>: %0.2f°; with <b>Ctrl</b> to snap angle"),
1232 degrees);
1234 return TRUE;
1235 }
1237 gboolean Inkscape::SelTrans::rotateRequest(Geom::Point &pt, guint state)
1238 {
1239 /* When rotating (or skewing):
1240 * 1) the stroke width will not change. This makes life much easier because we don't have to
1241 * account for that (like for scaling or stretching). As a consequence, all points will
1242 * have the same origin for the transformation and for the snapping.
1243 * 2) When holding shift, the transformation will be relative to the point opposite of
1244 * the handle; otherwise it will be relative to the center as set for the selection
1245 */
1247 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1248 int snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12);
1250 // rotate affine in rotate
1251 Geom::Point const d1 = _point - _origin;
1252 Geom::Point const d2 = pt - _origin;
1254 Geom::Coord const h1 = Geom::L2(d1); // initial radius
1255 if (h1 < 1e-15) return FALSE;
1256 Geom::Point q1 = d1 / h1; // normalized initial vector to handle
1257 Geom::Coord const h2 = Geom::L2(d2); // new radius
1258 if (fabs(h2) < 1e-15) return FALSE;
1259 Geom::Point q2 = d2 / h2; // normalized new vector to handle
1261 double radians;
1262 if (state & GDK_CONTROL_MASK) {
1263 // Snap to defined angle increments
1264 double cos_t = Geom::dot(q1, q2);
1265 double sin_t = Geom::dot(Geom::rot90(q1), q2);
1266 radians = atan2(sin_t, cos_t);
1267 if (snaps) {
1268 radians = ( M_PI / snaps ) * floor( radians * snaps / M_PI + .5 );
1269 }
1270 q1 = Geom::Point(1, 0);
1271 q2 = Geom::Point(cos(radians), sin(radians));
1272 } else {
1273 radians = atan2(Geom::dot(Geom::rot90(d1), d2),
1274 Geom::dot(d1, d2));
1275 }
1277 Geom::Rotate const r1(q1);
1278 Geom::Rotate const r2(q2);
1280 // Calculate the relative affine
1281 _relative_affine = r2 * r1.inverse();
1283 // Update the handle position
1284 pt = _point * Geom::Translate(-_origin) * _relative_affine * Geom::Translate(_origin);
1286 // Update the status text
1287 double degrees = mod360symm(Geom::rad_to_deg(radians));
1288 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1289 // TRANSLATORS: don't modify the first ";"
1290 // (it will NOT be displayed as ";" - only the second one will be)
1291 _("<b>Rotate</b>: %0.2f°; with <b>Ctrl</b> to snap angle"), degrees);
1293 return TRUE;
1294 }
1296 gboolean Inkscape::SelTrans::centerRequest(Geom::Point &pt, guint state)
1297 {
1298 SnapManager &m = _desktop->namedview->snap_manager;
1299 m.setup(_desktop);
1300 m.freeSnapReturnByRef(SnapPreferences::SNAPPOINT_NODE, pt);
1302 if (state & GDK_CONTROL_MASK) {
1303 if ( fabs(_point[Geom::X] - pt[Geom::X]) > fabs(_point[Geom::Y] - pt[Geom::Y]) ) {
1304 pt[Geom::Y] = _point[Geom::Y];
1305 } else {
1306 pt[Geom::X] = _point[Geom::X];
1307 }
1308 }
1310 if ( !(state & GDK_SHIFT_MASK) && _bbox ) {
1311 // screen pixels to snap center to bbox
1312 #define SNAP_DIST 5
1313 // FIXME: take from prefs
1314 double snap_dist = SNAP_DIST / _desktop->current_zoom();
1316 for (int i = 0; i < 2; i++) {
1317 if (fabs(pt[i] - _bbox->min()[i]) < snap_dist) {
1318 pt[i] = _bbox->min()[i];
1319 }
1320 if (fabs(pt[i] - _bbox->midpoint()[i]) < snap_dist) {
1321 pt[i] = _bbox->midpoint()[i];
1322 }
1323 if (fabs(pt[i] - _bbox->max()[i]) < snap_dist) {
1324 pt[i] = _bbox->max()[i];
1325 }
1326 }
1327 }
1329 // status text
1330 GString *xs = SP_PX_TO_METRIC_STRING(pt[Geom::X], _desktop->namedview->getDefaultMetric());
1331 GString *ys = SP_PX_TO_METRIC_STRING(pt[Geom::Y], _desktop->namedview->getDefaultMetric());
1332 _message_context.setF(Inkscape::NORMAL_MESSAGE, _("Move <b>center</b> to %s, %s"), xs->str, ys->str);
1333 g_string_free(xs, FALSE);
1334 g_string_free(ys, FALSE);
1336 return TRUE;
1337 }
1339 /*
1340 * handlers for handle movement
1341 *
1342 */
1344 void sp_sel_trans_stretch(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1345 {
1346 seltrans->stretch(handle, pt, state);
1347 }
1349 void sp_sel_trans_scale(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint state)
1350 {
1351 seltrans->scale(pt, state);
1352 }
1354 void sp_sel_trans_skew(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1355 {
1356 seltrans->skew(handle, pt, state);
1357 }
1359 void sp_sel_trans_rotate(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint state)
1360 {
1361 seltrans->rotate(pt, state);
1362 }
1364 void Inkscape::SelTrans::stretch(SPSelTransHandle const &/*handle*/, Geom::Point &/*pt*/, guint /*state*/)
1365 {
1366 transform(_absolute_affine, Geom::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1367 }
1369 void Inkscape::SelTrans::scale(Geom::Point &/*pt*/, guint /*state*/)
1370 {
1371 transform(_absolute_affine, Geom::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1372 }
1374 void Inkscape::SelTrans::skew(SPSelTransHandle const &/*handle*/, Geom::Point &/*pt*/, guint /*state*/)
1375 {
1376 transform(_relative_affine, _origin);
1377 }
1379 void Inkscape::SelTrans::rotate(Geom::Point &/*pt*/, guint /*state*/)
1380 {
1381 transform(_relative_affine, _origin);
1382 }
1384 void sp_sel_trans_center(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint /*state*/)
1385 {
1386 seltrans->setCenter(pt);
1387 }
1390 void Inkscape::SelTrans::moveTo(Geom::Point const &xy, guint state)
1391 {
1392 SnapManager &m = _desktop->namedview->snap_manager;
1393 m.setup(_desktop, true, _items_const);
1395 /* The amount that we've moved by during this drag */
1396 Geom::Point dxy = xy - _point;
1398 bool const alt = (state & GDK_MOD1_MASK);
1399 bool const control = (state & GDK_CONTROL_MASK);
1400 bool const shift = (state & GDK_SHIFT_MASK);
1402 if (alt) {
1404 /* Alt pressed means keep offset: snap the moved distance to the grid.
1405 ** FIXME: this will snap to more than just the grid, nowadays.
1406 */
1408 m.freeSnapReturnByRef(SnapPreferences::SNAPPOINT_NODE, dxy);
1410 } else if (!shift) {
1412 /* We're snapping to things, possibly with a constraint to horizontal or
1413 ** vertical movement. Obtain a list of possible translations and then
1414 ** pick the smallest.
1415 */
1417 /* This will be our list of possible translations */
1418 std::list<Inkscape::SnappedPoint> s;
1420 if (control) {
1422 /* Snap to things, and also constrain to horizontal or vertical movement */
1424 for (unsigned int dim = 0; dim < 2; dim++) {
1425 // When doing a constrained translation, all points will move in the same direction, i.e.
1426 // either horizontally or vertically. Therefore we only have to specify the direction of
1427 // the constraint-line once. The constraint lines are parallel, but might not be colinear.
1428 // Therefore we will have to set the point through which the constraint-line runs
1429 // individually for each point to be snapped; this will be handled however by _snapTransformed()
1430 s.push_back(m.constrainedSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_BBOX,
1431 _bbox_points,
1432 _point,
1433 Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1434 dxy));
1436 s.push_back(m.constrainedSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_NODE,
1437 _snap_points,
1438 _point,
1439 Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1440 dxy));
1441 }
1443 } else {
1445 // Let's leave this timer code here for a while. I'll probably need it in the near future (Diederik van Lierop)
1446 /* GTimeVal starttime;
1447 GTimeVal endtime;
1448 g_get_current_time(&starttime); */
1450 /* Snap to things with no constraint */
1451 s.push_back(m.freeSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, dxy));
1452 s.push_back(m.freeSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, dxy));
1454 /*g_get_current_time(&endtime);
1455 double elapsed = ((((double)endtime.tv_sec - starttime.tv_sec) * G_USEC_PER_SEC + (endtime.tv_usec - starttime.tv_usec))) / 1000.0;
1456 std::cout << "Time spent snapping: " << elapsed << std::endl; */
1457 }
1459 /* Pick one */
1460 Inkscape::SnappedPoint best_snapped_point;
1461 for (std::list<Inkscape::SnappedPoint>::const_iterator i = s.begin(); i != s.end(); i++) {
1462 if (i->getSnapped()) {
1463 if (best_snapped_point.isOtherSnapBetter(*i, true)) {
1464 best_snapped_point = *i;
1465 dxy = i->getTransformation();
1466 }
1467 }
1468 }
1469 if (best_snapped_point.getSnapped()) {
1470 _desktop->snapindicator->set_new_snaptarget(best_snapped_point);
1471 } else {
1472 // We didn't snap, so remove any previous snap indicator
1473 _desktop->snapindicator->remove_snaptarget();
1474 if (control) {
1475 // If we didn't snap, then we should still constrain horizontally or vertically
1476 // (When we did snap, then this constraint has already been enforced by
1477 // calling constrainedSnapTranslation() above)
1478 if (fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y])) {
1479 dxy[Geom::Y] = 0;
1480 } else {
1481 dxy[Geom::X] = 0;
1482 }
1483 }
1484 }
1485 }
1487 Geom::Matrix const move((Geom::Translate(dxy)));
1488 Geom::Point const norm(0, 0);
1489 transform(move, norm);
1491 // status text
1492 GString *xs = SP_PX_TO_METRIC_STRING(dxy[Geom::X], _desktop->namedview->getDefaultMetric());
1493 GString *ys = SP_PX_TO_METRIC_STRING(dxy[Geom::Y], _desktop->namedview->getDefaultMetric());
1494 _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);
1495 g_string_free(xs, TRUE);
1496 g_string_free(ys, TRUE);
1497 }
1499 // Given a location of a handle at the visual bounding box, find the corresponding location at the
1500 // geometrical bounding box
1501 Geom::Point Inkscape::SelTrans::_getGeomHandlePos(Geom::Point const &visual_handle_pos)
1502 {
1503 if ( _snap_bbox_type == SPItem::GEOMETRIC_BBOX) {
1504 // When the selector tool is using geometric bboxes, then the handle is already
1505 // located at one of the geometric bbox corners
1506 return visual_handle_pos;
1507 }
1509 if (!_geometric_bbox) {
1510 //_getGeomHandlePos() can only be used after _geometric_bbox has been defined!
1511 return visual_handle_pos;
1512 }
1514 // Using the Geom::Rect constructor below ensures that "min() < max()", which is important
1515 // because this will also hold for _bbox, and which is required for get_scale_transform_with_stroke()
1516 Geom::Rect new_bbox = Geom::Rect(_origin_for_bboxpoints, visual_handle_pos); // new visual bounding box
1517 // Please note that the new_bbox might in fact be just a single line, for example when stretching (in
1518 // which case the handle and origin will be aligned vertically or horizontally)
1519 Geom::Point normalized_handle_pos = (visual_handle_pos - new_bbox.min()) * Geom::Scale(new_bbox.dimensions()).inverse();
1521 // Calculate the absolute affine while taking into account the scaling of the stroke width
1522 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1523 bool transform_stroke = prefs->getBool("/options/transform/stroke", true);
1524 Geom::Matrix abs_affine = get_scale_transform_with_stroke (*_bbox, _strokewidth, transform_stroke,
1525 new_bbox.min()[Geom::X], new_bbox.min()[Geom::Y], new_bbox.max()[Geom::X], new_bbox.max()[Geom::Y]);
1527 // Calculate the scaled geometrical bbox
1528 Geom::Rect new_geom_bbox = Geom::Rect(_geometric_bbox->min() * abs_affine, _geometric_bbox->max() * abs_affine);
1529 // Find the location of the handle on this new geometrical bbox
1530 return normalized_handle_pos * Geom::Scale(new_geom_bbox.dimensions()) + new_geom_bbox.min(); //new position of the geometric handle
1531 }
1533 Geom::Scale Inkscape::calcScaleFactors(Geom::Point const &initial_point, Geom::Point const &new_point, Geom::Point const &origin, bool const skew)
1534 {
1535 // Work out the new scale factors for the bbox
1537 Geom::Point const initial_delta = initial_point - origin;
1538 Geom::Point const new_delta = new_point - origin;
1539 Geom::Point const offset = new_point - initial_point;
1540 Geom::Scale scale(1, 1);
1542 for ( unsigned int i = 0 ; i < 2 ; i++ ) {
1543 if ( fabs(initial_delta[i]) > 1e-6 ) {
1544 if (skew) {
1545 scale[i] = offset[1-i] / initial_delta[i];
1546 } else {
1547 scale[i] = new_delta[i] / initial_delta[i];
1548 }
1549 }
1550 }
1552 return scale;
1553 }
1555 // Only for scaling/stretching
1556 Geom::Point Inkscape::SelTrans::_calcAbsAffineDefault(Geom::Scale const default_scale)
1557 {
1558 Geom::Matrix abs_affine = Geom::Translate(-_origin) * Geom::Matrix(default_scale) * Geom::Translate(_origin);
1559 Geom::Point new_bbox_min = _approximate_bbox->min() * abs_affine;
1560 Geom::Point new_bbox_max = _approximate_bbox->max() * abs_affine;
1562 bool transform_stroke = false;
1563 gdouble strokewidth = 0;
1565 if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
1566 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1567 transform_stroke = prefs->getBool("/options/transform/stroke", true);
1568 strokewidth = _strokewidth;
1569 }
1571 _absolute_affine = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
1572 new_bbox_min[Geom::X], new_bbox_min[Geom::Y], new_bbox_max[Geom::X], new_bbox_max[Geom::Y]);
1574 // return the new handle position
1575 return ( _point - _origin ) * default_scale + _origin;
1576 }
1578 // Only for scaling/stretching
1579 Geom::Point Inkscape::SelTrans::_calcAbsAffineGeom(Geom::Scale const geom_scale)
1580 {
1581 _relative_affine = Geom::Matrix(geom_scale);
1582 _absolute_affine = Geom::Translate(-_origin_for_specpoints) * _relative_affine * Geom::Translate(_origin_for_specpoints);
1584 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1585 bool const transform_stroke = prefs->getBool("/options/transform/stroke", true);
1586 Geom::Rect visual_bbox = get_visual_bbox(_geometric_bbox, _absolute_affine, _strokewidth, transform_stroke);
1588 // return the new handle position
1589 return visual_bbox.min() + visual_bbox.dimensions() * Geom::Scale(_handle_x, _handle_y);
1590 }
1592 void Inkscape::SelTrans::_keepClosestPointOnly(std::vector<Geom::Point> &points, const Geom::Point &reference)
1593 {
1594 if (points.size() < 2) return;
1596 Geom::Point closest_point = Geom::Point(NR_HUGE, NR_HUGE);
1597 Geom::Coord closest_dist = NR_HUGE;
1599 for(std::vector<Geom::Point>::const_iterator i = points.begin(); i != points.end(); i++) {
1600 Geom::Coord dist = Geom::L2(*i - reference);
1601 if (i == points.begin() || dist < closest_dist) {
1602 closest_point = *i;
1603 closest_dist = dist;
1604 }
1605 }
1607 points.clear();
1608 points.push_back(closest_point);
1609 }
1611 /*
1612 Local Variables:
1613 mode:c++
1614 c-file-style:"stroustrup"
1615 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1616 indent-tabs-mode:nil
1617 fill-column:99
1618 End:
1619 */
1620 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :