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