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"
54 #include "isnan.h" //temp fix. make sure included last
56 static void sp_remove_handles(SPKnot *knot[], gint num);
58 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data);
59 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint state, gpointer data);
60 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data);
61 static void sp_sel_trans_handle_new_event(SPKnot *knot, NR::Point *position, guint32 state, gpointer data);
62 static gboolean sp_sel_trans_handle_request(SPKnot *knot, NR::Point *p, guint state, gboolean *data);
64 extern GdkPixbuf *handles[];
66 static gboolean sp_seltrans_handle_event(SPKnot *knot, GdkEvent *event, gpointer)
67 {
68 switch (event->type) {
69 case GDK_MOTION_NOTIFY:
70 break;
71 case GDK_KEY_PRESS:
72 if (get_group0_keyval (&event->key) == GDK_space) {
73 /* stamping mode: both mode(show content and outline) operation with knot */
74 if (!SP_KNOT_IS_GRABBED(knot)) {
75 return FALSE;
76 }
77 SPDesktop *desktop = knot->desktop;
78 Inkscape::SelTrans *seltrans = SP_SELECT_CONTEXT(desktop->event_context)->_seltrans;
79 seltrans->stamp();
80 return TRUE;
81 }
82 break;
83 default:
84 break;
85 }
87 return FALSE;
88 }
90 Inkscape::SelTrans::SelTrans(SPDesktop *desktop) :
91 _desktop(desktop),
92 _selcue(desktop),
93 _state(STATE_SCALE),
94 _show(SHOW_CONTENT),
95 _grabbed(false),
96 _show_handles(true),
97 _bbox(NR::Nothing()),
98 _approximate_bbox(NR::Nothing()),
99 _absolute_affine(NR::scale(1,1)),
100 _opposite(NR::Point(0,0)),
101 _opposite_for_specpoints(NR::Point(0,0)),
102 _opposite_for_bboxpoints(NR::Point(0,0)),
103 _origin_for_specpoints(NR::Point(0,0)),
104 _origin_for_bboxpoints(NR::Point(0,0)),
105 _chandle(NULL),
106 _stamp_cache(NULL),
107 _message_context(desktop->messageStack())
108 {
109 gchar const *prefs_bbox = prefs_get_string_attribute("tools", "bounding_box");
110 _snap_bbox_type = (prefs_bbox != NULL && strcmp(prefs_bbox, "geometric")==0)? SPItem::GEOMETRIC_BBOX : SPItem::APPROXIMATE_BBOX;
112 g_return_if_fail(desktop != NULL);
114 for (int i = 0; i < 8; i++) {
115 _shandle[i] = NULL;
116 _rhandle[i] = NULL;
117 }
119 _updateVolatileState();
120 _current_relative_affine.set_identity();
122 _center_is_set = false; // reread _center from items, or set to bbox midpoint
124 _updateHandles();
126 _selection = sp_desktop_selection(desktop);
128 _norm = sp_canvas_item_new(sp_desktop_controls(desktop),
129 SP_TYPE_CTRL,
130 "anchor", GTK_ANCHOR_CENTER,
131 "mode", SP_CTRL_MODE_COLOR,
132 "shape", SP_CTRL_SHAPE_BITMAP,
133 "size", 13.0,
134 "filled", TRUE,
135 "fill_color", 0x00000000,
136 "stroked", TRUE,
137 "stroke_color", 0x000000a0,
138 "pixbuf", handles[12],
139 NULL);
141 _grip = sp_canvas_item_new(sp_desktop_controls(desktop),
142 SP_TYPE_CTRL,
143 "anchor", GTK_ANCHOR_CENTER,
144 "mode", SP_CTRL_MODE_XOR,
145 "shape", SP_CTRL_SHAPE_CROSS,
146 "size", 7.0,
147 "filled", TRUE,
148 "fill_color", 0xffffff7f,
149 "stroked", TRUE,
150 "stroke_color", 0xffffffff,
151 "pixbuf", handles[12],
152 NULL);
154 sp_canvas_item_hide(_grip);
155 sp_canvas_item_hide(_norm);
157 for (int i = 0; i < 4; i++) {
158 _l[i] = sp_canvas_item_new(sp_desktop_controls(desktop), SP_TYPE_CTRLLINE, NULL);
159 sp_canvas_item_hide(_l[i]);
160 }
162 _sel_changed_connection = _selection->connectChanged(
163 sigc::mem_fun(*this, &Inkscape::SelTrans::_selChanged)
164 );
166 _sel_modified_connection = _selection->connectModified(
167 sigc::mem_fun(*this, &Inkscape::SelTrans::_selModified)
168 );
169 }
171 Inkscape::SelTrans::~SelTrans()
172 {
173 _sel_changed_connection.disconnect();
174 _sel_modified_connection.disconnect();
176 for (unsigned int i = 0; i < 8; i++) {
177 if (_shandle[i]) {
178 g_object_unref(G_OBJECT(_shandle[i]));
179 _shandle[i] = NULL;
180 }
181 if (_rhandle[i]) {
182 g_object_unref(G_OBJECT(_rhandle[i]));
183 _rhandle[i] = NULL;
184 }
185 }
186 if (_chandle) {
187 g_object_unref(G_OBJECT(_chandle));
188 _chandle = NULL;
189 }
191 if (_norm) {
192 gtk_object_destroy(GTK_OBJECT(_norm));
193 _norm = NULL;
194 }
195 if (_grip) {
196 gtk_object_destroy(GTK_OBJECT(_grip));
197 _grip = NULL;
198 }
199 for (int i = 0; i < 4; i++) {
200 if (_l[i]) {
201 gtk_object_destroy(GTK_OBJECT(_l[i]));
202 _l[i] = NULL;
203 }
204 }
206 for (unsigned i = 0; i < _items.size(); i++) {
207 sp_object_unref(SP_OBJECT(_items[i].first), NULL);
208 }
210 _items.clear();
211 _items_centers.clear();
212 }
214 void Inkscape::SelTrans::resetState()
215 {
216 _state = STATE_SCALE;
217 }
219 void Inkscape::SelTrans::increaseState()
220 {
221 if (_state == STATE_SCALE) {
222 _state = STATE_ROTATE;
223 } else {
224 _state = STATE_SCALE;
225 }
227 _center_is_set = true; // no need to reread center
229 _updateHandles();
230 }
232 void Inkscape::SelTrans::setCenter(NR::Point const &p)
233 {
234 _center = p;
235 _center_is_set = true;
237 // Write the new center position into all selected items
238 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
239 SPItem *it = (SPItem*)SP_OBJECT(l->data);
240 it->setCenter(p);
241 // only set the value; updating repr and document_done will be done once, on ungrab
242 }
244 _updateHandles();
245 }
247 void Inkscape::SelTrans::grab(NR::Point const &p, gdouble x, gdouble y, bool show_handles)
248 {
249 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
251 g_return_if_fail(!_grabbed);
253 _grabbed = true;
254 _show_handles = show_handles;
255 _updateVolatileState();
256 _current_relative_affine.set_identity();
258 _changed = false;
260 if (_empty) {
261 return;
262 }
264 for (GSList const *l = selection->itemList(); l; l = l->next) {
265 SPItem *it = (SPItem*)sp_object_ref(SP_OBJECT(l->data), NULL);
266 _items.push_back(std::pair<SPItem *, NR::Matrix>(it, sp_item_i2d_affine(it)));
267 _items_centers.push_back(std::pair<SPItem *, NR::Point>(it, it->getCenter())); // for content-dragging, we need to remember original centers
268 }
270 _handle_x = x;
271 _handle_y = y;
273 // The selector tool should snap the bbox, special snappoints, and path nodes
274 // (The special points are the handles, center, rotation axis, font baseline, ends of spiral, etc.)
276 // First, determine the bounding box for snapping ...
277 _bbox = selection->bounds(_snap_bbox_type);
278 _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX); // Used for correctly scaling the strokewidth
279 _geometric_bbox = selection->bounds(SPItem::GEOMETRIC_BBOX);
280 _point = p;
281 if (_geometric_bbox) {
282 _point_geom = _geometric_bbox->min() + _geometric_bbox->dimensions() * NR::scale(x, y);
283 } else {
284 _point_geom = p;
285 }
287 // Next, get all points to consider for snapping
288 SnapManager const &m = _desktop->namedview->snap_manager;
289 _snap_points = selection->getSnapPoints(m.getIncludeItemCenter());
290 std::vector<NR::Point> snap_points_hull = selection->getSnapPointsConvexHull();
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 NR::Rect snap_points_bbox;
303 if ( snap_points_hull.empty() == false ) {
304 std::vector<NR::Point>::iterator i = snap_points_hull.begin();
305 snap_points_bbox = NR::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() * NR::scale(1-x, 1-y);
326 _opposite_for_specpoints = snap_points_bbox.min() + snap_points_bbox.dimensions() * NR::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<NR::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<NR::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(NR::Matrix const &rel_affine, NR::Point const &norm)
359 {
360 g_return_if_fail(_grabbed);
361 g_return_if_fail(!_empty);
363 NR::Matrix const affine( NR::translate(-norm) * rel_affine * NR::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].first;
369 NR::Matrix const &prev_transform = _items[i].second;
370 sp_item_set_i2d_affine(&item, prev_transform * affine);
371 }
372 } else {
373 if (_bbox) {
374 NR::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].first), 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.is_translation()) {
429 for (unsigned i = 0; i < _items_centers.size(); i++) {
430 SPItem *currentItem = _items_centers[i].first;
431 if (currentItem->isCenterSet()) { // only if it's already set
432 currentItem->setCenter (_items_centers[i].second * _current_relative_affine);
433 SP_OBJECT(currentItem)->updateRepr();
434 }
435 }
436 }
438 _items.clear();
439 _items_centers.clear();
441 if (_current_relative_affine.is_translation()) {
442 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
443 _("Move"));
444 } else if (_current_relative_affine.is_scale()) {
445 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
446 _("Scale"));
447 } else if (_current_relative_affine.is_rotation()) {
448 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
449 _("Rotate"));
450 } else {
451 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
452 _("Skew"));
453 }
455 } else {
457 if (_center_is_set) {
458 // we were dragging center; update reprs and commit undoable action
459 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
460 SPItem *it = (SPItem*)SP_OBJECT(l->data);
461 SP_OBJECT(it)->updateRepr();
462 }
463 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
464 _("Set center"));
465 }
467 _items.clear();
468 _items_centers.clear();
469 _updateHandles();
470 }
471 }
473 /* fixme: This is really bad, as we compare positions for each stamp (Lauris) */
474 /* fixme: IMHO the best way to keep sort cache would be to implement timestamping at last */
476 void Inkscape::SelTrans::stamp()
477 {
478 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
480 bool fixup = !_grabbed;
481 if ( fixup && _stamp_cache ) {
482 // TODO - give a proper fix. Simple temproary work-around for the grab() issue
483 g_slist_free(_stamp_cache);
484 _stamp_cache = NULL;
485 }
487 /* stamping mode */
488 if (!_empty) {
489 GSList *l;
490 if (_stamp_cache) {
491 l = _stamp_cache;
492 } else {
493 /* Build cache */
494 l = g_slist_copy((GSList *) selection->itemList());
495 l = g_slist_sort(l, (GCompareFunc) sp_object_compare_position);
496 _stamp_cache = l;
497 }
499 while (l) {
500 SPItem *original_item = SP_ITEM(l->data);
501 Inkscape::XML::Node *original_repr = SP_OBJECT_REPR(original_item);
503 // remember the position of the item
504 gint pos = original_repr->position();
505 // remember parent
506 Inkscape::XML::Node *parent = sp_repr_parent(original_repr);
508 Inkscape::XML::Node *copy_repr = original_repr->duplicate(parent->document());
510 // add the new repr to the parent
511 parent->appendChild(copy_repr);
512 // move to the saved position
513 copy_repr->setPosition(pos > 0 ? pos : 0);
515 SPItem *copy_item = (SPItem *) sp_desktop_document(_desktop)->getObjectByRepr(copy_repr);
517 NR::Matrix const *new_affine;
518 if (_show == SHOW_OUTLINE) {
519 NR::Matrix const i2d(sp_item_i2d_affine(original_item));
520 NR::Matrix const i2dnew( i2d * _current_relative_affine );
521 sp_item_set_i2d_affine(copy_item, i2dnew);
522 new_affine = ©_item->transform;
523 } else {
524 new_affine = &original_item->transform;
525 }
527 sp_item_write_transform(copy_item, copy_repr, *new_affine);
529 if ( copy_item->isCenterSet() && _center ) {
530 copy_item->setCenter(*_center * _current_relative_affine);
531 }
533 Inkscape::GC::release(copy_repr);
534 l = l->next;
535 }
536 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
537 _("Stamp"));
538 }
540 if ( fixup && _stamp_cache ) {
541 // TODO - give a proper fix. Simple temproary work-around for the grab() issue
542 g_slist_free(_stamp_cache);
543 _stamp_cache = NULL;
544 }
545 }
547 void Inkscape::SelTrans::_updateHandles()
548 {
549 if ( !_show_handles || _empty )
550 {
551 sp_remove_handles(_shandle, 8);
552 sp_remove_handles(_rhandle, 8);
553 sp_remove_handles(&_chandle, 1);
554 return;
555 }
557 // center handle
558 if ( _chandle == NULL ) {
559 _chandle = sp_knot_new(_desktop, _("<b>Center</b> of rotation and skewing: drag to reposition; scaling with Shift also uses this center"));
561 _chandle->setShape (SP_CTRL_SHAPE_BITMAP);
562 _chandle->setSize (13);
563 _chandle->setAnchor (handle_center.anchor);
564 _chandle->setMode (SP_CTRL_MODE_XOR);
565 _chandle->setFill(0x00000000, 0x00000000, 0x00000000);
566 _chandle->setStroke(0x000000ff, 0xff0000b0, 0xff0000b0);
567 _chandle->setPixbuf(handles[handle_center.control]);
568 sp_knot_update_ctrl(_chandle);
570 g_signal_connect(G_OBJECT(_chandle), "request",
571 G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle_center);
572 g_signal_connect(G_OBJECT(_chandle), "moved",
573 G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle_center);
574 g_signal_connect(G_OBJECT(_chandle), "grabbed",
575 G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle_center);
576 g_signal_connect(G_OBJECT(_chandle), "ungrabbed",
577 G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle_center);
578 g_signal_connect(G_OBJECT(_chandle), "clicked",
579 G_CALLBACK(sp_sel_trans_handle_click), (gpointer) &handle_center);
580 }
582 sp_remove_handles(&_chandle, 1);
583 if ( _state == STATE_SCALE ) {
584 sp_remove_handles(_rhandle, 8);
585 _showHandles(_shandle, handles_scale, 8,
586 _("<b>Squeeze or stretch</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"),
587 _("<b>Scale</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"));
588 } else {
589 sp_remove_handles(_shandle, 8);
590 _showHandles(_rhandle, handles_rotate, 8,
591 _("<b>Skew</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to skew around the opposite side"),
592 _("<b>Rotate</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to rotate around the opposite corner"));
593 }
595 if (!_center_is_set) {
596 _center = _desktop->selection->center();
597 _center_is_set = true;
598 }
600 if ( _state == STATE_SCALE || !_center ) {
601 sp_knot_hide(_chandle);
602 } else {
603 sp_knot_show(_chandle);
604 sp_knot_moveto(_chandle, &*_center);
605 }
606 }
608 void Inkscape::SelTrans::_updateVolatileState()
609 {
610 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
611 _empty = selection->isEmpty();
613 if (_empty) {
614 return;
615 }
617 //Update the bboxes
618 _bbox = selection->bounds(_snap_bbox_type);
619 _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX);
621 if (!_bbox) {
622 _empty = true;
623 return;
624 }
626 _strokewidth = stroke_average_width (selection->itemList());
627 }
629 static void sp_remove_handles(SPKnot *knot[], gint num)
630 {
631 for (int i = 0; i < num; i++) {
632 if (knot[i] != NULL) {
633 sp_knot_hide(knot[i]);
634 }
635 }
636 }
638 void Inkscape::SelTrans::_showHandles(SPKnot *knot[], SPSelTransHandle const handle[], gint num,
639 gchar const *even_tip, gchar const *odd_tip)
640 {
641 g_return_if_fail( !_empty );
643 for (int i = 0; i < num; i++) {
644 if (knot[i] == NULL) {
645 knot[i] = sp_knot_new(_desktop, i % 2 ? even_tip : odd_tip);
647 knot[i]->setShape (SP_CTRL_SHAPE_BITMAP);
648 knot[i]->setSize (13);
649 knot[i]->setAnchor (handle[i].anchor);
650 knot[i]->setMode (SP_CTRL_MODE_XOR);
651 knot[i]->setFill(0x000000ff, 0x00ff6600, 0x00ff6600); // inversion, green, green
652 knot[i]->setStroke(0x000000ff, 0x000000ff, 0x000000ff); // inversion
653 knot[i]->setPixbuf(handles[handle[i].control]);
654 sp_knot_update_ctrl(knot[i]);
656 g_signal_connect(G_OBJECT(knot[i]), "request",
657 G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle[i]);
658 g_signal_connect(G_OBJECT(knot[i]), "moved",
659 G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle[i]);
660 g_signal_connect(G_OBJECT(knot[i]), "grabbed",
661 G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle[i]);
662 g_signal_connect(G_OBJECT(knot[i]), "ungrabbed",
663 G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle[i]);
664 g_signal_connect(G_OBJECT(knot[i]), "event", G_CALLBACK(sp_seltrans_handle_event), (gpointer) &handle[i]);
665 }
666 sp_knot_show(knot[i]);
668 NR::Point const handle_pt(handle[i].x, handle[i].y);
669 // shouldn't have nullary bbox, but knots
670 g_assert(_bbox);
671 NR::Point p( _bbox->min()
672 + ( _bbox->dimensions()
673 * NR::scale(handle_pt) ) );
675 sp_knot_moveto(knot[i], &p);
676 }
677 }
679 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data)
680 {
681 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleGrab(
682 knot, state, *(SPSelTransHandle const *) data
683 );
684 }
686 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint /*state*/, gpointer /*data*/)
687 {
688 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->ungrab();
689 }
691 static void sp_sel_trans_handle_new_event(SPKnot *knot, NR::Point *position, guint state, gpointer data)
692 {
693 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleNewEvent(
694 knot, position, state, *(SPSelTransHandle const *) data
695 );
696 }
698 static gboolean sp_sel_trans_handle_request(SPKnot *knot, NR::Point *position, guint state, gboolean *data)
699 {
700 return SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleRequest(
701 knot, position, state, *(SPSelTransHandle const *) data
702 );
703 }
705 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data)
706 {
707 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleClick(
708 knot, state, *(SPSelTransHandle const *) data
709 );
710 }
712 void Inkscape::SelTrans::handleClick(SPKnot */*knot*/, guint state, SPSelTransHandle const &handle)
713 {
714 switch (handle.anchor) {
715 case GTK_ANCHOR_CENTER:
716 if (state & GDK_SHIFT_MASK) {
717 // Unset the center position for all selected items
718 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
719 SPItem *it = (SPItem*)(SP_OBJECT(l->data));
720 it->unsetCenter();
721 SP_OBJECT(it)->updateRepr();
722 _center_is_set = false; // center has changed
723 _updateHandles();
724 }
725 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
726 _("Reset center"));
727 }
728 break;
729 default:
730 break;
731 }
732 }
734 void Inkscape::SelTrans::handleGrab(SPKnot *knot, guint /*state*/, SPSelTransHandle const &handle)
735 {
736 switch (handle.anchor) {
737 case GTK_ANCHOR_CENTER:
738 g_object_set(G_OBJECT(_grip),
739 "shape", SP_CTRL_SHAPE_BITMAP,
740 "size", 13.0,
741 NULL);
742 sp_canvas_item_show(_grip);
743 break;
744 default:
745 g_object_set(G_OBJECT(_grip),
746 "shape", SP_CTRL_SHAPE_CROSS,
747 "size", 7.0,
748 NULL);
749 sp_canvas_item_show(_norm);
750 sp_canvas_item_show(_grip);
752 break;
753 }
755 grab(sp_knot_position(knot), handle.x, handle.y, FALSE);
756 }
759 void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, NR::Point *position, guint state, SPSelTransHandle const &handle)
760 {
761 if (!SP_KNOT_IS_GRABBED(knot)) {
762 return;
763 }
765 // in case items have been unhooked from the document, don't
766 // try to continue processing events for them.
767 for (unsigned int i = 0; i < _items.size(); i++) {
768 if (!SP_OBJECT_DOCUMENT(SP_OBJECT(_items[i].first)) ) {
769 return;
770 }
771 }
773 handle.action(this, handle, *position, state);
774 }
777 gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, NR::Point *position, guint state, SPSelTransHandle const &handle)
778 {
779 if (!SP_KNOT_IS_GRABBED(knot)) {
780 return TRUE;
781 }
783 knot->desktop->setPosition(*position);
785 // When holding shift while rotating or skewing, the transformation will be
786 // relative to the point opposite of the handle; otherwise it will be relative
787 // to the center as set for the selection
788 if ((!(state & GDK_SHIFT_MASK) == !(_state == STATE_ROTATE)) && (&handle != &handle_center)) {
789 _origin = _opposite;
790 _origin_for_bboxpoints = _opposite_for_bboxpoints;
791 _origin_for_specpoints = _opposite_for_specpoints;
792 } else if (_center) {
793 _origin = *_center;
794 _origin_for_bboxpoints = *_center;
795 _origin_for_specpoints = *_center;
796 } else {
797 // FIXME
798 return TRUE;
799 }
800 if (handle.request(this, handle, *position, state)) {
801 sp_knot_set_position(knot, position, state);
802 SP_CTRL(_grip)->moveto(*position);
803 SP_CTRL(_norm)->moveto(_origin);
804 }
806 return TRUE;
807 }
810 void Inkscape::SelTrans::_selChanged(Inkscape::Selection */*selection*/)
811 {
812 if (!_grabbed) {
813 // reread in case it changed on the fly:
814 gchar const *prefs_bbox = prefs_get_string_attribute("tools", "bounding_box");
815 _snap_bbox_type = (prefs_bbox != NULL && strcmp(prefs_bbox, "geometric")==0)? SPItem::GEOMETRIC_BBOX : SPItem::APPROXIMATE_BBOX;
816 //SPItem::APPROXIMATE_BBOX will be replaced by SPItem::VISUAL_BBOX, as soon as the latter is implemented properly
818 _updateVolatileState();
819 _current_relative_affine.set_identity();
820 _center_is_set = false; // center(s) may have changed
821 _updateHandles();
822 }
823 }
825 void Inkscape::SelTrans::_selModified(Inkscape::Selection */*selection*/, guint /*flags*/)
826 {
827 if (!_grabbed) {
828 _updateVolatileState();
829 _current_relative_affine.set_identity();
831 // reset internal flag
832 _changed = false;
834 _center_is_set = false; // center(s) may have changed
836 _updateHandles();
837 }
838 }
840 /*
841 * handlers for handle move-request
842 */
844 /** Returns -1 or 1 according to the sign of x. Returns 1 for 0 and NaN. */
845 static double sign(double const x)
846 {
847 return ( x < 0
848 ? -1
849 : 1 );
850 }
852 gboolean sp_sel_trans_scale_request(Inkscape::SelTrans *seltrans,
853 SPSelTransHandle const &, NR::Point &pt, guint state)
854 {
855 return seltrans->scaleRequest(pt, state);
856 }
858 gboolean sp_sel_trans_stretch_request(Inkscape::SelTrans *seltrans,
859 SPSelTransHandle const &handle, NR::Point &pt, guint state)
860 {
861 return seltrans->stretchRequest(handle, pt, state);
862 }
864 gboolean sp_sel_trans_skew_request(Inkscape::SelTrans *seltrans,
865 SPSelTransHandle const &handle, NR::Point &pt, guint state)
866 {
867 return seltrans->skewRequest(handle, pt, state);
868 }
870 gboolean sp_sel_trans_rotate_request(Inkscape::SelTrans *seltrans,
871 SPSelTransHandle const &, NR::Point &pt, guint state)
872 {
873 return seltrans->rotateRequest(pt, state);
874 }
876 gboolean sp_sel_trans_center_request(Inkscape::SelTrans *seltrans,
877 SPSelTransHandle const &, NR::Point &pt, guint state)
878 {
879 return seltrans->centerRequest(pt, state);
880 }
882 gboolean Inkscape::SelTrans::scaleRequest(NR::Point &pt, guint state)
883 {
885 // Calculate the scale factors, which can be either visual or geometric
886 // depending on which type of bbox is currently being used (see preferences -> selector tool)
887 NR::scale default_scale = calcScaleFactors(_point, pt, _origin);
889 // Find the scale factors for the geometric bbox
890 NR::Point pt_geom = _getGeomHandlePos(pt);
891 NR::scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
893 _absolute_affine = NR::identity(); //Initialize the scaler
895 if (state & GDK_MOD1_MASK) { // scale by an integer multiplier/divider
896 // We're scaling either the visual or the geometric bbox here (see the comment above)
897 for ( unsigned int i = 0 ; i < 2 ; i++ ) {
898 if (fabs(default_scale[i]) > 1) {
899 default_scale[i] = round(default_scale[i]);
900 } else if (default_scale[i] != 0) {
901 default_scale[i] = 1/round(1/(MIN(default_scale[i], 10)));
902 }
903 }
904 // Update the knot position
905 pt = _calcAbsAffineDefault(default_scale);
906 // When scaling by an integer, snapping is not needed
907 } else {
908 // In all other cases we should try to snap now
909 SnapManager const &m = _desktop->namedview->snap_manager;
911 /* Get a STL list of the selected items.
912 ** FIXME: this should probably be done by Inkscape::Selection.
913 */
914 std::list<SPItem const*> it;
915 for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
916 it.push_back(reinterpret_cast<SPItem*>(i->data));
917 }
919 std::pair<NR::scale, bool> bb = std::make_pair(NR::scale(1,1), false);
920 std::pair<NR::scale, bool> sn = std::make_pair(NR::scale(1,1), false);
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.second ? fabs(bb.first[NR::X] - default_scale[NR::X]) : NR_HUGE;
944 sd = sn.second ? fabs(sn.first[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.second ? fabs(NR::L2(bb.first.point()) - NR::L2(default_scale.point())) : NR_HUGE;
952 sd = sn.second ? fabs(NR::L2(sn.first.point()) - NR::L2(geom_scale.point())) : NR_HUGE;
953 }
955 if (!(bb.second || sn.second)) {
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 default_scale = bb.first;
961 // Calculate the new transformation and update the handle position
962 pt = _calcAbsAffineDefault(default_scale);
963 } else {
964 // We snapped the special points (e.g. nodes), which are not at the visual bbox
965 // The handle location however (pt) might however be at the visual bbox, so we
966 // will have to calculate pt taking the stroke width into account
967 geom_scale = sn.first;
968 pt = _calcAbsAffineGeom(geom_scale);
969 }
970 }
972 /* Status text */
973 _message_context.setF(Inkscape::NORMAL_MESSAGE,
974 _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
975 100 * _absolute_affine[0], 100 * _absolute_affine[3]);
977 return TRUE;
978 }
980 gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, NR::Point &pt, guint state)
981 {
982 NR::Dim2 axis, perp;
983 switch (handle.cursor) {
984 case GDK_TOP_SIDE:
985 case GDK_BOTTOM_SIDE:
986 axis = NR::Y;
987 perp = NR::X;
988 break;
989 case GDK_LEFT_SIDE:
990 case GDK_RIGHT_SIDE:
991 axis = NR::X;
992 perp = NR::Y;
993 break;
994 default:
995 g_assert_not_reached();
996 return TRUE;
997 };
999 // Calculate the scale factors, which can be either visual or geometric
1000 // depending on which type of bbox is currently being used (see preferences -> selector tool)
1001 NR::scale default_scale = calcScaleFactors(_point, pt, _origin);
1002 default_scale[perp] = 1;
1004 // Find the scale factors for the geometric bbox
1005 NR::Point pt_geom = _getGeomHandlePos(pt);
1006 NR::scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
1007 geom_scale[perp] = 1;
1009 _absolute_affine = NR::identity(); //Initialize the scaler
1011 if (state & GDK_MOD1_MASK) { // stretch by an integer multiplier/divider
1012 if (fabs(default_scale[axis]) > 1) {
1013 default_scale[axis] = round(default_scale[axis]);
1014 } else if (default_scale[axis] != 0) {
1015 default_scale[axis] = 1/round(1/(MIN(default_scale[axis], 10)));
1016 }
1017 // Calculate the new transformation and update the handle position
1018 pt = _calcAbsAffineDefault(default_scale);
1019 // When stretching by an integer, snapping is not needed
1020 } else {
1021 // In all other cases we should try to snap now
1023 /* Get a STL list of the selected items.
1024 ** FIXME: this should probably be done by Inkscape::Selection.
1025 */
1026 std::list<SPItem const*> it;
1027 for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
1028 it.push_back(reinterpret_cast<SPItem*>(i->data));
1029 }
1031 SnapManager const &m = _desktop->namedview->snap_manager;
1033 std::pair<NR::Coord, bool> bb = std::make_pair(NR_HUGE, false);
1034 std::pair<NR::Coord, bool> sn = std::make_pair(NR_HUGE, false);
1035 NR::Coord bd(NR_HUGE);
1036 NR::Coord sd(NR_HUGE);
1038 bool symmetrical = state & GDK_CONTROL_MASK;
1040 bb = m.constrainedSnapStretch(Snapper::SNAPPOINT_BBOX, _bbox_points, it, default_scale[axis], _origin_for_bboxpoints, axis, symmetrical);
1041 sn = m.constrainedSnapStretch(Snapper::SNAPPOINT_NODE, _snap_points, it, geom_scale[axis], _origin_for_specpoints, axis, symmetrical);
1043 if (bb.second) {
1044 // We snapped the bbox (which is either visual or geometric)
1045 bd = fabs(bb.first - default_scale[axis]);
1046 default_scale[axis] = bb.first;
1047 }
1049 if (sn.second) {
1050 sd = fabs(sn.first - geom_scale[axis]);
1051 geom_scale[axis] = sn.first;
1052 }
1054 if (symmetrical) {
1055 // on ctrl, apply symmetrical scaling instead of stretching
1056 // Preserve aspect ratio, but never flip in the dimension not being edited (by using fabs())
1057 default_scale[perp] = fabs(default_scale[axis]);
1058 geom_scale[perp] = fabs(geom_scale[axis]);
1059 }
1061 if (!(bb.second || sn.second)) {
1062 // We didn't snap at all! Don't update the handle position, just calculate the new transformation
1063 _calcAbsAffineDefault(default_scale);
1064 } else if (bd < sd) {
1065 // Calculate the new transformation and update the handle position
1066 pt = _calcAbsAffineDefault(default_scale);
1067 } else {
1068 // We snapped the special points (e.g. nodes), which are not at the visual bbox
1069 // The handle location however (pt) might however be at the visual bbox, so we
1070 // will have to calculate pt taking the stroke width into account
1071 pt = _calcAbsAffineGeom(geom_scale);
1072 }
1073 }
1075 // status text
1076 _message_context.setF(Inkscape::NORMAL_MESSAGE,
1077 _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1078 100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1080 return TRUE;
1081 }
1083 gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, NR::Point &pt, guint state)
1084 {
1085 /* When skewing (or rotating):
1086 * 1) the stroke width will not change. This makes life much easier because we don't have to
1087 * account for that (like for scaling or stretching). As a consequence, all points will
1088 * have the same origin for the transformation and for the snapping.
1089 * 2) When holding shift, the transformation will be relative to the point opposite of
1090 * the handle; otherwise it will be relative to the center as set for the selection
1091 */
1093 NR::Dim2 dim_a;
1094 NR::Dim2 dim_b;
1096 switch (handle.cursor) {
1097 case GDK_SB_H_DOUBLE_ARROW:
1098 dim_a = NR::Y;
1099 dim_b = NR::X;
1100 break;
1101 case GDK_SB_V_DOUBLE_ARROW:
1102 dim_a = NR::X;
1103 dim_b = NR::Y;
1104 break;
1105 default:
1106 g_assert_not_reached();
1107 abort();
1108 break;
1109 }
1111 NR::Point const initial_delta = _point - _origin;
1113 if (fabs(initial_delta[dim_a]) < 1e-15) {
1114 return false;
1115 }
1117 // Calculate the scale factors, which can be either visual or geometric
1118 // depending on which type of bbox is currently being used (see preferences -> selector tool)
1119 NR::scale scale = calcScaleFactors(_point, pt, _origin, false);
1120 NR::scale skew = calcScaleFactors(_point, pt, _origin, true);
1121 scale[dim_b] = 1;
1122 skew[dim_b] = 1;
1124 if (fabs(scale[dim_a]) < 1) {
1125 // Prevent shrinking of the selected object, while allowing mirroring
1126 scale[dim_a] = sign(scale[dim_a]);
1127 } else {
1128 // Allow expanding of the selected object by integer multiples
1129 scale[dim_a] = floor(scale[dim_a] + 0.5);
1130 }
1132 double radians = atan(skew[dim_a] / scale[dim_a]);
1134 if (state & GDK_CONTROL_MASK) {
1135 // Snap to defined angle increments
1136 int snaps = prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12);
1137 if (snaps) {
1138 double sections = floor(radians * snaps / M_PI + .5);
1139 if (fabs(sections) >= snaps / 2) {
1140 sections = sign(sections) * (snaps / 2 - 1);
1141 }
1142 radians = (M_PI / snaps) * sections;
1143 }
1144 skew[dim_a] = tan(radians) * scale[dim_a];
1145 } else {
1146 // Snap to objects, grids, guides
1148 /* Get a STL list of the selected items.
1149 ** FIXME: this should probably be done by Inkscape::Selection.
1150 */
1151 std::list<SPItem const*> it;
1152 for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
1153 it.push_back(reinterpret_cast<SPItem*>(i->data));
1154 }
1156 SnapManager const &m = _desktop->namedview->snap_manager;
1158 std::pair<NR::Coord, bool> bb = m.freeSnapSkew(Inkscape::Snapper::SNAPPOINT_BBOX, _bbox_points, it, skew[dim_a], _origin, dim_b);
1159 std::pair<NR::Coord, bool> sn = m.freeSnapSkew(Inkscape::Snapper::SNAPPOINT_NODE, _snap_points, it, skew[dim_a], _origin, dim_b);
1161 if (bb.second || sn.second) {
1162 // We snapped something, so change the skew to reflect it
1163 NR::Coord const bd = bb.second ? bb.first : NR_HUGE;
1164 NR::Coord const sd = sn.second ? sn.first : NR_HUGE;
1165 skew[dim_a] = std::min(bd, sd);
1166 }
1167 }
1169 // Update the handle position
1170 pt[dim_b] = initial_delta[dim_a] * skew[dim_a] + _point[dim_b];
1171 pt[dim_a] = initial_delta[dim_a] * scale[dim_a] + _origin[dim_a];
1173 // Calculate the relative affine
1174 _relative_affine = NR::identity();
1175 _relative_affine[2*dim_a + dim_a] = (pt[dim_a] - _origin[dim_a]) / initial_delta[dim_a];
1176 _relative_affine[2*dim_a + (dim_b)] = (pt[dim_b] - _point[dim_b]) / initial_delta[dim_a];
1177 _relative_affine[2*(dim_b) + (dim_a)] = 0;
1178 _relative_affine[2*(dim_b) + (dim_b)] = 1;
1180 for (int i = 0; i < 2; i++) {
1181 if (fabs(_relative_affine[3*i]) < 1e-15) {
1182 _relative_affine[3*i] = 1e-15;
1183 }
1184 }
1186 // Update the status text
1187 double degrees = mod360symm(Geom::rad_to_deg(radians));
1188 _message_context.setF(Inkscape::NORMAL_MESSAGE,
1189 // TRANSLATORS: don't modify the first ";"
1190 // (it will NOT be displayed as ";" - only the second one will be)
1191 _("<b>Skew</b>: %0.2f°; with <b>Ctrl</b> to snap angle"),
1192 degrees);
1194 return TRUE;
1195 }
1197 gboolean Inkscape::SelTrans::rotateRequest(NR::Point &pt, guint state)
1198 {
1199 /* When rotating (or skewing):
1200 * 1) the stroke width will not change. This makes life much easier because we don't have to
1201 * account for that (like for scaling or stretching). As a consequence, all points will
1202 * have the same origin for the transformation and for the snapping.
1203 * 2) When holding shift, the transformation will be relative to the point opposite of
1204 * the handle; otherwise it will be relative to the center as set for the selection
1205 */
1207 int snaps = prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12);
1209 // rotate affine in rotate
1210 NR::Point const d1 = _point - _origin;
1211 NR::Point const d2 = pt - _origin;
1213 NR::Coord const h1 = NR::L2(d1); // initial radius
1214 if (h1 < 1e-15) return FALSE;
1215 NR::Point q1 = d1 / h1; // normalized initial vector to handle
1216 NR::Coord const h2 = NR::L2(d2); // new radius
1217 if (fabs(h2) < 1e-15) return FALSE;
1218 NR::Point q2 = d2 / h2; // normalized new vector to handle
1220 double radians;
1221 if (state & GDK_CONTROL_MASK) {
1222 // Snap to defined angle increments
1223 double cos_t = NR::dot(q1, q2);
1224 double sin_t = NR::dot(NR::rot90(q1), q2);
1225 radians = atan2(sin_t, cos_t);
1226 if (snaps) {
1227 radians = ( M_PI / snaps ) * floor( radians * snaps / M_PI + .5 );
1228 }
1229 q1 = NR::Point(1, 0);
1230 q2 = NR::Point(cos(radians), sin(radians));
1231 } else {
1232 radians = atan2(NR::dot(NR::rot90(d1), d2),
1233 NR::dot(d1, d2));
1234 }
1236 NR::rotate const r1(q1);
1237 NR::rotate const r2(q2);
1239 // Calculate the relative affine
1240 _relative_affine = NR::Matrix(r2/r1);
1242 // Update the handle position
1243 pt = _point * NR::translate(-_origin) * _relative_affine * NR::translate(_origin);
1245 // Update the status text
1246 double degrees = mod360symm(Geom::rad_to_deg(radians));
1247 _message_context.setF(Inkscape::NORMAL_MESSAGE,
1248 // TRANSLATORS: don't modify the first ";"
1249 // (it will NOT be displayed as ";" - only the second one will be)
1250 _("<b>Rotate</b>: %0.2f°; with <b>Ctrl</b> to snap angle"), degrees);
1252 return TRUE;
1253 }
1255 gboolean Inkscape::SelTrans::centerRequest(NR::Point &pt, guint state)
1256 {
1257 SnapManager const &m = _desktop->namedview->snap_manager;
1258 pt = m.freeSnap(Snapper::SNAPPOINT_NODE, pt, NULL).getPoint();
1260 if (state & GDK_CONTROL_MASK) {
1261 if ( fabs(_point[NR::X] - pt[NR::X]) > fabs(_point[NR::Y] - pt[NR::Y]) ) {
1262 pt[NR::Y] = _point[NR::Y];
1263 } else {
1264 pt[NR::X] = _point[NR::X];
1265 }
1266 }
1268 if ( !(state & GDK_SHIFT_MASK) && _bbox ) {
1269 // screen pixels to snap center to bbox
1270 #define SNAP_DIST 5
1271 // FIXME: take from prefs
1272 double snap_dist = SNAP_DIST / _desktop->current_zoom();
1274 for (int i = 0; i < 2; i++) {
1275 if (fabs(pt[i] - _bbox->min()[i]) < snap_dist) {
1276 pt[i] = _bbox->min()[i];
1277 }
1278 if (fabs(pt[i] - _bbox->midpoint()[i]) < snap_dist) {
1279 pt[i] = _bbox->midpoint()[i];
1280 }
1281 if (fabs(pt[i] - _bbox->max()[i]) < snap_dist) {
1282 pt[i] = _bbox->max()[i];
1283 }
1284 }
1285 }
1287 // status text
1288 GString *xs = SP_PX_TO_METRIC_STRING(pt[NR::X], _desktop->namedview->getDefaultMetric());
1289 GString *ys = SP_PX_TO_METRIC_STRING(pt[NR::Y], _desktop->namedview->getDefaultMetric());
1290 _message_context.setF(Inkscape::NORMAL_MESSAGE, _("Move <b>center</b> to %s, %s"), xs->str, ys->str);
1291 g_string_free(xs, FALSE);
1292 g_string_free(ys, FALSE);
1294 return TRUE;
1295 }
1297 /*
1298 * handlers for handle movement
1299 *
1300 */
1302 void sp_sel_trans_stretch(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, NR::Point &pt, guint state)
1303 {
1304 seltrans->stretch(handle, pt, state);
1305 }
1307 void sp_sel_trans_scale(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
1308 {
1309 seltrans->scale(pt, state);
1310 }
1312 void sp_sel_trans_skew(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, NR::Point &pt, guint state)
1313 {
1314 seltrans->skew(handle, pt, state);
1315 }
1317 void sp_sel_trans_rotate(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
1318 {
1319 seltrans->rotate(pt, state);
1320 }
1322 void Inkscape::SelTrans::stretch(SPSelTransHandle const &handle, NR::Point &pt, guint state)
1323 {
1324 transform(_absolute_affine, NR::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1325 }
1327 void Inkscape::SelTrans::scale(NR::Point &pt, guint /*state*/)
1328 {
1329 transform(_absolute_affine, NR::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1330 }
1332 void Inkscape::SelTrans::skew(SPSelTransHandle const &handle, NR::Point &pt, guint /*state*/)
1333 {
1334 transform(_relative_affine, _origin);
1335 }
1337 void Inkscape::SelTrans::rotate(NR::Point &pt, guint /*state*/)
1338 {
1339 transform(_relative_affine, _origin);
1340 }
1342 void sp_sel_trans_center(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint /*state*/)
1343 {
1344 seltrans->setCenter(pt);
1345 }
1348 void Inkscape::SelTrans::moveTo(NR::Point const &xy, guint state)
1349 {
1350 SnapManager const &m = _desktop->namedview->snap_manager;
1352 /* The amount that we've moved by during this drag */
1353 NR::Point dxy = xy - _point;
1355 /* Get a STL list of the selected items.
1356 ** FIXME: this should probably be done by Inkscape::Selection.
1357 */
1358 std::list<SPItem const*> it;
1359 for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
1360 it.push_back(reinterpret_cast<SPItem*>(i->data));
1361 }
1363 bool const alt = (state & GDK_MOD1_MASK);
1364 bool const control = (state & GDK_CONTROL_MASK);
1365 bool const shift = (state & GDK_SHIFT_MASK);
1367 if (alt) {
1369 /* Alt pressed means keep offset: snap the moved distance to the grid.
1370 ** FIXME: this will snap to more than just the grid, nowadays.
1371 */
1373 dxy = m.freeSnap(Snapper::SNAPPOINT_NODE, dxy, NULL).getPoint();
1375 } else if (!shift) {
1377 /* We're snapping to things, possibly with a constraint to horizontal or
1378 ** vertical movement. Obtain a list of possible translations and then
1379 ** pick the smallest.
1380 */
1382 /* This will be our list of possible translations */
1383 std::list<std::pair<NR::Point, bool> > s;
1385 if (control) {
1387 /* Snap to things, and also constrain to horizontal or vertical movement */
1389 for (unsigned int dim = 0; dim < 2; dim++) {
1390 s.push_back(m.constrainedSnapTranslation(Inkscape::Snapper::SNAPPOINT_BBOX,
1391 _bbox_points,
1392 it,
1393 Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1394 dxy));
1396 s.push_back(m.constrainedSnapTranslation(Inkscape::Snapper::SNAPPOINT_NODE,
1397 _snap_points,
1398 it,
1399 Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1400 dxy));
1401 }
1403 } else {
1405 // Let's leave this timer code here for a while. I'll probably need it in the near future (Diederik van Lierop)
1406 /* GTimeVal starttime;
1407 GTimeVal endtime;
1408 g_get_current_time(&starttime); */
1410 /* Snap to things with no constraint */
1411 s.push_back(m.freeSnapTranslation(Inkscape::Snapper::SNAPPOINT_BBOX,
1412 _bbox_points, it, dxy));
1413 s.push_back(m.freeSnapTranslation(Inkscape::Snapper::SNAPPOINT_NODE,
1414 _snap_points, it, dxy));
1416 /*g_get_current_time(&endtime);
1417 double elapsed = ((((double)endtime.tv_sec - starttime.tv_sec) * G_USEC_PER_SEC + (endtime.tv_usec - starttime.tv_usec))) / 1000.0;
1418 std::cout << "Time spent snapping: " << elapsed << std::endl; */
1419 }
1421 /* Pick one */
1422 NR::Coord best = NR_HUGE;
1423 for (std::list<std::pair<NR::Point, bool> >::const_iterator i = s.begin(); i != s.end(); i++) {
1424 if (i->second) {
1425 NR::Coord const m = NR::L2(i->first);
1426 if (m < best) {
1427 best = m;
1428 dxy = i->first;
1429 }
1430 }
1431 }
1432 }
1434 if (control) {
1435 /* Ensure that the horizontal and vertical constraint has been applied */
1436 if (fabs(dxy[NR::X]) > fabs(dxy[NR::Y])) {
1437 dxy[NR::Y] = 0;
1438 } else {
1439 dxy[NR::X] = 0;
1440 }
1441 }
1443 NR::Matrix const move((NR::translate(dxy)));
1444 NR::Point const norm(0, 0);
1445 transform(move, norm);
1447 // status text
1448 GString *xs = SP_PX_TO_METRIC_STRING(dxy[NR::X], _desktop->namedview->getDefaultMetric());
1449 GString *ys = SP_PX_TO_METRIC_STRING(dxy[NR::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 NR::Point Inkscape::SelTrans::_getGeomHandlePos(NR::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 NR::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 NR::Rect new_bbox = NR::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 NR::Point normalized_handle_pos = (visual_handle_pos - new_bbox.min()) * NR::scale(new_bbox.dimensions()).inverse();
1477 // Calculate the absolute affine while taking into account the scaling of the stroke width
1478 int transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1479 NR::Matrix abs_affine = get_scale_transform_with_stroke (*_bbox, _strokewidth, transform_stroke,
1480 new_bbox.min()[NR::X], new_bbox.min()[NR::Y], new_bbox.max()[NR::X], new_bbox.max()[NR::Y]);
1482 // Calculate the scaled geometrical bbox
1483 NR::Rect new_geom_bbox = NR::Rect(_geometric_bbox->min() * abs_affine, _geometric_bbox->max() * abs_affine);
1484 // Find the location of the handle on this new geometrical bbox
1485 return normalized_handle_pos * NR::scale(new_geom_bbox.dimensions()) + new_geom_bbox.min(); //new position of the geometric handle
1486 }
1488 NR::scale Inkscape::calcScaleFactors(NR::Point const &initial_point, NR::Point const &new_point, NR::Point const &origin, bool const skew)
1489 {
1490 // Work out the new scale factors for the bbox
1492 NR::Point const initial_delta = initial_point - origin;
1493 NR::Point const new_delta = new_point - origin;
1494 NR::Point const offset = new_point - initial_point;
1495 NR::scale scale(1, 1);
1497 for ( unsigned int i = 0 ; i < 2 ; i++ ) {
1498 if ( fabs(initial_delta[i]) > 1e-6 ) {
1499 if (skew) {
1500 scale[i] = offset[1-i] / initial_delta[i];
1501 } else {
1502 scale[i] = new_delta[i] / initial_delta[i];
1503 }
1504 }
1505 }
1507 return scale;
1508 }
1510 // Only for scaling/stretching
1511 NR::Point Inkscape::SelTrans::_calcAbsAffineDefault(NR::scale const default_scale)
1512 {
1513 NR::Matrix abs_affine = NR::translate(-_origin) * NR::Matrix(default_scale) * NR::translate(_origin);
1514 NR::Point new_bbox_min = _approximate_bbox->min() * abs_affine;
1515 NR::Point new_bbox_max = _approximate_bbox->max() * abs_affine;
1517 int transform_stroke = false;
1518 gdouble strokewidth = 0;
1520 if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
1521 transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1522 strokewidth = _strokewidth;
1523 }
1525 _absolute_affine = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
1526 new_bbox_min[NR::X], new_bbox_min[NR::Y], new_bbox_max[NR::X], new_bbox_max[NR::Y]);
1528 // return the new handle position
1529 return ( _point - _origin ) * default_scale + _origin;
1530 }
1532 // Only for scaling/stretching
1533 NR::Point Inkscape::SelTrans::_calcAbsAffineGeom(NR::scale const geom_scale)
1534 {
1535 _relative_affine = NR::Matrix(geom_scale);
1536 _absolute_affine = NR::translate(-_origin_for_specpoints) * _relative_affine * NR::translate(_origin_for_specpoints);
1538 bool const transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1539 NR::Rect visual_bbox = get_visual_bbox(_geometric_bbox, _absolute_affine, _strokewidth, transform_stroke);
1541 // return the new handle position
1542 return visual_bbox.min() + visual_bbox.dimensions() * NR::scale(_handle_x, _handle_y);
1543 }
1546 /*
1547 Local Variables:
1548 mode:c++
1549 c-file-style:"stroustrup"
1550 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1551 indent-tabs-mode:nil
1552 fill-column:99
1553 End:
1554 */
1555 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :