614ce7584f7d4c0de05bd3ec9e5f151f36afe512
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 // ... and add the bbox corners to _bbox_points
316 for ( unsigned i = 0 ; i < 4 ; i++ ) {
317 _bbox_points.push_back(_bbox->corner(i));
318 }
319 // There are two separate "opposites" (i.e. opposite w.r.t. the handle being dragged):
320 // - one for snapping the boundingbox, which can be either visual or geometric
321 // - one for snapping the special points
322 // The "opposite" in case of a geometric boundingbox always coincides with the "opposite" for the special points
323 // These distinct "opposites" are needed in the snapmanager to avoid bugs such as #sf1540195 (in which
324 // a box is caught between two guides)
325 _opposite_for_bboxpoints = _bbox->min() + _bbox->dimensions() * Geom::Scale(1-x, 1-y);
326 _opposite_for_specpoints = snap_points_bbox.min() + snap_points_bbox.dimensions() * Geom::Scale(1-x, 1-y);
327 _opposite = _opposite_for_bboxpoints;
328 }
330 // The lines below are usefull for debugging any snapping issues, as they'll spit out all points that are considered for snapping
332 /*std::cout << "Number of snap points: " << _snap_points.size() << std::endl;
333 for (std::vector<Geom::Point>::const_iterator i = _snap_points.begin(); i != _snap_points.end(); i++)
334 {
335 std::cout << " " << *i << std::endl;
336 }
338 std::cout << "Number of bbox points: " << _bbox_points.size() << std::endl;
339 for (std::vector<Geom::Point>::const_iterator i = _bbox_points.begin(); i != _bbox_points.end(); i++)
340 {
341 std::cout << " " << *i << std::endl;
342 }*/
344 if ((x != -1) && (y != -1)) {
345 sp_canvas_item_show(_norm);
346 sp_canvas_item_show(_grip);
347 }
349 if (_show == SHOW_OUTLINE) {
350 for (int i = 0; i < 4; i++)
351 sp_canvas_item_show(_l[i]);
352 }
354 _updateHandles();
355 g_return_if_fail(_stamp_cache == NULL);
356 }
358 void Inkscape::SelTrans::transform(Geom::Matrix const &rel_affine, Geom::Point const &norm)
359 {
360 g_return_if_fail(_grabbed);
361 g_return_if_fail(!_empty);
363 Geom::Matrix const affine( Geom::Translate(-norm) * rel_affine * Geom::Translate(norm) );
365 if (_show == SHOW_CONTENT) {
366 // update the content
367 for (unsigned i = 0; i < _items.size(); i++) {
368 SPItem &item = *_items[i];
369 Geom::Matrix const &prev_transform = _items_affines[i];
370 sp_item_set_i2d_affine(&item, prev_transform * affine);
371 }
372 } else {
373 if (_bbox) {
374 Geom::Point p[4];
375 /* update the outline */
376 for (unsigned i = 0 ; i < 4 ; i++) {
377 p[i] = _bbox->corner(i) * affine;
378 }
379 for (unsigned i = 0 ; i < 4 ; i++) {
380 sp_ctrlline_set_coords(SP_CTRLLINE(_l[i]), p[i], p[(i+1)%4]);
381 }
382 }
383 }
385 _current_relative_affine = affine;
386 _changed = true;
387 _updateHandles();
388 }
390 void Inkscape::SelTrans::ungrab()
391 {
392 g_return_if_fail(_grabbed);
393 _grabbed = false;
394 _show_handles = true;
396 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
397 _updateVolatileState();
399 for (unsigned i = 0; i < _items.size(); i++) {
400 sp_object_unref(SP_OBJECT(_items[i]), NULL);
401 }
403 sp_canvas_item_hide(_norm);
404 sp_canvas_item_hide(_grip);
406 if (_show == SHOW_OUTLINE) {
407 for (int i = 0; i < 4; i++)
408 sp_canvas_item_hide(_l[i]);
409 }
411 if (_stamp_cache) {
412 g_slist_free(_stamp_cache);
413 _stamp_cache = NULL;
414 }
416 _message_context.clear();
418 if (!_empty && _changed) {
419 sp_selection_apply_affine(selection, _current_relative_affine, (_show == SHOW_OUTLINE)? true : false);
420 if (_center) {
421 *_center *= _current_relative_affine;
422 _center_is_set = true;
423 }
425 // If dragging showed content live, sp_selection_apply_affine cannot change the centers
426 // appropriately - it does not know the original positions of the centers (all objects already have
427 // the new bboxes). So we need to reset the centers from our saved array.
428 if (_show != SHOW_OUTLINE && !_current_relative_affine.isTranslation()) {
429 for (unsigned i = 0; i < _items_centers.size(); i++) {
430 SPItem *currentItem = _items[i];
431 if (currentItem->isCenterSet()) { // only if it's already set
432 currentItem->setCenter (_items_centers[i] * _current_relative_affine);
433 SP_OBJECT(currentItem)->updateRepr();
434 }
435 }
436 }
438 _items.clear();
439 _items_const.clear();
440 _items_affines.clear();
441 _items_centers.clear();
443 if (_current_relative_affine.isTranslation()) {
444 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
445 _("Move"));
446 } else if (_current_relative_affine.isScale()) {
447 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
448 _("Scale"));
449 } else if (_current_relative_affine.isRotation()) {
450 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
451 _("Rotate"));
452 } else {
453 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
454 _("Skew"));
455 }
457 } else {
459 if (_center_is_set) {
460 // we were dragging center; update reprs and commit undoable action
461 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
462 SPItem *it = (SPItem*)SP_OBJECT(l->data);
463 SP_OBJECT(it)->updateRepr();
464 }
465 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
466 _("Set center"));
467 }
469 _items.clear();
470 _items_const.clear();
471 _items_affines.clear();
472 _items_centers.clear();
473 _updateHandles();
474 }
475 }
477 /* fixme: This is really bad, as we compare positions for each stamp (Lauris) */
478 /* fixme: IMHO the best way to keep sort cache would be to implement timestamping at last */
480 void Inkscape::SelTrans::stamp()
481 {
482 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
484 bool fixup = !_grabbed;
485 if ( fixup && _stamp_cache ) {
486 // TODO - give a proper fix. Simple temproary work-around for the grab() issue
487 g_slist_free(_stamp_cache);
488 _stamp_cache = NULL;
489 }
491 /* stamping mode */
492 if (!_empty) {
493 GSList *l;
494 if (_stamp_cache) {
495 l = _stamp_cache;
496 } else {
497 /* Build cache */
498 l = g_slist_copy((GSList *) selection->itemList());
499 l = g_slist_sort(l, (GCompareFunc) sp_object_compare_position);
500 _stamp_cache = l;
501 }
503 while (l) {
504 SPItem *original_item = SP_ITEM(l->data);
505 Inkscape::XML::Node *original_repr = SP_OBJECT_REPR(original_item);
507 // remember the position of the item
508 gint pos = original_repr->position();
509 // remember parent
510 Inkscape::XML::Node *parent = sp_repr_parent(original_repr);
512 Inkscape::XML::Node *copy_repr = original_repr->duplicate(parent->document());
514 // add the new repr to the parent
515 parent->appendChild(copy_repr);
516 // move to the saved position
517 copy_repr->setPosition(pos > 0 ? pos : 0);
519 SPItem *copy_item = (SPItem *) sp_desktop_document(_desktop)->getObjectByRepr(copy_repr);
521 Geom::Matrix const *new_affine;
522 if (_show == SHOW_OUTLINE) {
523 Geom::Matrix const i2d(sp_item_i2d_affine(original_item));
524 Geom::Matrix const i2dnew( i2d * _current_relative_affine );
525 sp_item_set_i2d_affine(copy_item, i2dnew);
526 new_affine = ©_item->transform;
527 } else {
528 new_affine = &original_item->transform;
529 }
531 sp_item_write_transform(copy_item, copy_repr, *new_affine);
533 if ( copy_item->isCenterSet() && _center ) {
534 copy_item->setCenter(*_center * _current_relative_affine);
535 }
537 Inkscape::GC::release(copy_repr);
538 l = l->next;
539 }
540 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
541 _("Stamp"));
542 }
544 if ( fixup && _stamp_cache ) {
545 // TODO - give a proper fix. Simple temproary work-around for the grab() issue
546 g_slist_free(_stamp_cache);
547 _stamp_cache = NULL;
548 }
549 }
551 void Inkscape::SelTrans::_updateHandles()
552 {
553 if ( !_show_handles || _empty )
554 {
555 sp_remove_handles(_shandle, 8);
556 sp_remove_handles(_rhandle, 8);
557 sp_remove_handles(&_chandle, 1);
558 return;
559 }
561 // center handle
562 if ( _chandle == NULL ) {
563 _chandle = sp_knot_new(_desktop, _("<b>Center</b> of rotation and skewing: drag to reposition; scaling with Shift also uses this center"));
565 _chandle->setShape (SP_CTRL_SHAPE_BITMAP);
566 _chandle->setSize (13);
567 _chandle->setAnchor (handle_center.anchor);
568 _chandle->setMode (SP_CTRL_MODE_XOR);
569 _chandle->setFill(0x00000000, 0x00000000, 0x00000000);
570 _chandle->setStroke(0x000000ff, 0xff0000b0, 0xff0000b0);
571 _chandle->setPixbuf(handles[handle_center.control]);
572 sp_knot_update_ctrl(_chandle);
574 g_signal_connect(G_OBJECT(_chandle), "request",
575 G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle_center);
576 g_signal_connect(G_OBJECT(_chandle), "moved",
577 G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle_center);
578 g_signal_connect(G_OBJECT(_chandle), "grabbed",
579 G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle_center);
580 g_signal_connect(G_OBJECT(_chandle), "ungrabbed",
581 G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle_center);
582 g_signal_connect(G_OBJECT(_chandle), "clicked",
583 G_CALLBACK(sp_sel_trans_handle_click), (gpointer) &handle_center);
584 }
586 sp_remove_handles(&_chandle, 1);
587 if ( _state == STATE_SCALE ) {
588 sp_remove_handles(_rhandle, 8);
589 _showHandles(_shandle, handles_scale, 8,
590 _("<b>Squeeze or stretch</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"),
591 _("<b>Scale</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"));
592 } else {
593 sp_remove_handles(_shandle, 8);
594 _showHandles(_rhandle, handles_rotate, 8,
595 _("<b>Skew</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to skew around the opposite side"),
596 _("<b>Rotate</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to rotate around the opposite corner"));
597 }
599 if (!_center_is_set) {
600 _center = _desktop->selection->center();
601 _center_is_set = true;
602 }
604 if ( _state == STATE_SCALE || !_center ) {
605 sp_knot_hide(_chandle);
606 } else {
607 sp_knot_show(_chandle);
608 sp_knot_moveto(_chandle, *_center);
609 }
610 }
612 void Inkscape::SelTrans::_updateVolatileState()
613 {
614 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
615 _empty = selection->isEmpty();
617 if (_empty) {
618 return;
619 }
621 //Update the bboxes
622 _bbox = selection->bounds(_snap_bbox_type);
623 _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX);
625 if (!_bbox) {
626 _empty = true;
627 return;
628 }
630 _strokewidth = stroke_average_width (selection->itemList());
631 }
633 static void sp_remove_handles(SPKnot *knot[], gint num)
634 {
635 for (int i = 0; i < num; i++) {
636 if (knot[i] != NULL) {
637 sp_knot_hide(knot[i]);
638 }
639 }
640 }
642 void Inkscape::SelTrans::_showHandles(SPKnot *knot[], SPSelTransHandle const handle[], gint num,
643 gchar const *even_tip, gchar const *odd_tip)
644 {
645 g_return_if_fail( !_empty );
647 for (int i = 0; i < num; i++) {
648 if (knot[i] == NULL) {
649 knot[i] = sp_knot_new(_desktop, i % 2 ? even_tip : odd_tip);
651 knot[i]->setShape (SP_CTRL_SHAPE_BITMAP);
652 knot[i]->setSize (13);
653 knot[i]->setAnchor (handle[i].anchor);
654 knot[i]->setMode (SP_CTRL_MODE_XOR);
655 knot[i]->setFill(0x000000ff, 0x00ff6600, 0x00ff6600); // inversion, green, green
656 knot[i]->setStroke(0x000000ff, 0x000000ff, 0x000000ff); // inversion
657 knot[i]->setPixbuf(handles[handle[i].control]);
658 sp_knot_update_ctrl(knot[i]);
660 g_signal_connect(G_OBJECT(knot[i]), "request",
661 G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle[i]);
662 g_signal_connect(G_OBJECT(knot[i]), "moved",
663 G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle[i]);
664 g_signal_connect(G_OBJECT(knot[i]), "grabbed",
665 G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle[i]);
666 g_signal_connect(G_OBJECT(knot[i]), "ungrabbed",
667 G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle[i]);
668 g_signal_connect(G_OBJECT(knot[i]), "event", G_CALLBACK(sp_seltrans_handle_event), (gpointer) &handle[i]);
669 }
670 sp_knot_show(knot[i]);
672 Geom::Point const handle_pt(handle[i].x, handle[i].y);
673 // shouldn't have nullary bbox, but knots
674 g_assert(_bbox);
675 Geom::Point p( _bbox->min()
676 + ( _bbox->dimensions()
677 * Geom::Scale(handle_pt) ) );
679 sp_knot_moveto(knot[i], p);
680 }
681 }
683 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data)
684 {
685 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleGrab(
686 knot, state, *(SPSelTransHandle const *) data
687 );
688 }
690 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint /*state*/, gpointer /*data*/)
691 {
692 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->ungrab();
693 }
695 static void sp_sel_trans_handle_new_event(SPKnot *knot, Geom::Point *position, guint state, gpointer data)
696 {
697 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleNewEvent(
698 knot, position, state, *(SPSelTransHandle const *) data
699 );
700 }
702 static gboolean sp_sel_trans_handle_request(SPKnot *knot, Geom::Point *position, guint state, gboolean *data)
703 {
704 return SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleRequest(
705 knot, position, state, *(SPSelTransHandle const *) data
706 );
707 }
709 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data)
710 {
711 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleClick(
712 knot, state, *(SPSelTransHandle const *) data
713 );
714 }
716 void Inkscape::SelTrans::handleClick(SPKnot */*knot*/, guint state, SPSelTransHandle const &handle)
717 {
718 switch (handle.anchor) {
719 case GTK_ANCHOR_CENTER:
720 if (state & GDK_SHIFT_MASK) {
721 // Unset the center position for all selected items
722 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
723 SPItem *it = (SPItem*)(SP_OBJECT(l->data));
724 it->unsetCenter();
725 SP_OBJECT(it)->updateRepr();
726 _center_is_set = false; // center has changed
727 _updateHandles();
728 }
729 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
730 _("Reset center"));
731 }
732 break;
733 default:
734 break;
735 }
736 }
738 void Inkscape::SelTrans::handleGrab(SPKnot *knot, guint /*state*/, SPSelTransHandle const &handle)
739 {
740 switch (handle.anchor) {
741 case GTK_ANCHOR_CENTER:
742 g_object_set(G_OBJECT(_grip),
743 "shape", SP_CTRL_SHAPE_BITMAP,
744 "size", 13.0,
745 NULL);
746 sp_canvas_item_show(_grip);
747 break;
748 default:
749 g_object_set(G_OBJECT(_grip),
750 "shape", SP_CTRL_SHAPE_CROSS,
751 "size", 7.0,
752 NULL);
753 sp_canvas_item_show(_norm);
754 sp_canvas_item_show(_grip);
756 break;
757 }
759 grab(sp_knot_position(knot), handle.x, handle.y, FALSE);
760 }
763 void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const &handle)
764 {
765 if (!SP_KNOT_IS_GRABBED(knot)) {
766 return;
767 }
769 // in case items have been unhooked from the document, don't
770 // try to continue processing events for them.
771 for (unsigned int i = 0; i < _items.size(); i++) {
772 if (!SP_OBJECT_DOCUMENT(SP_OBJECT(_items[i])) ) {
773 return;
774 }
775 }
777 handle.action(this, handle, *position, state);
778 }
781 gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const &handle)
782 {
783 if (!SP_KNOT_IS_GRABBED(knot)) {
784 return TRUE;
785 }
787 knot->desktop->setPosition(*position);
789 // When holding shift while rotating or skewing, the transformation will be
790 // relative to the point opposite of the handle; otherwise it will be relative
791 // to the center as set for the selection
792 if ((!(state & GDK_SHIFT_MASK) == !(_state == STATE_ROTATE)) && (&handle != &handle_center)) {
793 _origin = _opposite;
794 _origin_for_bboxpoints = _opposite_for_bboxpoints;
795 _origin_for_specpoints = _opposite_for_specpoints;
796 } else if (_center) {
797 _origin = *_center;
798 _origin_for_bboxpoints = *_center;
799 _origin_for_specpoints = *_center;
800 } else {
801 // FIXME
802 return TRUE;
803 }
804 if (handle.request(this, handle, *position, state)) {
805 sp_knot_set_position(knot, *position, state);
806 SP_CTRL(_grip)->moveto(*position);
807 SP_CTRL(_norm)->moveto(_origin);
808 }
810 return TRUE;
811 }
814 void Inkscape::SelTrans::_selChanged(Inkscape::Selection */*selection*/)
815 {
816 if (!_grabbed) {
817 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
818 // reread in case it changed on the fly:
819 int prefs_bbox = prefs->getBool("/tools/bounding_box");
820 _snap_bbox_type = !prefs_bbox ?
821 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
822 //SPItem::APPROXIMATE_BBOX will be replaced by SPItem::VISUAL_BBOX, as soon as the latter is implemented properly
824 _updateVolatileState();
825 _current_relative_affine.setIdentity();
826 _center_is_set = false; // center(s) may have changed
827 _updateHandles();
828 }
829 }
831 void Inkscape::SelTrans::_selModified(Inkscape::Selection */*selection*/, guint /*flags*/)
832 {
833 if (!_grabbed) {
834 _updateVolatileState();
835 _current_relative_affine.setIdentity();
837 // reset internal flag
838 _changed = false;
840 _center_is_set = false; // center(s) may have changed
842 _updateHandles();
843 }
844 }
846 /*
847 * handlers for handle move-request
848 */
850 /** Returns -1 or 1 according to the sign of x. Returns 1 for 0 and NaN. */
851 static double sign(double const x)
852 {
853 return ( x < 0
854 ? -1
855 : 1 );
856 }
858 gboolean sp_sel_trans_scale_request(Inkscape::SelTrans *seltrans,
859 SPSelTransHandle const &, Geom::Point &pt, guint state)
860 {
861 return seltrans->scaleRequest(pt, state);
862 }
864 gboolean sp_sel_trans_stretch_request(Inkscape::SelTrans *seltrans,
865 SPSelTransHandle const &handle, Geom::Point &pt, guint state)
866 {
867 return seltrans->stretchRequest(handle, pt, state);
868 }
870 gboolean sp_sel_trans_skew_request(Inkscape::SelTrans *seltrans,
871 SPSelTransHandle const &handle, Geom::Point &pt, guint state)
872 {
873 return seltrans->skewRequest(handle, pt, state);
874 }
876 gboolean sp_sel_trans_rotate_request(Inkscape::SelTrans *seltrans,
877 SPSelTransHandle const &, Geom::Point &pt, guint state)
878 {
879 return seltrans->rotateRequest(pt, state);
880 }
882 gboolean sp_sel_trans_center_request(Inkscape::SelTrans *seltrans,
883 SPSelTransHandle const &, Geom::Point &pt, guint state)
884 {
885 return seltrans->centerRequest(pt, state);
886 }
888 gboolean Inkscape::SelTrans::scaleRequest(Geom::Point &pt, guint state)
889 {
891 // Calculate the scale factors, which can be either visual or geometric
892 // depending on which type of bbox is currently being used (see preferences -> selector tool)
893 Geom::Scale default_scale = calcScaleFactors(_point, pt, _origin);
895 // Find the scale factors for the geometric bbox
896 Geom::Point pt_geom = _getGeomHandlePos(pt);
897 Geom::Scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
899 _absolute_affine = Geom::identity(); //Initialize the scaler
901 if (state & GDK_MOD1_MASK) { // scale by an integer multiplier/divider
902 // We're scaling either the visual or the geometric bbox here (see the comment above)
903 for ( unsigned int i = 0 ; i < 2 ; i++ ) {
904 if (fabs(default_scale[i]) > 1) {
905 default_scale[i] = round(default_scale[i]);
906 } else if (default_scale[i] != 0) {
907 default_scale[i] = 1/round(1/(MIN(default_scale[i], 10)));
908 }
909 }
910 // Update the knot position
911 pt = _calcAbsAffineDefault(default_scale);
912 // When scaling by an integer, snapping is not needed
913 } else {
914 // In all other cases we should try to snap now
915 SnapManager &m = _desktop->namedview->snap_manager;
916 m.setup(_desktop, false, _items_const);
918 Inkscape::SnappedPoint bb, sn;
919 Geom::Coord bd(NR_HUGE);
920 Geom::Coord sd(NR_HUGE);
922 if ((state & GDK_CONTROL_MASK) || _desktop->isToolboxButtonActive ("lock")) {
923 // Scale is locked to a 1:1 aspect ratio, so that s[X] must be made to equal s[Y].
924 //
925 // The aspect-ratio must be locked before snapping
926 if (fabs(default_scale[Geom::X]) > fabs(default_scale[Geom::Y])) {
927 default_scale[Geom::X] = fabs(default_scale[Geom::Y]) * sign(default_scale[Geom::X]);
928 geom_scale[Geom::X] = fabs(geom_scale[Geom::Y]) * sign(geom_scale[Geom::X]);
929 } else {
930 default_scale[Geom::Y] = fabs(default_scale[Geom::X]) * sign(default_scale[Geom::Y]);
931 geom_scale[Geom::Y] = fabs(geom_scale[Geom::X]) * sign(geom_scale[Geom::Y]);
932 }
934 // Snap along a suitable constraint vector from the origin.
935 bb = m.constrainedSnapScale(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, default_scale, _origin_for_bboxpoints);
936 sn = m.constrainedSnapScale(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, geom_scale, _origin_for_specpoints);
938 /* Choose the smaller difference in scale. Since s[X] == s[Y] we can
939 ** just compare difference in s[X].
940 */
941 bd = bb.getSnapped() ? fabs(bb.getTransformation()[Geom::X] - default_scale[Geom::X]) : NR_HUGE;
942 sd = sn.getSnapped() ? fabs(sn.getTransformation()[Geom::X] - geom_scale[Geom::X]) : NR_HUGE;
943 } else {
944 /* Scale aspect ratio is unlocked */
945 bb = m.freeSnapScale(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, default_scale, _origin_for_bboxpoints);
946 sn = m.freeSnapScale(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, geom_scale, _origin_for_specpoints);
948 /* Pick the snap that puts us closest to the original scale */
949 bd = bb.getSnapped() ? fabs(Geom::L2(bb.getTransformation()) - Geom::L2(Geom::Point(default_scale[Geom::X], default_scale[Geom::Y]))) : NR_HUGE;
950 sd = sn.getSnapped() ? fabs(Geom::L2(sn.getTransformation()) - Geom::L2(Geom::Point(geom_scale[Geom::X], geom_scale[Geom::Y]))) : NR_HUGE;
951 }
953 if (!(bb.getSnapped() || sn.getSnapped())) {
954 // We didn't snap at all! Don't update the handle position, just calculate the new transformation
955 _calcAbsAffineDefault(default_scale);
956 _desktop->snapindicator->remove_snappoint();
957 } else if (bd < sd) {
958 // We snapped the bbox (which is either visual or geometric)
959 _desktop->snapindicator->set_new_snappoint(bb);
960 default_scale = Geom::Scale(bb.getTransformation());
961 // Calculate the new transformation and update the handle position
962 pt = _calcAbsAffineDefault(default_scale);
963 } else {
964 _desktop->snapindicator->set_new_snappoint(sn);
965 // We snapped the special points (e.g. nodes), which are not at the visual bbox
966 // The handle location however (pt) might however be at the visual bbox, so we
967 // will have to calculate pt taking the stroke width into account
968 geom_scale = Geom::Scale(sn.getTransformation());
969 pt = _calcAbsAffineGeom(geom_scale);
970 }
971 }
973 /* Status text */
974 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
975 _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
976 100 * _absolute_affine[0], 100 * _absolute_affine[3]);
978 return TRUE;
979 }
981 gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, Geom::Point &pt, guint state)
982 {
983 Geom::Dim2 axis, perp;
984 switch (handle.cursor) {
985 case GDK_TOP_SIDE:
986 case GDK_BOTTOM_SIDE:
987 axis = Geom::Y;
988 perp = Geom::X;
989 break;
990 case GDK_LEFT_SIDE:
991 case GDK_RIGHT_SIDE:
992 axis = Geom::X;
993 perp = Geom::Y;
994 break;
995 default:
996 g_assert_not_reached();
997 return TRUE;
998 };
1000 // Calculate the scale factors, which can be either visual or geometric
1001 // depending on which type of bbox is currently being used (see preferences -> selector tool)
1002 Geom::Scale default_scale = calcScaleFactors(_point, pt, _origin);
1003 default_scale[perp] = 1;
1005 // Find the scale factors for the geometric bbox
1006 Geom::Point pt_geom = _getGeomHandlePos(pt);
1007 Geom::Scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
1008 geom_scale[perp] = 1;
1010 _absolute_affine = Geom::identity(); //Initialize the scaler
1012 if (state & GDK_MOD1_MASK) { // stretch by an integer multiplier/divider
1013 if (fabs(default_scale[axis]) > 1) {
1014 default_scale[axis] = round(default_scale[axis]);
1015 } else if (default_scale[axis] != 0) {
1016 default_scale[axis] = 1/round(1/(MIN(default_scale[axis], 10)));
1017 }
1018 // Calculate the new transformation and update the handle position
1019 pt = _calcAbsAffineDefault(default_scale);
1020 // When stretching by an integer, snapping is not needed
1021 } else {
1022 // In all other cases we should try to snap now
1024 SnapManager &m = _desktop->namedview->snap_manager;
1025 m.setup(_desktop, false, _items_const);
1027 Inkscape::SnappedPoint bb, sn;
1028 g_assert(bb.getSnapped() == false); // Check initialization to catch any regression
1029 Geom::Coord bd(NR_HUGE);
1030 Geom::Coord sd(NR_HUGE);
1032 bool symmetrical = state & GDK_CONTROL_MASK;
1034 bb = m.constrainedSnapStretch(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, Geom::Coord(default_scale[axis]), _origin_for_bboxpoints, Geom::Dim2(axis), symmetrical);
1035 sn = m.constrainedSnapStretch(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, Geom::Coord(geom_scale[axis]), _origin_for_specpoints, Geom::Dim2(axis), symmetrical);
1037 if (bb.getSnapped()) {
1038 // We snapped the bbox (which is either visual or geometric)
1039 bd = fabs(bb.getTransformation()[axis] - default_scale[axis]);
1040 default_scale[axis] = bb.getTransformation()[axis];
1041 }
1043 if (sn.getSnapped()) {
1044 sd = fabs(sn.getTransformation()[axis] - geom_scale[axis]);
1045 geom_scale[axis] = sn.getTransformation()[axis];
1046 }
1048 if (symmetrical) {
1049 // on ctrl, apply symmetrical scaling instead of stretching
1050 // Preserve aspect ratio, but never flip in the dimension not being edited (by using fabs())
1051 default_scale[perp] = fabs(default_scale[axis]);
1052 geom_scale[perp] = fabs(geom_scale[axis]);
1053 }
1055 if (!(bb.getSnapped() || sn.getSnapped())) {
1056 // We didn't snap at all! Don't update the handle position, just calculate the new transformation
1057 _calcAbsAffineDefault(default_scale);
1058 _desktop->snapindicator->remove_snappoint();
1059 } else if (bd < sd) {
1060 _desktop->snapindicator->set_new_snappoint(bb);
1061 // Calculate the new transformation and update the handle position
1062 pt = _calcAbsAffineDefault(default_scale);
1063 } else {
1064 _desktop->snapindicator->set_new_snappoint(sn);
1065 // We snapped the special points (e.g. nodes), which are not at the visual bbox
1066 // The handle location however (pt) might however be at the visual bbox, so we
1067 // will have to calculate pt taking the stroke width into account
1068 pt = _calcAbsAffineGeom(geom_scale);
1069 }
1070 }
1072 // status text
1073 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1074 _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1075 100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1077 return TRUE;
1078 }
1080 gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1081 {
1082 /* When skewing (or rotating):
1083 * 1) the stroke width will not change. This makes life much easier because we don't have to
1084 * account for that (like for scaling or stretching). As a consequence, all points will
1085 * have the same origin for the transformation and for the snapping.
1086 * 2) When holding shift, the transformation will be relative to the point opposite of
1087 * the handle; otherwise it will be relative to the center as set for the selection
1088 */
1090 Geom::Dim2 dim_a;
1091 Geom::Dim2 dim_b;
1093 switch (handle.cursor) {
1094 case GDK_SB_H_DOUBLE_ARROW:
1095 dim_a = Geom::Y;
1096 dim_b = Geom::X;
1097 break;
1098 case GDK_SB_V_DOUBLE_ARROW:
1099 dim_a = Geom::X;
1100 dim_b = Geom::Y;
1101 break;
1102 default:
1103 g_assert_not_reached();
1104 abort();
1105 break;
1106 }
1108 Geom::Point const initial_delta = _point - _origin;
1110 if (fabs(initial_delta[dim_a]) < 1e-15) {
1111 return false;
1112 }
1114 // Calculate the scale factors, which can be either visual or geometric
1115 // depending on which type of bbox is currently being used (see preferences -> selector tool)
1116 Geom::Scale scale = calcScaleFactors(_point, pt, _origin, false);
1117 Geom::Scale skew = calcScaleFactors(_point, pt, _origin, true);
1118 scale[dim_b] = 1;
1119 skew[dim_b] = 1;
1121 if (fabs(scale[dim_a]) < 1) {
1122 // Prevent shrinking of the selected object, while allowing mirroring
1123 scale[dim_a] = sign(scale[dim_a]);
1124 } else {
1125 // Allow expanding of the selected object by integer multiples
1126 scale[dim_a] = floor(scale[dim_a] + 0.5);
1127 }
1129 double radians = atan(skew[dim_a] / scale[dim_a]);
1131 if (state & GDK_CONTROL_MASK) {
1132 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1133 // Snap to defined angle increments
1134 int snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12);
1135 if (snaps) {
1136 double sections = floor(radians * snaps / M_PI + .5);
1137 if (fabs(sections) >= snaps / 2) {
1138 sections = sign(sections) * (snaps / 2 - 1);
1139 }
1140 radians = (M_PI / snaps) * sections;
1141 }
1142 skew[dim_a] = tan(radians) * scale[dim_a];
1143 } else {
1144 // Snap to objects, grids, guides
1146 SnapManager &m = _desktop->namedview->snap_manager;
1147 m.setup(_desktop, false, _items_const);
1149 Inkscape::Snapper::ConstraintLine const constraint(component_vectors[dim_b]);
1150 // When skewing, we cannot snap the corners of the bounding box, see the comment in "constrainedSnapSkew" for details
1151 Geom::Point const s(skew[dim_a], scale[dim_a]);
1152 Inkscape::SnappedPoint sn = m.constrainedSnapSkew(Inkscape::SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, constraint, s, _origin, Geom::Dim2(dim_b));
1154 if (sn.getSnapped()) {
1155 // We snapped something, so change the skew to reflect it
1156 Geom::Coord const sd = sn.getSnapped() ? sn.getTransformation()[0] : NR_HUGE;
1157 _desktop->snapindicator->set_new_snappoint(sn);
1158 skew[dim_a] = sd;
1159 } else {
1160 _desktop->snapindicator->remove_snappoint();
1161 }
1162 }
1164 // Update the handle position
1165 pt[dim_b] = initial_delta[dim_a] * skew[dim_a] + _point[dim_b];
1166 pt[dim_a] = initial_delta[dim_a] * scale[dim_a] + _origin[dim_a];
1168 // Calculate the relative affine
1169 _relative_affine = Geom::identity();
1170 _relative_affine[2*dim_a + dim_a] = (pt[dim_a] - _origin[dim_a]) / initial_delta[dim_a];
1171 _relative_affine[2*dim_a + (dim_b)] = (pt[dim_b] - _point[dim_b]) / initial_delta[dim_a];
1172 _relative_affine[2*(dim_b) + (dim_a)] = 0;
1173 _relative_affine[2*(dim_b) + (dim_b)] = 1;
1175 for (int i = 0; i < 2; i++) {
1176 if (fabs(_relative_affine[3*i]) < 1e-15) {
1177 _relative_affine[3*i] = 1e-15;
1178 }
1179 }
1181 // Update the status text
1182 double degrees = mod360symm(Geom::rad_to_deg(radians));
1183 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1184 // TRANSLATORS: don't modify the first ";"
1185 // (it will NOT be displayed as ";" - only the second one will be)
1186 _("<b>Skew</b>: %0.2f°; with <b>Ctrl</b> to snap angle"),
1187 degrees);
1189 return TRUE;
1190 }
1192 gboolean Inkscape::SelTrans::rotateRequest(Geom::Point &pt, guint state)
1193 {
1194 /* When rotating (or skewing):
1195 * 1) the stroke width will not change. This makes life much easier because we don't have to
1196 * account for that (like for scaling or stretching). As a consequence, all points will
1197 * have the same origin for the transformation and for the snapping.
1198 * 2) When holding shift, the transformation will be relative to the point opposite of
1199 * the handle; otherwise it will be relative to the center as set for the selection
1200 */
1202 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1203 int snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12);
1205 // rotate affine in rotate
1206 Geom::Point const d1 = _point - _origin;
1207 Geom::Point const d2 = pt - _origin;
1209 Geom::Coord const h1 = Geom::L2(d1); // initial radius
1210 if (h1 < 1e-15) return FALSE;
1211 Geom::Point q1 = d1 / h1; // normalized initial vector to handle
1212 Geom::Coord const h2 = Geom::L2(d2); // new radius
1213 if (fabs(h2) < 1e-15) return FALSE;
1214 Geom::Point q2 = d2 / h2; // normalized new vector to handle
1216 double radians;
1217 if (state & GDK_CONTROL_MASK) {
1218 // Snap to defined angle increments
1219 double cos_t = Geom::dot(q1, q2);
1220 double sin_t = Geom::dot(Geom::rot90(q1), q2);
1221 radians = atan2(sin_t, cos_t);
1222 if (snaps) {
1223 radians = ( M_PI / snaps ) * floor( radians * snaps / M_PI + .5 );
1224 }
1225 q1 = Geom::Point(1, 0);
1226 q2 = Geom::Point(cos(radians), sin(radians));
1227 } else {
1228 radians = atan2(Geom::dot(Geom::rot90(d1), d2),
1229 Geom::dot(d1, d2));
1230 }
1232 Geom::Rotate const r1(q1);
1233 Geom::Rotate const r2(q2);
1235 // Calculate the relative affine
1236 _relative_affine = r2 * r1.inverse();
1238 // Update the handle position
1239 pt = _point * Geom::Translate(-_origin) * _relative_affine * Geom::Translate(_origin);
1241 // Update the status text
1242 double degrees = mod360symm(Geom::rad_to_deg(radians));
1243 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1244 // TRANSLATORS: don't modify the first ";"
1245 // (it will NOT be displayed as ";" - only the second one will be)
1246 _("<b>Rotate</b>: %0.2f°; with <b>Ctrl</b> to snap angle"), degrees);
1248 return TRUE;
1249 }
1251 gboolean Inkscape::SelTrans::centerRequest(Geom::Point &pt, guint state)
1252 {
1253 SnapManager &m = _desktop->namedview->snap_manager;
1254 m.setup(_desktop);
1255 m.freeSnapReturnByRef(SnapPreferences::SNAPPOINT_NODE, pt);
1257 if (state & GDK_CONTROL_MASK) {
1258 if ( fabs(_point[Geom::X] - pt[Geom::X]) > fabs(_point[Geom::Y] - pt[Geom::Y]) ) {
1259 pt[Geom::Y] = _point[Geom::Y];
1260 } else {
1261 pt[Geom::X] = _point[Geom::X];
1262 }
1263 }
1265 if ( !(state & GDK_SHIFT_MASK) && _bbox ) {
1266 // screen pixels to snap center to bbox
1267 #define SNAP_DIST 5
1268 // FIXME: take from prefs
1269 double snap_dist = SNAP_DIST / _desktop->current_zoom();
1271 for (int i = 0; i < 2; i++) {
1272 if (fabs(pt[i] - _bbox->min()[i]) < snap_dist) {
1273 pt[i] = _bbox->min()[i];
1274 }
1275 if (fabs(pt[i] - _bbox->midpoint()[i]) < snap_dist) {
1276 pt[i] = _bbox->midpoint()[i];
1277 }
1278 if (fabs(pt[i] - _bbox->max()[i]) < snap_dist) {
1279 pt[i] = _bbox->max()[i];
1280 }
1281 }
1282 }
1284 // status text
1285 GString *xs = SP_PX_TO_METRIC_STRING(pt[Geom::X], _desktop->namedview->getDefaultMetric());
1286 GString *ys = SP_PX_TO_METRIC_STRING(pt[Geom::Y], _desktop->namedview->getDefaultMetric());
1287 _message_context.setF(Inkscape::NORMAL_MESSAGE, _("Move <b>center</b> to %s, %s"), xs->str, ys->str);
1288 g_string_free(xs, FALSE);
1289 g_string_free(ys, FALSE);
1291 return TRUE;
1292 }
1294 /*
1295 * handlers for handle movement
1296 *
1297 */
1299 void sp_sel_trans_stretch(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1300 {
1301 seltrans->stretch(handle, pt, state);
1302 }
1304 void sp_sel_trans_scale(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint state)
1305 {
1306 seltrans->scale(pt, state);
1307 }
1309 void sp_sel_trans_skew(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1310 {
1311 seltrans->skew(handle, pt, state);
1312 }
1314 void sp_sel_trans_rotate(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint state)
1315 {
1316 seltrans->rotate(pt, state);
1317 }
1319 void Inkscape::SelTrans::stretch(SPSelTransHandle const &/*handle*/, Geom::Point &/*pt*/, guint /*state*/)
1320 {
1321 transform(_absolute_affine, Geom::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1322 }
1324 void Inkscape::SelTrans::scale(Geom::Point &/*pt*/, guint /*state*/)
1325 {
1326 transform(_absolute_affine, Geom::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1327 }
1329 void Inkscape::SelTrans::skew(SPSelTransHandle const &/*handle*/, Geom::Point &/*pt*/, guint /*state*/)
1330 {
1331 transform(_relative_affine, _origin);
1332 }
1334 void Inkscape::SelTrans::rotate(Geom::Point &/*pt*/, guint /*state*/)
1335 {
1336 transform(_relative_affine, _origin);
1337 }
1339 void sp_sel_trans_center(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint /*state*/)
1340 {
1341 seltrans->setCenter(pt);
1342 }
1345 void Inkscape::SelTrans::moveTo(Geom::Point const &xy, guint state)
1346 {
1347 SnapManager &m = _desktop->namedview->snap_manager;
1348 m.setup(_desktop, true, _items_const);
1350 /* The amount that we've moved by during this drag */
1351 Geom::Point dxy = xy - _point;
1353 bool const alt = (state & GDK_MOD1_MASK);
1354 bool const control = (state & GDK_CONTROL_MASK);
1355 bool const shift = (state & GDK_SHIFT_MASK);
1357 if (alt) {
1359 /* Alt pressed means keep offset: snap the moved distance to the grid.
1360 ** FIXME: this will snap to more than just the grid, nowadays.
1361 */
1363 m.freeSnapReturnByRef(SnapPreferences::SNAPPOINT_NODE, dxy);
1365 } else if (!shift) {
1367 /* We're snapping to things, possibly with a constraint to horizontal or
1368 ** vertical movement. Obtain a list of possible translations and then
1369 ** pick the smallest.
1370 */
1372 /* This will be our list of possible translations */
1373 std::list<Inkscape::SnappedPoint> s;
1375 if (control) {
1377 /* Snap to things, and also constrain to horizontal or vertical movement */
1379 for (unsigned int dim = 0; dim < 2; dim++) {
1380 // When doing a constrained translation, all points will move in the same direction, i.e.
1381 // either horizontally or vertically. Therefore we only have to specify the direction of
1382 // the constraint-line once. The constraint lines are parallel, but might not be colinear.
1383 // Therefore we will have to set the point through which the constraint-line runs
1384 // individually for each point to be snapped; this will be handled however by _snapTransformed()
1385 s.push_back(m.constrainedSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_BBOX,
1386 _bbox_points,
1387 _point,
1388 Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1389 dxy));
1391 s.push_back(m.constrainedSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_NODE,
1392 _snap_points,
1393 _point,
1394 Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1395 dxy));
1396 }
1398 } else {
1400 // Let's leave this timer code here for a while. I'll probably need it in the near future (Diederik van Lierop)
1401 /* GTimeVal starttime;
1402 GTimeVal endtime;
1403 g_get_current_time(&starttime); */
1405 /* Snap to things with no constraint */
1406 s.push_back(m.freeSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, dxy));
1407 s.push_back(m.freeSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, dxy));
1409 /*g_get_current_time(&endtime);
1410 double elapsed = ((((double)endtime.tv_sec - starttime.tv_sec) * G_USEC_PER_SEC + (endtime.tv_usec - starttime.tv_usec))) / 1000.0;
1411 std::cout << "Time spent snapping: " << elapsed << std::endl; */
1412 }
1414 /* Pick one */
1415 Inkscape::SnappedPoint best_snapped_point;
1416 g_assert(best_snapped_point.getDistance() == NR_HUGE);
1417 for (std::list<Inkscape::SnappedPoint>::const_iterator i = s.begin(); i != s.end(); i++) {
1418 if (i->getSnapped()) {
1419 if (i->getDistance() < best_snapped_point.getDistance()) {
1420 best_snapped_point = *i;
1421 dxy = i->getTransformation();
1422 }
1423 }
1424 }
1425 if (best_snapped_point.getSnapped()) {
1426 _desktop->snapindicator->set_new_snappoint(best_snapped_point);
1427 } else {
1428 // We didn't snap, so remove any previous snap indicator
1429 _desktop->snapindicator->remove_snappoint();
1430 if (control) {
1431 // If we didn't snap, then we should still constrain horizontally or vertically
1432 // (When we did snap, then this constraint has already been enforced by
1433 // calling constrainedSnapTranslation() above)
1434 if (fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y])) {
1435 dxy[Geom::Y] = 0;
1436 } else {
1437 dxy[Geom::X] = 0;
1438 }
1439 }
1440 }
1441 }
1443 Geom::Matrix const move((Geom::Translate(dxy)));
1444 Geom::Point const norm(0, 0);
1445 transform(move, norm);
1447 // status text
1448 GString *xs = SP_PX_TO_METRIC_STRING(dxy[Geom::X], _desktop->namedview->getDefaultMetric());
1449 GString *ys = SP_PX_TO_METRIC_STRING(dxy[Geom::Y], _desktop->namedview->getDefaultMetric());
1450 _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);
1451 g_string_free(xs, TRUE);
1452 g_string_free(ys, TRUE);
1453 }
1455 // Given a location of a handle at the visual bounding box, find the corresponding location at the
1456 // geometrical bounding box
1457 Geom::Point Inkscape::SelTrans::_getGeomHandlePos(Geom::Point const &visual_handle_pos)
1458 {
1459 if ( _snap_bbox_type == SPItem::GEOMETRIC_BBOX) {
1460 // When the selector tool is using geometric bboxes, then the handle is already
1461 // located at one of the geometric bbox corners
1462 return visual_handle_pos;
1463 }
1465 if (!_geometric_bbox) {
1466 //_getGeomHandlePos() can only be used after _geometric_bbox has been defined!
1467 return visual_handle_pos;
1468 }
1470 // Using the Geom::Rect constructor below ensures that "min() < max()", which is important
1471 // because this will also hold for _bbox, and which is required for get_scale_transform_with_stroke()
1472 Geom::Rect new_bbox = Geom::Rect(_origin_for_bboxpoints, visual_handle_pos); // new visual bounding box
1473 // Please note that the new_bbox might in fact be just a single line, for example when stretching (in
1474 // which case the handle and origin will be aligned vertically or horizontally)
1475 Geom::Point normalized_handle_pos = (visual_handle_pos - new_bbox.min()) * Geom::Scale(new_bbox.dimensions()).inverse();
1477 // Calculate the absolute affine while taking into account the scaling of the stroke width
1478 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1479 bool transform_stroke = prefs->getBool("/options/transform/stroke", true);
1480 Geom::Matrix abs_affine = get_scale_transform_with_stroke (*_bbox, _strokewidth, transform_stroke,
1481 new_bbox.min()[Geom::X], new_bbox.min()[Geom::Y], new_bbox.max()[Geom::X], new_bbox.max()[Geom::Y]);
1483 // Calculate the scaled geometrical bbox
1484 Geom::Rect new_geom_bbox = Geom::Rect(_geometric_bbox->min() * abs_affine, _geometric_bbox->max() * abs_affine);
1485 // Find the location of the handle on this new geometrical bbox
1486 return normalized_handle_pos * Geom::Scale(new_geom_bbox.dimensions()) + new_geom_bbox.min(); //new position of the geometric handle
1487 }
1489 Geom::Scale Inkscape::calcScaleFactors(Geom::Point const &initial_point, Geom::Point const &new_point, Geom::Point const &origin, bool const skew)
1490 {
1491 // Work out the new scale factors for the bbox
1493 Geom::Point const initial_delta = initial_point - origin;
1494 Geom::Point const new_delta = new_point - origin;
1495 Geom::Point const offset = new_point - initial_point;
1496 Geom::Scale scale(1, 1);
1498 for ( unsigned int i = 0 ; i < 2 ; i++ ) {
1499 if ( fabs(initial_delta[i]) > 1e-6 ) {
1500 if (skew) {
1501 scale[i] = offset[1-i] / initial_delta[i];
1502 } else {
1503 scale[i] = new_delta[i] / initial_delta[i];
1504 }
1505 }
1506 }
1508 return scale;
1509 }
1511 // Only for scaling/stretching
1512 Geom::Point Inkscape::SelTrans::_calcAbsAffineDefault(Geom::Scale const default_scale)
1513 {
1514 Geom::Matrix abs_affine = Geom::Translate(-_origin) * Geom::Matrix(default_scale) * Geom::Translate(_origin);
1515 Geom::Point new_bbox_min = _approximate_bbox->min() * abs_affine;
1516 Geom::Point new_bbox_max = _approximate_bbox->max() * abs_affine;
1518 bool transform_stroke = false;
1519 gdouble strokewidth = 0;
1521 if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
1522 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1523 transform_stroke = prefs->getBool("/options/transform/stroke", true);
1524 strokewidth = _strokewidth;
1525 }
1527 _absolute_affine = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
1528 new_bbox_min[Geom::X], new_bbox_min[Geom::Y], new_bbox_max[Geom::X], new_bbox_max[Geom::Y]);
1530 // return the new handle position
1531 return ( _point - _origin ) * default_scale + _origin;
1532 }
1534 // Only for scaling/stretching
1535 Geom::Point Inkscape::SelTrans::_calcAbsAffineGeom(Geom::Scale const geom_scale)
1536 {
1537 _relative_affine = Geom::Matrix(geom_scale);
1538 _absolute_affine = Geom::Translate(-_origin_for_specpoints) * _relative_affine * Geom::Translate(_origin_for_specpoints);
1540 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1541 bool const transform_stroke = prefs->getBool("/options/transform/stroke", true);
1542 Geom::Rect visual_bbox = get_visual_bbox(_geometric_bbox, _absolute_affine, _strokewidth, transform_stroke);
1544 // return the new handle position
1545 return visual_bbox.min() + visual_bbox.dimensions() * Geom::Scale(_handle_x, _handle_y);
1546 }
1548 /*
1549 Local Variables:
1550 mode:c++
1551 c-file-style:"stroustrup"
1552 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1553 indent-tabs-mode:nil
1554 fill-column:99
1555 End:
1556 */
1557 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :