1 #define __SELTRANS_C__
3 /*
4 * Helper object for transforming selected items
5 *
6 * Authors:
7 * Lauris Kaplinski <lauris@kaplinski.com>
8 * bulia byak <buliabyak@users.sf.net>
9 * Carl Hetherington <inkscape@carlh.net>
10 * Diederik van Lierop <mail@diedenrezi.nl>
11 *
12 * Copyright (C) 1999-2002 Lauris Kaplinski
13 * Copyright (C) 1999-2008 Authors
14 *
15 * Released under GNU GPL, read the file 'COPYING' for more information
16 */
18 #ifdef HAVE_CONFIG_H
19 # include <config.h>
20 #endif
21 #include <cstring>
22 #include <string>
24 #include <libnr/nr-matrix-ops.h>
25 #include <libnr/nr-matrix-translate-ops.h>
26 #include <libnr/nr-rotate-ops.h>
27 #include <libnr/nr-scale-ops.h>
28 #include <libnr/nr-translate-matrix-ops.h>
29 #include <libnr/nr-translate-ops.h>
30 #include <gdk/gdkkeysyms.h>
31 #include "document.h"
32 #include "sp-namedview.h"
33 #include "desktop.h"
34 #include "desktop-handles.h"
35 #include "desktop-style.h"
36 #include "knot.h"
37 #include "snap.h"
38 #include "selection.h"
39 #include "select-context.h"
40 #include "sp-item.h"
41 #include "sp-item-transform.h"
42 #include "seltrans-handles.h"
43 #include "seltrans.h"
44 #include "selection-chemistry.h"
45 #include "sp-metrics.h"
46 #include "verbs.h"
47 #include <glibmm/i18n.h>
48 #include "display/sp-ctrlline.h"
49 #include "prefs-utils.h"
50 #include "xml/repr.h"
51 #include "mod360.h"
52 #include "2geom/angle.h"
53 #include "display/snap-indicator.h"
55 #include "isnan.h" //temp fix. make sure included last
57 static void sp_remove_handles(SPKnot *knot[], gint num);
59 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data);
60 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint state, gpointer data);
61 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data);
62 static void sp_sel_trans_handle_new_event(SPKnot *knot, NR::Point *position, guint32 state, gpointer data);
63 static gboolean sp_sel_trans_handle_request(SPKnot *knot, NR::Point *p, guint state, gboolean *data);
65 extern GdkPixbuf *handles[];
67 static gboolean sp_seltrans_handle_event(SPKnot *knot, GdkEvent *event, gpointer)
68 {
69 switch (event->type) {
70 case GDK_MOTION_NOTIFY:
71 break;
72 case GDK_KEY_PRESS:
73 if (get_group0_keyval (&event->key) == GDK_space) {
74 /* stamping mode: both mode(show content and outline) operation with knot */
75 if (!SP_KNOT_IS_GRABBED(knot)) {
76 return FALSE;
77 }
78 SPDesktop *desktop = knot->desktop;
79 Inkscape::SelTrans *seltrans = SP_SELECT_CONTEXT(desktop->event_context)->_seltrans;
80 seltrans->stamp();
81 return TRUE;
82 }
83 break;
84 default:
85 break;
86 }
88 return FALSE;
89 }
91 Inkscape::SelTrans::SelTrans(SPDesktop *desktop) :
92 _desktop(desktop),
93 _selcue(desktop),
94 _state(STATE_SCALE),
95 _show(SHOW_CONTENT),
96 _grabbed(false),
97 _show_handles(true),
98 _bbox(NR::Nothing()),
99 _approximate_bbox(NR::Nothing()),
100 _absolute_affine(NR::scale(1,1)),
101 _opposite(NR::Point(0,0)),
102 _opposite_for_specpoints(NR::Point(0,0)),
103 _opposite_for_bboxpoints(NR::Point(0,0)),
104 _origin_for_specpoints(NR::Point(0,0)),
105 _origin_for_bboxpoints(NR::Point(0,0)),
106 _chandle(NULL),
107 _stamp_cache(NULL),
108 _message_context(desktop->messageStack())
109 {
110 gchar const *prefs_bbox = prefs_get_string_attribute("tools", "bounding_box");
111 _snap_bbox_type = (prefs_bbox != NULL && strcmp(prefs_bbox, "geometric")==0)? SPItem::GEOMETRIC_BBOX : SPItem::APPROXIMATE_BBOX;
113 g_return_if_fail(desktop != NULL);
115 for (int i = 0; i < 8; i++) {
116 _shandle[i] = NULL;
117 _rhandle[i] = NULL;
118 }
120 _updateVolatileState();
121 _current_relative_affine.set_identity();
123 _center_is_set = false; // reread _center from items, or set to bbox midpoint
125 _updateHandles();
127 _selection = sp_desktop_selection(desktop);
129 _norm = sp_canvas_item_new(sp_desktop_controls(desktop),
130 SP_TYPE_CTRL,
131 "anchor", GTK_ANCHOR_CENTER,
132 "mode", SP_CTRL_MODE_COLOR,
133 "shape", SP_CTRL_SHAPE_BITMAP,
134 "size", 13.0,
135 "filled", TRUE,
136 "fill_color", 0x00000000,
137 "stroked", TRUE,
138 "stroke_color", 0x000000a0,
139 "pixbuf", handles[12],
140 NULL);
142 _grip = sp_canvas_item_new(sp_desktop_controls(desktop),
143 SP_TYPE_CTRL,
144 "anchor", GTK_ANCHOR_CENTER,
145 "mode", SP_CTRL_MODE_XOR,
146 "shape", SP_CTRL_SHAPE_CROSS,
147 "size", 7.0,
148 "filled", TRUE,
149 "fill_color", 0xffffff7f,
150 "stroked", TRUE,
151 "stroke_color", 0xffffffff,
152 "pixbuf", handles[12],
153 NULL);
155 sp_canvas_item_hide(_grip);
156 sp_canvas_item_hide(_norm);
158 for (int i = 0; i < 4; i++) {
159 _l[i] = sp_canvas_item_new(sp_desktop_controls(desktop), SP_TYPE_CTRLLINE, NULL);
160 sp_canvas_item_hide(_l[i]);
161 }
163 _sel_changed_connection = _selection->connectChanged(
164 sigc::mem_fun(*this, &Inkscape::SelTrans::_selChanged)
165 );
167 _sel_modified_connection = _selection->connectModified(
168 sigc::mem_fun(*this, &Inkscape::SelTrans::_selModified)
169 );
170 }
172 Inkscape::SelTrans::~SelTrans()
173 {
174 _sel_changed_connection.disconnect();
175 _sel_modified_connection.disconnect();
177 for (unsigned int i = 0; i < 8; i++) {
178 if (_shandle[i]) {
179 g_object_unref(G_OBJECT(_shandle[i]));
180 _shandle[i] = NULL;
181 }
182 if (_rhandle[i]) {
183 g_object_unref(G_OBJECT(_rhandle[i]));
184 _rhandle[i] = NULL;
185 }
186 }
187 if (_chandle) {
188 g_object_unref(G_OBJECT(_chandle));
189 _chandle = NULL;
190 }
192 if (_norm) {
193 gtk_object_destroy(GTK_OBJECT(_norm));
194 _norm = NULL;
195 }
196 if (_grip) {
197 gtk_object_destroy(GTK_OBJECT(_grip));
198 _grip = NULL;
199 }
200 for (int i = 0; i < 4; i++) {
201 if (_l[i]) {
202 gtk_object_destroy(GTK_OBJECT(_l[i]));
203 _l[i] = NULL;
204 }
205 }
207 for (unsigned i = 0; i < _items.size(); i++) {
208 sp_object_unref(SP_OBJECT(_items[i].first), NULL);
209 }
211 _items.clear();
212 _items_centers.clear();
213 }
215 void Inkscape::SelTrans::resetState()
216 {
217 _state = STATE_SCALE;
218 }
220 void Inkscape::SelTrans::increaseState()
221 {
222 if (_state == STATE_SCALE) {
223 _state = STATE_ROTATE;
224 } else {
225 _state = STATE_SCALE;
226 }
228 _center_is_set = true; // no need to reread center
230 _updateHandles();
231 }
233 void Inkscape::SelTrans::setCenter(NR::Point const &p)
234 {
235 _center = p;
236 _center_is_set = true;
238 // Write the new center position into all selected items
239 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
240 SPItem *it = (SPItem*)SP_OBJECT(l->data);
241 it->setCenter(p);
242 // only set the value; updating repr and document_done will be done once, on ungrab
243 }
245 _updateHandles();
246 }
248 void Inkscape::SelTrans::grab(NR::Point const &p, gdouble x, gdouble y, bool show_handles)
249 {
250 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
252 g_return_if_fail(!_grabbed);
254 _grabbed = true;
255 _show_handles = show_handles;
256 _updateVolatileState();
257 _current_relative_affine.set_identity();
259 _changed = false;
261 if (_empty) {
262 return;
263 }
265 for (GSList const *l = selection->itemList(); l; l = l->next) {
266 SPItem *it = (SPItem*)sp_object_ref(SP_OBJECT(l->data), NULL);
267 _items.push_back(std::pair<SPItem *, NR::Matrix>(it, sp_item_i2d_affine(it)));
268 _items_centers.push_back(std::pair<SPItem *, NR::Point>(it, it->getCenter())); // for content-dragging, we need to remember original centers
269 }
271 _handle_x = x;
272 _handle_y = y;
274 // The selector tool should snap the bbox, special snappoints, and path nodes
275 // (The special points are the handles, center, rotation axis, font baseline, ends of spiral, etc.)
277 // First, determine the bounding box for snapping ...
278 _bbox = selection->bounds(_snap_bbox_type);
279 _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX); // Used for correctly scaling the strokewidth
280 _geometric_bbox = selection->bounds(SPItem::GEOMETRIC_BBOX);
281 _point = p;
282 if (_geometric_bbox) {
283 _point_geom = _geometric_bbox->min() + _geometric_bbox->dimensions() * NR::scale(x, y);
284 } else {
285 _point_geom = p;
286 }
288 // Next, get all points to consider for snapping
289 SnapManager const &m = _desktop->namedview->snap_manager;
290 _snap_points = selection->getSnapPoints(m.getIncludeItemCenter());
291 std::vector<NR::Point> snap_points_hull = selection->getSnapPointsConvexHull();
292 if (_snap_points.size() > 100) {
293 /* Snapping a huge number of nodes will take way too long, so limit the number of snappable nodes
294 An average user would rarely ever try to snap such a large number of nodes anyway, because
295 (s)he could hardly discern which node would be snapping */
296 _snap_points = snap_points_hull;
297 // Unfortunately, by now we will have lost the font-baseline snappoints :-(
298 }
300 // Find bbox hulling all special points, which excludes stroke width. Here we need to include the
301 // path nodes, for example because a rectangle which has been converted to a path doesn't have
302 // any other special points
303 NR::Rect snap_points_bbox;
304 if ( snap_points_hull.empty() == false ) {
305 std::vector<NR::Point>::iterator i = snap_points_hull.begin();
306 snap_points_bbox = NR::Rect(*i, *i);
307 i++;
308 while (i != snap_points_hull.end()) {
309 snap_points_bbox.expandTo(*i);
310 i++;
311 }
312 }
314 _bbox_points.clear();
315 if (_bbox) {
316 // ... and add the bbox corners to _bbox_points
317 for ( unsigned i = 0 ; i < 4 ; i++ ) {
318 _bbox_points.push_back(_bbox->corner(i));
319 }
320 // There are two separate "opposites" (i.e. opposite w.r.t. the handle being dragged):
321 // - one for snapping the boundingbox, which can be either visual or geometric
322 // - one for snapping the special points
323 // The "opposite" in case of a geometric boundingbox always coincides with the "opposite" for the special points
324 // These distinct "opposites" are needed in the snapmanager to avoid bugs such as #sf1540195 (in which
325 // a box is caught between two guides)
326 _opposite_for_bboxpoints = _bbox->min() + _bbox->dimensions() * NR::scale(1-x, 1-y);
327 _opposite_for_specpoints = snap_points_bbox.min() + snap_points_bbox.dimensions() * NR::scale(1-x, 1-y);
328 _opposite = _opposite_for_bboxpoints;
329 }
331 // The lines below are usefull for debugging any snapping issues, as they'll spit out all points that are considered for snapping
333 /*std::cout << "Number of snap points: " << _snap_points.size() << std::endl;
334 for (std::vector<NR::Point>::const_iterator i = _snap_points.begin(); i != _snap_points.end(); i++)
335 {
336 std::cout << " " << *i << std::endl;
337 }
339 std::cout << "Number of bbox points: " << _bbox_points.size() << std::endl;
340 for (std::vector<NR::Point>::const_iterator i = _bbox_points.begin(); i != _bbox_points.end(); i++)
341 {
342 std::cout << " " << *i << std::endl;
343 }*/
345 if ((x != -1) && (y != -1)) {
346 sp_canvas_item_show(_norm);
347 sp_canvas_item_show(_grip);
348 }
350 if (_show == SHOW_OUTLINE) {
351 for (int i = 0; i < 4; i++)
352 sp_canvas_item_show(_l[i]);
353 }
355 _updateHandles();
356 g_return_if_fail(_stamp_cache == NULL);
357 }
359 void Inkscape::SelTrans::transform(NR::Matrix const &rel_affine, NR::Point const &norm)
360 {
361 g_return_if_fail(_grabbed);
362 g_return_if_fail(!_empty);
364 NR::Matrix const affine( NR::translate(-norm) * rel_affine * NR::translate(norm) );
366 if (_show == SHOW_CONTENT) {
367 // update the content
368 for (unsigned i = 0; i < _items.size(); i++) {
369 SPItem &item = *_items[i].first;
370 NR::Matrix const &prev_transform = _items[i].second;
371 sp_item_set_i2d_affine(&item, prev_transform * affine);
372 }
373 } else {
374 if (_bbox) {
375 NR::Point p[4];
376 /* update the outline */
377 for (unsigned i = 0 ; i < 4 ; i++) {
378 p[i] = _bbox->corner(i) * affine;
379 }
380 for (unsigned i = 0 ; i < 4 ; i++) {
381 sp_ctrlline_set_coords(SP_CTRLLINE(_l[i]), p[i], p[(i+1)%4]);
382 }
383 }
384 }
386 _current_relative_affine = affine;
387 _changed = true;
388 _updateHandles();
389 }
391 void Inkscape::SelTrans::ungrab()
392 {
393 g_return_if_fail(_grabbed);
394 _grabbed = false;
395 _show_handles = true;
397 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
398 _updateVolatileState();
400 for (unsigned i = 0; i < _items.size(); i++) {
401 sp_object_unref(SP_OBJECT(_items[i].first), NULL);
402 }
404 sp_canvas_item_hide(_norm);
405 sp_canvas_item_hide(_grip);
407 if (_show == SHOW_OUTLINE) {
408 for (int i = 0; i < 4; i++)
409 sp_canvas_item_hide(_l[i]);
410 }
412 if (_stamp_cache) {
413 g_slist_free(_stamp_cache);
414 _stamp_cache = NULL;
415 }
417 _message_context.clear();
419 if (!_empty && _changed) {
420 sp_selection_apply_affine(selection, _current_relative_affine, (_show == SHOW_OUTLINE)? true : false);
421 if (_center) {
422 *_center *= _current_relative_affine;
423 _center_is_set = true;
424 }
426 // If dragging showed content live, sp_selection_apply_affine cannot change the centers
427 // appropriately - it does not know the original positions of the centers (all objects already have
428 // the new bboxes). So we need to reset the centers from our saved array.
429 if (_show != SHOW_OUTLINE && !_current_relative_affine.is_translation()) {
430 for (unsigned i = 0; i < _items_centers.size(); i++) {
431 SPItem *currentItem = _items_centers[i].first;
432 if (currentItem->isCenterSet()) { // only if it's already set
433 currentItem->setCenter (_items_centers[i].second * _current_relative_affine);
434 SP_OBJECT(currentItem)->updateRepr();
435 }
436 }
437 }
439 _items.clear();
440 _items_centers.clear();
442 if (_current_relative_affine.is_translation()) {
443 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
444 _("Move"));
445 } else if (_current_relative_affine.is_scale()) {
446 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
447 _("Scale"));
448 } else if (_current_relative_affine.is_rotation()) {
449 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
450 _("Rotate"));
451 } else {
452 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
453 _("Skew"));
454 }
456 } else {
458 if (_center_is_set) {
459 // we were dragging center; update reprs and commit undoable action
460 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
461 SPItem *it = (SPItem*)SP_OBJECT(l->data);
462 SP_OBJECT(it)->updateRepr();
463 }
464 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
465 _("Set center"));
466 }
468 _items.clear();
469 _items_centers.clear();
470 _updateHandles();
471 }
472 }
474 /* fixme: This is really bad, as we compare positions for each stamp (Lauris) */
475 /* fixme: IMHO the best way to keep sort cache would be to implement timestamping at last */
477 void Inkscape::SelTrans::stamp()
478 {
479 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
481 bool fixup = !_grabbed;
482 if ( fixup && _stamp_cache ) {
483 // TODO - give a proper fix. Simple temproary work-around for the grab() issue
484 g_slist_free(_stamp_cache);
485 _stamp_cache = NULL;
486 }
488 /* stamping mode */
489 if (!_empty) {
490 GSList *l;
491 if (_stamp_cache) {
492 l = _stamp_cache;
493 } else {
494 /* Build cache */
495 l = g_slist_copy((GSList *) selection->itemList());
496 l = g_slist_sort(l, (GCompareFunc) sp_object_compare_position);
497 _stamp_cache = l;
498 }
500 while (l) {
501 SPItem *original_item = SP_ITEM(l->data);
502 Inkscape::XML::Node *original_repr = SP_OBJECT_REPR(original_item);
504 // remember the position of the item
505 gint pos = original_repr->position();
506 // remember parent
507 Inkscape::XML::Node *parent = sp_repr_parent(original_repr);
509 Inkscape::XML::Node *copy_repr = original_repr->duplicate(parent->document());
511 // add the new repr to the parent
512 parent->appendChild(copy_repr);
513 // move to the saved position
514 copy_repr->setPosition(pos > 0 ? pos : 0);
516 SPItem *copy_item = (SPItem *) sp_desktop_document(_desktop)->getObjectByRepr(copy_repr);
518 NR::Matrix const *new_affine;
519 if (_show == SHOW_OUTLINE) {
520 NR::Matrix const i2d(sp_item_i2d_affine(original_item));
521 NR::Matrix const i2dnew( i2d * _current_relative_affine );
522 sp_item_set_i2d_affine(copy_item, i2dnew);
523 new_affine = ©_item->transform;
524 } else {
525 new_affine = &original_item->transform;
526 }
528 sp_item_write_transform(copy_item, copy_repr, *new_affine);
530 if ( copy_item->isCenterSet() && _center ) {
531 copy_item->setCenter(*_center * _current_relative_affine);
532 }
534 Inkscape::GC::release(copy_repr);
535 l = l->next;
536 }
537 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
538 _("Stamp"));
539 }
541 if ( fixup && _stamp_cache ) {
542 // TODO - give a proper fix. Simple temproary work-around for the grab() issue
543 g_slist_free(_stamp_cache);
544 _stamp_cache = NULL;
545 }
546 }
548 void Inkscape::SelTrans::_updateHandles()
549 {
550 if ( !_show_handles || _empty )
551 {
552 sp_remove_handles(_shandle, 8);
553 sp_remove_handles(_rhandle, 8);
554 sp_remove_handles(&_chandle, 1);
555 return;
556 }
558 // center handle
559 if ( _chandle == NULL ) {
560 _chandle = sp_knot_new(_desktop, _("<b>Center</b> of rotation and skewing: drag to reposition; scaling with Shift also uses this center"));
562 _chandle->setShape (SP_CTRL_SHAPE_BITMAP);
563 _chandle->setSize (13);
564 _chandle->setAnchor (handle_center.anchor);
565 _chandle->setMode (SP_CTRL_MODE_XOR);
566 _chandle->setFill(0x00000000, 0x00000000, 0x00000000);
567 _chandle->setStroke(0x000000ff, 0xff0000b0, 0xff0000b0);
568 _chandle->setPixbuf(handles[handle_center.control]);
569 sp_knot_update_ctrl(_chandle);
571 g_signal_connect(G_OBJECT(_chandle), "request",
572 G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle_center);
573 g_signal_connect(G_OBJECT(_chandle), "moved",
574 G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle_center);
575 g_signal_connect(G_OBJECT(_chandle), "grabbed",
576 G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle_center);
577 g_signal_connect(G_OBJECT(_chandle), "ungrabbed",
578 G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle_center);
579 g_signal_connect(G_OBJECT(_chandle), "clicked",
580 G_CALLBACK(sp_sel_trans_handle_click), (gpointer) &handle_center);
581 }
583 sp_remove_handles(&_chandle, 1);
584 if ( _state == STATE_SCALE ) {
585 sp_remove_handles(_rhandle, 8);
586 _showHandles(_shandle, handles_scale, 8,
587 _("<b>Squeeze or stretch</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"),
588 _("<b>Scale</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"));
589 } else {
590 sp_remove_handles(_shandle, 8);
591 _showHandles(_rhandle, handles_rotate, 8,
592 _("<b>Skew</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to skew around the opposite side"),
593 _("<b>Rotate</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to rotate around the opposite corner"));
594 }
596 if (!_center_is_set) {
597 _center = _desktop->selection->center();
598 _center_is_set = true;
599 }
601 if ( _state == STATE_SCALE || !_center ) {
602 sp_knot_hide(_chandle);
603 } else {
604 sp_knot_show(_chandle);
605 sp_knot_moveto(_chandle, &*_center);
606 }
607 }
609 void Inkscape::SelTrans::_updateVolatileState()
610 {
611 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
612 _empty = selection->isEmpty();
614 if (_empty) {
615 return;
616 }
618 //Update the bboxes
619 _bbox = selection->bounds(_snap_bbox_type);
620 _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX);
622 if (!_bbox) {
623 _empty = true;
624 return;
625 }
627 _strokewidth = stroke_average_width (selection->itemList());
628 }
630 static void sp_remove_handles(SPKnot *knot[], gint num)
631 {
632 for (int i = 0; i < num; i++) {
633 if (knot[i] != NULL) {
634 sp_knot_hide(knot[i]);
635 }
636 }
637 }
639 void Inkscape::SelTrans::_showHandles(SPKnot *knot[], SPSelTransHandle const handle[], gint num,
640 gchar const *even_tip, gchar const *odd_tip)
641 {
642 g_return_if_fail( !_empty );
644 for (int i = 0; i < num; i++) {
645 if (knot[i] == NULL) {
646 knot[i] = sp_knot_new(_desktop, i % 2 ? even_tip : odd_tip);
648 knot[i]->setShape (SP_CTRL_SHAPE_BITMAP);
649 knot[i]->setSize (13);
650 knot[i]->setAnchor (handle[i].anchor);
651 knot[i]->setMode (SP_CTRL_MODE_XOR);
652 knot[i]->setFill(0x000000ff, 0x00ff6600, 0x00ff6600); // inversion, green, green
653 knot[i]->setStroke(0x000000ff, 0x000000ff, 0x000000ff); // inversion
654 knot[i]->setPixbuf(handles[handle[i].control]);
655 sp_knot_update_ctrl(knot[i]);
657 g_signal_connect(G_OBJECT(knot[i]), "request",
658 G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle[i]);
659 g_signal_connect(G_OBJECT(knot[i]), "moved",
660 G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle[i]);
661 g_signal_connect(G_OBJECT(knot[i]), "grabbed",
662 G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle[i]);
663 g_signal_connect(G_OBJECT(knot[i]), "ungrabbed",
664 G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle[i]);
665 g_signal_connect(G_OBJECT(knot[i]), "event", G_CALLBACK(sp_seltrans_handle_event), (gpointer) &handle[i]);
666 }
667 sp_knot_show(knot[i]);
669 NR::Point const handle_pt(handle[i].x, handle[i].y);
670 // shouldn't have nullary bbox, but knots
671 g_assert(_bbox);
672 NR::Point p( _bbox->min()
673 + ( _bbox->dimensions()
674 * NR::scale(handle_pt) ) );
676 sp_knot_moveto(knot[i], &p);
677 }
678 }
680 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data)
681 {
682 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleGrab(
683 knot, state, *(SPSelTransHandle const *) data
684 );
685 }
687 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint /*state*/, gpointer /*data*/)
688 {
689 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->ungrab();
690 }
692 static void sp_sel_trans_handle_new_event(SPKnot *knot, NR::Point *position, guint state, gpointer data)
693 {
694 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleNewEvent(
695 knot, position, state, *(SPSelTransHandle const *) data
696 );
697 }
699 static gboolean sp_sel_trans_handle_request(SPKnot *knot, NR::Point *position, guint state, gboolean *data)
700 {
701 return SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleRequest(
702 knot, position, state, *(SPSelTransHandle const *) data
703 );
704 }
706 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data)
707 {
708 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleClick(
709 knot, state, *(SPSelTransHandle const *) data
710 );
711 }
713 void Inkscape::SelTrans::handleClick(SPKnot */*knot*/, guint state, SPSelTransHandle const &handle)
714 {
715 switch (handle.anchor) {
716 case GTK_ANCHOR_CENTER:
717 if (state & GDK_SHIFT_MASK) {
718 // Unset the center position for all selected items
719 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
720 SPItem *it = (SPItem*)(SP_OBJECT(l->data));
721 it->unsetCenter();
722 SP_OBJECT(it)->updateRepr();
723 _center_is_set = false; // center has changed
724 _updateHandles();
725 }
726 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
727 _("Reset center"));
728 }
729 break;
730 default:
731 break;
732 }
733 }
735 void Inkscape::SelTrans::handleGrab(SPKnot *knot, guint /*state*/, SPSelTransHandle const &handle)
736 {
737 switch (handle.anchor) {
738 case GTK_ANCHOR_CENTER:
739 g_object_set(G_OBJECT(_grip),
740 "shape", SP_CTRL_SHAPE_BITMAP,
741 "size", 13.0,
742 NULL);
743 sp_canvas_item_show(_grip);
744 break;
745 default:
746 g_object_set(G_OBJECT(_grip),
747 "shape", SP_CTRL_SHAPE_CROSS,
748 "size", 7.0,
749 NULL);
750 sp_canvas_item_show(_norm);
751 sp_canvas_item_show(_grip);
753 break;
754 }
756 grab(sp_knot_position(knot), handle.x, handle.y, FALSE);
757 }
760 void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, NR::Point *position, guint state, SPSelTransHandle const &handle)
761 {
762 if (!SP_KNOT_IS_GRABBED(knot)) {
763 return;
764 }
766 // in case items have been unhooked from the document, don't
767 // try to continue processing events for them.
768 for (unsigned int i = 0; i < _items.size(); i++) {
769 if (!SP_OBJECT_DOCUMENT(SP_OBJECT(_items[i].first)) ) {
770 return;
771 }
772 }
774 handle.action(this, handle, *position, state);
775 }
778 gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, NR::Point *position, guint state, SPSelTransHandle const &handle)
779 {
780 if (!SP_KNOT_IS_GRABBED(knot)) {
781 return TRUE;
782 }
784 knot->desktop->setPosition(*position);
786 // When holding shift while rotating or skewing, the transformation will be
787 // relative to the point opposite of the handle; otherwise it will be relative
788 // to the center as set for the selection
789 if ((!(state & GDK_SHIFT_MASK) == !(_state == STATE_ROTATE)) && (&handle != &handle_center)) {
790 _origin = _opposite;
791 _origin_for_bboxpoints = _opposite_for_bboxpoints;
792 _origin_for_specpoints = _opposite_for_specpoints;
793 } else if (_center) {
794 _origin = *_center;
795 _origin_for_bboxpoints = *_center;
796 _origin_for_specpoints = *_center;
797 } else {
798 // FIXME
799 return TRUE;
800 }
801 if (handle.request(this, handle, *position, state)) {
802 sp_knot_set_position(knot, position, state);
803 SP_CTRL(_grip)->moveto(*position);
804 SP_CTRL(_norm)->moveto(_origin);
805 }
807 return TRUE;
808 }
811 void Inkscape::SelTrans::_selChanged(Inkscape::Selection */*selection*/)
812 {
813 if (!_grabbed) {
814 // reread in case it changed on the fly:
815 gchar const *prefs_bbox = prefs_get_string_attribute("tools", "bounding_box");
816 _snap_bbox_type = (prefs_bbox != NULL && strcmp(prefs_bbox, "geometric")==0)? SPItem::GEOMETRIC_BBOX : SPItem::APPROXIMATE_BBOX;
817 //SPItem::APPROXIMATE_BBOX will be replaced by SPItem::VISUAL_BBOX, as soon as the latter is implemented properly
819 _updateVolatileState();
820 _current_relative_affine.set_identity();
821 _center_is_set = false; // center(s) may have changed
822 _updateHandles();
823 }
824 }
826 void Inkscape::SelTrans::_selModified(Inkscape::Selection */*selection*/, guint /*flags*/)
827 {
828 if (!_grabbed) {
829 _updateVolatileState();
830 _current_relative_affine.set_identity();
832 // reset internal flag
833 _changed = false;
835 _center_is_set = false; // center(s) may have changed
837 _updateHandles();
838 }
839 }
841 /*
842 * handlers for handle move-request
843 */
845 /** Returns -1 or 1 according to the sign of x. Returns 1 for 0 and NaN. */
846 static double sign(double const x)
847 {
848 return ( x < 0
849 ? -1
850 : 1 );
851 }
853 gboolean sp_sel_trans_scale_request(Inkscape::SelTrans *seltrans,
854 SPSelTransHandle const &, NR::Point &pt, guint state)
855 {
856 return seltrans->scaleRequest(pt, state);
857 }
859 gboolean sp_sel_trans_stretch_request(Inkscape::SelTrans *seltrans,
860 SPSelTransHandle const &handle, NR::Point &pt, guint state)
861 {
862 return seltrans->stretchRequest(handle, pt, state);
863 }
865 gboolean sp_sel_trans_skew_request(Inkscape::SelTrans *seltrans,
866 SPSelTransHandle const &handle, NR::Point &pt, guint state)
867 {
868 return seltrans->skewRequest(handle, pt, state);
869 }
871 gboolean sp_sel_trans_rotate_request(Inkscape::SelTrans *seltrans,
872 SPSelTransHandle const &, NR::Point &pt, guint state)
873 {
874 return seltrans->rotateRequest(pt, state);
875 }
877 gboolean sp_sel_trans_center_request(Inkscape::SelTrans *seltrans,
878 SPSelTransHandle const &, NR::Point &pt, guint state)
879 {
880 return seltrans->centerRequest(pt, state);
881 }
883 gboolean Inkscape::SelTrans::scaleRequest(NR::Point &pt, guint state)
884 {
886 // Calculate the scale factors, which can be either visual or geometric
887 // depending on which type of bbox is currently being used (see preferences -> selector tool)
888 NR::scale default_scale = calcScaleFactors(_point, pt, _origin);
890 // Find the scale factors for the geometric bbox
891 NR::Point pt_geom = _getGeomHandlePos(pt);
892 NR::scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
894 _absolute_affine = NR::identity(); //Initialize the scaler
896 if (state & GDK_MOD1_MASK) { // scale by an integer multiplier/divider
897 // We're scaling either the visual or the geometric bbox here (see the comment above)
898 for ( unsigned int i = 0 ; i < 2 ; i++ ) {
899 if (fabs(default_scale[i]) > 1) {
900 default_scale[i] = round(default_scale[i]);
901 } else if (default_scale[i] != 0) {
902 default_scale[i] = 1/round(1/(MIN(default_scale[i], 10)));
903 }
904 }
905 // Update the knot position
906 pt = _calcAbsAffineDefault(default_scale);
907 // When scaling by an integer, snapping is not needed
908 } else {
909 // In all other cases we should try to snap now
910 SnapManager const &m = _desktop->namedview->snap_manager;
912 /* Get a STL list of the selected items.
913 ** FIXME: this should probably be done by Inkscape::Selection.
914 */
915 std::list<SPItem const*> it;
916 for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
917 it.push_back(reinterpret_cast<SPItem*>(i->data));
918 }
920 Inkscape::SnappedPoint bb, sn;
921 NR::Coord bd(NR_HUGE);
922 NR::Coord sd(NR_HUGE);
924 if ((state & GDK_CONTROL_MASK) || _desktop->isToolboxButtonActive ("lock")) {
925 // Scale is locked to a 1:1 aspect ratio, so that s[X] must be made to equal s[Y].
926 //
927 // The aspect-ratio must be locked before snapping
928 if (fabs(default_scale[NR::X]) > fabs(default_scale[NR::Y])) {
929 default_scale[NR::X] = fabs(default_scale[NR::Y]) * sign(default_scale[NR::X]);
930 geom_scale[NR::X] = fabs(geom_scale[NR::Y]) * sign(geom_scale[NR::X]);
931 } else {
932 default_scale[NR::Y] = fabs(default_scale[NR::X]) * sign(default_scale[NR::Y]);
933 geom_scale[NR::Y] = fabs(geom_scale[NR::X]) * sign(geom_scale[NR::Y]);
934 }
936 // Snap along a suitable constraint vector from the origin.
937 bb = m.constrainedSnapScale(Snapper::SNAPPOINT_BBOX, _bbox_points, it, default_scale, _origin_for_bboxpoints);
938 sn = m.constrainedSnapScale(Snapper::SNAPPOINT_NODE, _snap_points, it, geom_scale, _origin_for_specpoints);
940 /* Choose the smaller difference in scale. Since s[X] == s[Y] we can
941 ** just compare difference in s[X].
942 */
943 bd = bb.getSnapped() ? fabs(bb.getTransformation()[NR::X] - default_scale[NR::X]) : NR_HUGE;
944 sd = sn.getSnapped() ? fabs(sn.getTransformation()[NR::X] - geom_scale[NR::X]) : NR_HUGE;
945 } else {
946 /* Scale aspect ratio is unlocked */
947 bb = m.freeSnapScale(Snapper::SNAPPOINT_BBOX, _bbox_points, it, default_scale, _origin_for_bboxpoints);
948 sn = m.freeSnapScale(Snapper::SNAPPOINT_NODE, _snap_points, it, geom_scale, _origin_for_specpoints);
950 /* Pick the snap that puts us closest to the original scale */
951 bd = bb.getSnapped() ? fabs(NR::L2(bb.getTransformation()) - NR::L2(default_scale.point())) : NR_HUGE;
952 sd = sn.getSnapped() ? fabs(NR::L2(sn.getTransformation()) - NR::L2(geom_scale.point())) : NR_HUGE;
953 }
955 if (!(bb.getSnapped() || sn.getSnapped())) {
956 // We didn't snap at all! Don't update the handle position, just calculate the new transformation
957 _calcAbsAffineDefault(default_scale);
958 } else if (bd < sd) {
959 // We snapped the bbox (which is either visual or geometric)
960 _desktop->snapindicator->set_new_snappoint(bb);
961 default_scale = NR::scale(bb.getTransformation());
962 // Calculate the new transformation and update the handle position
963 pt = _calcAbsAffineDefault(default_scale);
964 } else {
965 _desktop->snapindicator->set_new_snappoint(sn);
966 // We snapped the special points (e.g. nodes), which are not at the visual bbox
967 // The handle location however (pt) might however be at the visual bbox, so we
968 // will have to calculate pt taking the stroke width into account
969 geom_scale = NR::scale(sn.getTransformation());
970 pt = _calcAbsAffineGeom(geom_scale);
971 }
972 }
974 /* Status text */
975 _message_context.setF(Inkscape::NORMAL_MESSAGE,
976 _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
977 100 * _absolute_affine[0], 100 * _absolute_affine[3]);
979 return TRUE;
980 }
982 gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, NR::Point &pt, guint state)
983 {
984 NR::Dim2 axis, perp;
985 switch (handle.cursor) {
986 case GDK_TOP_SIDE:
987 case GDK_BOTTOM_SIDE:
988 axis = NR::Y;
989 perp = NR::X;
990 break;
991 case GDK_LEFT_SIDE:
992 case GDK_RIGHT_SIDE:
993 axis = NR::X;
994 perp = NR::Y;
995 break;
996 default:
997 g_assert_not_reached();
998 return TRUE;
999 };
1001 // Calculate the scale factors, which can be either visual or geometric
1002 // depending on which type of bbox is currently being used (see preferences -> selector tool)
1003 NR::scale default_scale = calcScaleFactors(_point, pt, _origin);
1004 default_scale[perp] = 1;
1006 // Find the scale factors for the geometric bbox
1007 NR::Point pt_geom = _getGeomHandlePos(pt);
1008 NR::scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
1009 geom_scale[perp] = 1;
1011 _absolute_affine = NR::identity(); //Initialize the scaler
1013 if (state & GDK_MOD1_MASK) { // stretch by an integer multiplier/divider
1014 if (fabs(default_scale[axis]) > 1) {
1015 default_scale[axis] = round(default_scale[axis]);
1016 } else if (default_scale[axis] != 0) {
1017 default_scale[axis] = 1/round(1/(MIN(default_scale[axis], 10)));
1018 }
1019 // Calculate the new transformation and update the handle position
1020 pt = _calcAbsAffineDefault(default_scale);
1021 // When stretching by an integer, snapping is not needed
1022 } else {
1023 // In all other cases we should try to snap now
1025 /* Get a STL list of the selected items.
1026 ** FIXME: this should probably be done by Inkscape::Selection.
1027 */
1028 std::list<SPItem const*> it;
1029 for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
1030 it.push_back(reinterpret_cast<SPItem*>(i->data));
1031 }
1033 SnapManager const &m = _desktop->namedview->snap_manager;
1035 Inkscape::SnappedPoint bb, sn;
1036 g_assert(bb.getSnapped() == false); // Check initialization to catch any regression
1037 NR::Coord bd(NR_HUGE);
1038 NR::Coord sd(NR_HUGE);
1040 bool symmetrical = state & GDK_CONTROL_MASK;
1042 bb = m.constrainedSnapStretch(Snapper::SNAPPOINT_BBOX, _bbox_points, it, default_scale[axis], _origin_for_bboxpoints, axis, symmetrical);
1043 sn = m.constrainedSnapStretch(Snapper::SNAPPOINT_NODE, _snap_points, it, geom_scale[axis], _origin_for_specpoints, axis, symmetrical);
1045 if (bb.getSnapped()) {
1046 // We snapped the bbox (which is either visual or geometric)
1047 bd = fabs(bb.getTransformation()[axis] - default_scale[axis]);
1048 default_scale[axis] = bb.getTransformation()[axis];
1049 }
1051 if (sn.getSnapped()) {
1052 sd = fabs(sn.getTransformation()[axis] - geom_scale[axis]);
1053 geom_scale[axis] = sn.getTransformation()[axis];
1054 }
1056 if (symmetrical) {
1057 // on ctrl, apply symmetrical scaling instead of stretching
1058 // Preserve aspect ratio, but never flip in the dimension not being edited (by using fabs())
1059 default_scale[perp] = fabs(default_scale[axis]);
1060 geom_scale[perp] = fabs(geom_scale[axis]);
1061 }
1063 if (!(bb.getSnapped() || sn.getSnapped())) {
1064 // We didn't snap at all! Don't update the handle position, just calculate the new transformation
1065 _calcAbsAffineDefault(default_scale);
1066 } else if (bd < sd) {
1067 _desktop->snapindicator->set_new_snappoint(bb);
1068 // Calculate the new transformation and update the handle position
1069 pt = _calcAbsAffineDefault(default_scale);
1070 } else {
1071 _desktop->snapindicator->set_new_snappoint(sn);
1072 // We snapped the special points (e.g. nodes), which are not at the visual bbox
1073 // The handle location however (pt) might however be at the visual bbox, so we
1074 // will have to calculate pt taking the stroke width into account
1075 pt = _calcAbsAffineGeom(geom_scale);
1076 }
1077 }
1079 // status text
1080 _message_context.setF(Inkscape::NORMAL_MESSAGE,
1081 _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1082 100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1084 return TRUE;
1085 }
1087 gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, NR::Point &pt, guint state)
1088 {
1089 /* When skewing (or rotating):
1090 * 1) the stroke width will not change. This makes life much easier because we don't have to
1091 * account for that (like for scaling or stretching). As a consequence, all points will
1092 * have the same origin for the transformation and for the snapping.
1093 * 2) When holding shift, the transformation will be relative to the point opposite of
1094 * the handle; otherwise it will be relative to the center as set for the selection
1095 */
1097 NR::Dim2 dim_a;
1098 NR::Dim2 dim_b;
1100 switch (handle.cursor) {
1101 case GDK_SB_H_DOUBLE_ARROW:
1102 dim_a = NR::Y;
1103 dim_b = NR::X;
1104 break;
1105 case GDK_SB_V_DOUBLE_ARROW:
1106 dim_a = NR::X;
1107 dim_b = NR::Y;
1108 break;
1109 default:
1110 g_assert_not_reached();
1111 abort();
1112 break;
1113 }
1115 NR::Point const initial_delta = _point - _origin;
1117 if (fabs(initial_delta[dim_a]) < 1e-15) {
1118 return false;
1119 }
1121 // Calculate the scale factors, which can be either visual or geometric
1122 // depending on which type of bbox is currently being used (see preferences -> selector tool)
1123 NR::scale scale = calcScaleFactors(_point, pt, _origin, false);
1124 NR::scale skew = calcScaleFactors(_point, pt, _origin, true);
1125 scale[dim_b] = 1;
1126 skew[dim_b] = 1;
1128 if (fabs(scale[dim_a]) < 1) {
1129 // Prevent shrinking of the selected object, while allowing mirroring
1130 scale[dim_a] = sign(scale[dim_a]);
1131 } else {
1132 // Allow expanding of the selected object by integer multiples
1133 scale[dim_a] = floor(scale[dim_a] + 0.5);
1134 }
1136 double radians = atan(skew[dim_a] / scale[dim_a]);
1138 if (state & GDK_CONTROL_MASK) {
1139 // Snap to defined angle increments
1140 int snaps = prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12);
1141 if (snaps) {
1142 double sections = floor(radians * snaps / M_PI + .5);
1143 if (fabs(sections) >= snaps / 2) {
1144 sections = sign(sections) * (snaps / 2 - 1);
1145 }
1146 radians = (M_PI / snaps) * sections;
1147 }
1148 skew[dim_a] = tan(radians) * scale[dim_a];
1149 } else {
1150 // Snap to objects, grids, guides
1152 /* Get a STL list of the selected items.
1153 ** FIXME: this should probably be done by Inkscape::Selection.
1154 */
1155 std::list<SPItem const*> it;
1156 for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
1157 it.push_back(reinterpret_cast<SPItem*>(i->data));
1158 }
1160 SnapManager const &m = _desktop->namedview->snap_manager;
1162 //TODO: While skewing, scaling in the opposite direction by integer multiples is also allowed. This is not handled though by freeSnapSkew / _snapTransformed yet!
1163 //TODO: We need a constrainedSnapSkew instead of a freeSnapSkew
1164 Inkscape::SnappedPoint bb = m.freeSnapSkew(Inkscape::Snapper::SNAPPOINT_BBOX, _bbox_points, it, skew[dim_a], _origin, dim_b);
1165 Inkscape::SnappedPoint sn = m.freeSnapSkew(Inkscape::Snapper::SNAPPOINT_NODE, _snap_points, it, skew[dim_a], _origin, dim_b);
1167 if (bb.getSnapped() || sn.getSnapped()) {
1168 // We snapped something, so change the skew to reflect it
1169 NR::Coord const bd = bb.getSnapped() ? bb.getTransformation()[dim_b] : NR_HUGE;
1170 NR::Coord const sd = sn.getSnapped() ? sn.getTransformation()[dim_b] : NR_HUGE;
1171 if (bd < sd) {
1172 _desktop->snapindicator->set_new_snappoint(bb);
1173 skew[dim_a] = bd;
1174 } else {
1175 _desktop->snapindicator->set_new_snappoint(sn);
1176 skew[dim_a] = sd;
1177 }
1178 }
1179 }
1181 // Update the handle position
1182 pt[dim_b] = initial_delta[dim_a] * skew[dim_a] + _point[dim_b];
1183 pt[dim_a] = initial_delta[dim_a] * scale[dim_a] + _origin[dim_a];
1185 // Calculate the relative affine
1186 _relative_affine = NR::identity();
1187 _relative_affine[2*dim_a + dim_a] = (pt[dim_a] - _origin[dim_a]) / initial_delta[dim_a];
1188 _relative_affine[2*dim_a + (dim_b)] = (pt[dim_b] - _point[dim_b]) / initial_delta[dim_a];
1189 _relative_affine[2*(dim_b) + (dim_a)] = 0;
1190 _relative_affine[2*(dim_b) + (dim_b)] = 1;
1192 for (int i = 0; i < 2; i++) {
1193 if (fabs(_relative_affine[3*i]) < 1e-15) {
1194 _relative_affine[3*i] = 1e-15;
1195 }
1196 }
1198 // Update the status text
1199 double degrees = mod360symm(Geom::rad_to_deg(radians));
1200 _message_context.setF(Inkscape::NORMAL_MESSAGE,
1201 // TRANSLATORS: don't modify the first ";"
1202 // (it will NOT be displayed as ";" - only the second one will be)
1203 _("<b>Skew</b>: %0.2f°; with <b>Ctrl</b> to snap angle"),
1204 degrees);
1206 return TRUE;
1207 }
1209 gboolean Inkscape::SelTrans::rotateRequest(NR::Point &pt, guint state)
1210 {
1211 /* When rotating (or skewing):
1212 * 1) the stroke width will not change. This makes life much easier because we don't have to
1213 * account for that (like for scaling or stretching). As a consequence, all points will
1214 * have the same origin for the transformation and for the snapping.
1215 * 2) When holding shift, the transformation will be relative to the point opposite of
1216 * the handle; otherwise it will be relative to the center as set for the selection
1217 */
1219 int snaps = prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12);
1221 // rotate affine in rotate
1222 NR::Point const d1 = _point - _origin;
1223 NR::Point const d2 = pt - _origin;
1225 NR::Coord const h1 = NR::L2(d1); // initial radius
1226 if (h1 < 1e-15) return FALSE;
1227 NR::Point q1 = d1 / h1; // normalized initial vector to handle
1228 NR::Coord const h2 = NR::L2(d2); // new radius
1229 if (fabs(h2) < 1e-15) return FALSE;
1230 NR::Point q2 = d2 / h2; // normalized new vector to handle
1232 double radians;
1233 if (state & GDK_CONTROL_MASK) {
1234 // Snap to defined angle increments
1235 double cos_t = NR::dot(q1, q2);
1236 double sin_t = NR::dot(NR::rot90(q1), q2);
1237 radians = atan2(sin_t, cos_t);
1238 if (snaps) {
1239 radians = ( M_PI / snaps ) * floor( radians * snaps / M_PI + .5 );
1240 }
1241 q1 = NR::Point(1, 0);
1242 q2 = NR::Point(cos(radians), sin(radians));
1243 } else {
1244 radians = atan2(NR::dot(NR::rot90(d1), d2),
1245 NR::dot(d1, d2));
1246 }
1248 NR::rotate const r1(q1);
1249 NR::rotate const r2(q2);
1251 // Calculate the relative affine
1252 _relative_affine = NR::Matrix(r2/r1);
1254 // Update the handle position
1255 pt = _point * NR::translate(-_origin) * _relative_affine * NR::translate(_origin);
1257 // Update the status text
1258 double degrees = mod360symm(Geom::rad_to_deg(radians));
1259 _message_context.setF(Inkscape::NORMAL_MESSAGE,
1260 // TRANSLATORS: don't modify the first ";"
1261 // (it will NOT be displayed as ";" - only the second one will be)
1262 _("<b>Rotate</b>: %0.2f°; with <b>Ctrl</b> to snap angle"), degrees);
1264 return TRUE;
1265 }
1267 gboolean Inkscape::SelTrans::centerRequest(NR::Point &pt, guint state)
1268 {
1269 SnapManager const &m = _desktop->namedview->snap_manager;
1270 pt = m.freeSnap(Snapper::SNAPPOINT_NODE, pt, NULL).getPoint();
1272 if (state & GDK_CONTROL_MASK) {
1273 if ( fabs(_point[NR::X] - pt[NR::X]) > fabs(_point[NR::Y] - pt[NR::Y]) ) {
1274 pt[NR::Y] = _point[NR::Y];
1275 } else {
1276 pt[NR::X] = _point[NR::X];
1277 }
1278 }
1280 if ( !(state & GDK_SHIFT_MASK) && _bbox ) {
1281 // screen pixels to snap center to bbox
1282 #define SNAP_DIST 5
1283 // FIXME: take from prefs
1284 double snap_dist = SNAP_DIST / _desktop->current_zoom();
1286 for (int i = 0; i < 2; i++) {
1287 if (fabs(pt[i] - _bbox->min()[i]) < snap_dist) {
1288 pt[i] = _bbox->min()[i];
1289 }
1290 if (fabs(pt[i] - _bbox->midpoint()[i]) < snap_dist) {
1291 pt[i] = _bbox->midpoint()[i];
1292 }
1293 if (fabs(pt[i] - _bbox->max()[i]) < snap_dist) {
1294 pt[i] = _bbox->max()[i];
1295 }
1296 }
1297 }
1299 // status text
1300 GString *xs = SP_PX_TO_METRIC_STRING(pt[NR::X], _desktop->namedview->getDefaultMetric());
1301 GString *ys = SP_PX_TO_METRIC_STRING(pt[NR::Y], _desktop->namedview->getDefaultMetric());
1302 _message_context.setF(Inkscape::NORMAL_MESSAGE, _("Move <b>center</b> to %s, %s"), xs->str, ys->str);
1303 g_string_free(xs, FALSE);
1304 g_string_free(ys, FALSE);
1306 return TRUE;
1307 }
1309 /*
1310 * handlers for handle movement
1311 *
1312 */
1314 void sp_sel_trans_stretch(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, NR::Point &pt, guint state)
1315 {
1316 seltrans->stretch(handle, pt, state);
1317 }
1319 void sp_sel_trans_scale(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
1320 {
1321 seltrans->scale(pt, state);
1322 }
1324 void sp_sel_trans_skew(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, NR::Point &pt, guint state)
1325 {
1326 seltrans->skew(handle, pt, state);
1327 }
1329 void sp_sel_trans_rotate(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
1330 {
1331 seltrans->rotate(pt, state);
1332 }
1334 void Inkscape::SelTrans::stretch(SPSelTransHandle const &handle, NR::Point &pt, guint state)
1335 {
1336 transform(_absolute_affine, NR::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1337 }
1339 void Inkscape::SelTrans::scale(NR::Point &pt, guint /*state*/)
1340 {
1341 transform(_absolute_affine, NR::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1342 }
1344 void Inkscape::SelTrans::skew(SPSelTransHandle const &handle, NR::Point &pt, guint /*state*/)
1345 {
1346 transform(_relative_affine, _origin);
1347 }
1349 void Inkscape::SelTrans::rotate(NR::Point &pt, guint /*state*/)
1350 {
1351 transform(_relative_affine, _origin);
1352 }
1354 void sp_sel_trans_center(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint /*state*/)
1355 {
1356 seltrans->setCenter(pt);
1357 }
1360 void Inkscape::SelTrans::moveTo(NR::Point const &xy, guint state)
1361 {
1362 SnapManager const &m = _desktop->namedview->snap_manager;
1364 /* The amount that we've moved by during this drag */
1365 NR::Point dxy = xy - _point;
1367 /* Get a STL list of the selected items.
1368 ** FIXME: this should probably be done by Inkscape::Selection.
1369 */
1370 std::list<SPItem const*> it;
1371 for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
1372 it.push_back(reinterpret_cast<SPItem*>(i->data));
1373 }
1375 bool const alt = (state & GDK_MOD1_MASK);
1376 bool const control = (state & GDK_CONTROL_MASK);
1377 bool const shift = (state & GDK_SHIFT_MASK);
1379 if (alt) {
1381 /* Alt pressed means keep offset: snap the moved distance to the grid.
1382 ** FIXME: this will snap to more than just the grid, nowadays.
1383 */
1385 dxy = m.freeSnap(Snapper::SNAPPOINT_NODE, dxy, NULL).getPoint();
1387 } else if (!shift) {
1389 /* We're snapping to things, possibly with a constraint to horizontal or
1390 ** vertical movement. Obtain a list of possible translations and then
1391 ** pick the smallest.
1392 */
1394 /* This will be our list of possible translations */
1395 std::list<Inkscape::SnappedPoint> s;
1397 if (control) {
1399 /* Snap to things, and also constrain to horizontal or vertical movement */
1401 for (unsigned int dim = 0; dim < 2; dim++) {
1402 s.push_back(m.constrainedSnapTranslation(Inkscape::Snapper::SNAPPOINT_BBOX,
1403 _bbox_points,
1404 it,
1405 Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1406 dxy));
1408 s.push_back(m.constrainedSnapTranslation(Inkscape::Snapper::SNAPPOINT_NODE,
1409 _snap_points,
1410 it,
1411 Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1412 dxy));
1413 }
1415 } else {
1417 // Let's leave this timer code here for a while. I'll probably need it in the near future (Diederik van Lierop)
1418 /* GTimeVal starttime;
1419 GTimeVal endtime;
1420 g_get_current_time(&starttime); */
1422 /* Snap to things with no constraint */
1423 s.push_back(m.freeSnapTranslation(Inkscape::Snapper::SNAPPOINT_BBOX,
1424 _bbox_points, it, dxy));
1425 s.push_back(m.freeSnapTranslation(Inkscape::Snapper::SNAPPOINT_NODE,
1426 _snap_points, it, dxy));
1428 /*g_get_current_time(&endtime);
1429 double elapsed = ((((double)endtime.tv_sec - starttime.tv_sec) * G_USEC_PER_SEC + (endtime.tv_usec - starttime.tv_usec))) / 1000.0;
1430 std::cout << "Time spent snapping: " << elapsed << std::endl; */
1431 }
1433 /* Pick one */
1434 Inkscape::SnappedPoint best_snapped_point;
1435 g_assert(best_snapped_point.getDistance() == NR_HUGE);
1436 for (std::list<Inkscape::SnappedPoint>::const_iterator i = s.begin(); i != s.end(); i++) {
1437 if (i->getSnapped()) {
1438 // std::cout << "moveTo() -> snapped to point: " << i->getPoint() << " with transformation: " << i->getTransformation();
1439 if (i->getDistance() < best_snapped_point.getDistance()) {
1440 best_snapped_point = *i;
1441 dxy = i->getTransformation();
1442 // std::cout << " SEL";
1443 }
1444 //std::cout << std::endl;
1445 }
1446 }
1447 if (best_snapped_point.getSnapped()) {
1448 _desktop->snapindicator->set_new_snappoint(best_snapped_point);
1449 }
1450 }
1452 if (control) {
1453 /* Ensure that the horizontal and vertical constraint has been applied */
1454 if (fabs(dxy[NR::X]) > fabs(dxy[NR::Y])) {
1455 dxy[NR::Y] = 0;
1456 } else {
1457 dxy[NR::X] = 0;
1458 }
1459 }
1461 NR::Matrix const move((NR::translate(dxy)));
1462 NR::Point const norm(0, 0);
1463 transform(move, norm);
1465 // status text
1466 GString *xs = SP_PX_TO_METRIC_STRING(dxy[NR::X], _desktop->namedview->getDefaultMetric());
1467 GString *ys = SP_PX_TO_METRIC_STRING(dxy[NR::Y], _desktop->namedview->getDefaultMetric());
1468 _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);
1469 g_string_free(xs, TRUE);
1470 g_string_free(ys, TRUE);
1471 }
1473 // Given a location of a handle at the visual bounding box, find the corresponding location at the
1474 // geometrical bounding box
1475 NR::Point Inkscape::SelTrans::_getGeomHandlePos(NR::Point const &visual_handle_pos)
1476 {
1477 if ( _snap_bbox_type == SPItem::GEOMETRIC_BBOX) {
1478 // When the selector tool is using geometric bboxes, then the handle is already
1479 // located at one of the geometric bbox corners
1480 return visual_handle_pos;
1481 }
1483 if (!_geometric_bbox) {
1484 //_getGeomHandlePos() can only be used after _geometric_bbox has been defined!
1485 return visual_handle_pos;
1486 }
1488 // Using the NR::Rect constructor below ensures that "min() < max()", which is important
1489 // because this will also hold for _bbox, and which is required for get_scale_transform_with_stroke()
1490 NR::Rect new_bbox = NR::Rect(_origin_for_bboxpoints, visual_handle_pos); // new visual bounding box
1491 // Please note that the new_bbox might in fact be just a single line, for example when stretching (in
1492 // which case the handle and origin will be aligned vertically or horizontally)
1493 NR::Point normalized_handle_pos = (visual_handle_pos - new_bbox.min()) * NR::scale(new_bbox.dimensions()).inverse();
1495 // Calculate the absolute affine while taking into account the scaling of the stroke width
1496 int transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1497 NR::Matrix abs_affine = get_scale_transform_with_stroke (*_bbox, _strokewidth, transform_stroke,
1498 new_bbox.min()[NR::X], new_bbox.min()[NR::Y], new_bbox.max()[NR::X], new_bbox.max()[NR::Y]);
1500 // Calculate the scaled geometrical bbox
1501 NR::Rect new_geom_bbox = NR::Rect(_geometric_bbox->min() * abs_affine, _geometric_bbox->max() * abs_affine);
1502 // Find the location of the handle on this new geometrical bbox
1503 return normalized_handle_pos * NR::scale(new_geom_bbox.dimensions()) + new_geom_bbox.min(); //new position of the geometric handle
1504 }
1506 NR::scale Inkscape::calcScaleFactors(NR::Point const &initial_point, NR::Point const &new_point, NR::Point const &origin, bool const skew)
1507 {
1508 // Work out the new scale factors for the bbox
1510 NR::Point const initial_delta = initial_point - origin;
1511 NR::Point const new_delta = new_point - origin;
1512 NR::Point const offset = new_point - initial_point;
1513 NR::scale scale(1, 1);
1515 for ( unsigned int i = 0 ; i < 2 ; i++ ) {
1516 if ( fabs(initial_delta[i]) > 1e-6 ) {
1517 if (skew) {
1518 scale[i] = offset[1-i] / initial_delta[i];
1519 } else {
1520 scale[i] = new_delta[i] / initial_delta[i];
1521 }
1522 }
1523 }
1525 return scale;
1526 }
1528 // Only for scaling/stretching
1529 NR::Point Inkscape::SelTrans::_calcAbsAffineDefault(NR::scale const default_scale)
1530 {
1531 NR::Matrix abs_affine = NR::translate(-_origin) * NR::Matrix(default_scale) * NR::translate(_origin);
1532 NR::Point new_bbox_min = _approximate_bbox->min() * abs_affine;
1533 NR::Point new_bbox_max = _approximate_bbox->max() * abs_affine;
1535 int transform_stroke = false;
1536 gdouble strokewidth = 0;
1538 if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
1539 transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1540 strokewidth = _strokewidth;
1541 }
1543 _absolute_affine = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
1544 new_bbox_min[NR::X], new_bbox_min[NR::Y], new_bbox_max[NR::X], new_bbox_max[NR::Y]);
1546 // return the new handle position
1547 return ( _point - _origin ) * default_scale + _origin;
1548 }
1550 // Only for scaling/stretching
1551 NR::Point Inkscape::SelTrans::_calcAbsAffineGeom(NR::scale const geom_scale)
1552 {
1553 _relative_affine = NR::Matrix(geom_scale);
1554 _absolute_affine = NR::translate(-_origin_for_specpoints) * _relative_affine * NR::translate(_origin_for_specpoints);
1556 bool const transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1557 NR::Rect visual_bbox = get_visual_bbox(_geometric_bbox, _absolute_affine, _strokewidth, transform_stroke);
1559 // return the new handle position
1560 return visual_bbox.min() + visual_bbox.dimensions() * NR::scale(_handle_x, _handle_y);
1561 }
1564 /*
1565 Local Variables:
1566 mode:c++
1567 c-file-style:"stroustrup"
1568 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1569 indent-tabs-mode:nil
1570 fill-column:99
1571 End:
1572 */
1573 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :