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 _point_geom = _geometric_bbox->min() + _geometric_bbox->dimensions() * NR::scale(x, y);
283 // Next, get all points to consider for snapping
284 SnapManager const &m = _desktop->namedview->snap_manager;
285 _snap_points = selection->getSnapPoints(m.getIncludeItemCenter());
286 std::vector<NR::Point> snap_points_hull = selection->getSnapPointsConvexHull();
287 if (_snap_points.size() > 100) {
288 /* Snapping a huge number of nodes will take way too long, so limit the number of snappable nodes
289 An average user would rarely ever try to snap such a large number of nodes anyway, because
290 (s)he could hardly discern which node would be snapping */
291 _snap_points = snap_points_hull;
292 // Unfortunately, by now we will have lost the font-baseline snappoints :-(
293 }
295 // Find bbox hulling all special points, which excludes stroke width. Here we need to include the
296 // path nodes, for example because a rectangle which has been converted to a path doesn't have
297 // any other special points
298 NR::Rect snap_points_bbox;
299 if ( snap_points_hull.empty() == false ) {
300 std::vector<NR::Point>::iterator i = snap_points_hull.begin();
301 snap_points_bbox = NR::Rect(*i, *i);
302 i++;
303 while (i != snap_points_hull.end()) {
304 snap_points_bbox.expandTo(*i);
305 i++;
306 }
307 }
309 _bbox_points.clear();
310 if (_bbox) {
311 // ... and add the bbox corners to _bbox_points
312 for ( unsigned i = 0 ; i < 4 ; i++ ) {
313 _bbox_points.push_back(_bbox->corner(i));
314 }
315 // There are two separate "opposites" (i.e. opposite w.r.t. the handle being dragged):
316 // - one for snapping the boundingbox, which can be either visual or geometric
317 // - one for snapping the special points
318 // The "opposite" in case of a geometric boundingbox always coincides with the "opposite" for the special points
319 // These distinct "opposites" are needed in the snapmanager to avoid bugs such as #sf1540195 (in which
320 // a box is caught between two guides)
321 _opposite_for_bboxpoints = _bbox->min() + _bbox->dimensions() * NR::scale(1-x, 1-y);
322 _opposite_for_specpoints = snap_points_bbox.min() + snap_points_bbox.dimensions() * NR::scale(1-x, 1-y);
323 _opposite = _opposite_for_bboxpoints;
324 }
326 // The lines below are usefull for debugging any snapping issues, as they'll spit out all points that are considered for snapping
328 /*std::cout << "Number of snap points: " << _snap_points.size() << std::endl;
329 for (std::vector<NR::Point>::const_iterator i = _snap_points.begin(); i != _snap_points.end(); i++)
330 {
331 std::cout << " " << *i << std::endl;
332 }
334 std::cout << "Number of bbox points: " << _bbox_points.size() << std::endl;
335 for (std::vector<NR::Point>::const_iterator i = _bbox_points.begin(); i != _bbox_points.end(); i++)
336 {
337 std::cout << " " << *i << std::endl;
338 }*/
340 if ((x != -1) && (y != -1)) {
341 sp_canvas_item_show(_norm);
342 sp_canvas_item_show(_grip);
343 }
345 if (_show == SHOW_OUTLINE) {
346 for (int i = 0; i < 4; i++)
347 sp_canvas_item_show(_l[i]);
348 }
350 _updateHandles();
351 g_return_if_fail(_stamp_cache == NULL);
352 }
354 void Inkscape::SelTrans::transform(NR::Matrix const &rel_affine, NR::Point const &norm)
355 {
356 g_return_if_fail(_grabbed);
357 g_return_if_fail(!_empty);
359 NR::Matrix const affine( NR::translate(-norm) * rel_affine * NR::translate(norm) );
361 if (_show == SHOW_CONTENT) {
362 // update the content
363 for (unsigned i = 0; i < _items.size(); i++) {
364 SPItem &item = *_items[i].first;
365 NR::Matrix const &prev_transform = _items[i].second;
366 sp_item_set_i2d_affine(&item, prev_transform * affine);
367 }
368 } else {
369 if (_bbox) {
370 NR::Point p[4];
371 /* update the outline */
372 for (unsigned i = 0 ; i < 4 ; i++) {
373 p[i] = _bbox->corner(i) * affine;
374 }
375 for (unsigned i = 0 ; i < 4 ; i++) {
376 sp_ctrlline_set_coords(SP_CTRLLINE(_l[i]), p[i], p[(i+1)%4]);
377 }
378 }
379 }
381 _current_relative_affine = affine;
382 _changed = true;
383 _updateHandles();
384 }
386 void Inkscape::SelTrans::ungrab()
387 {
388 g_return_if_fail(_grabbed);
389 _grabbed = false;
390 _show_handles = true;
392 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
393 _updateVolatileState();
395 for (unsigned i = 0; i < _items.size(); i++) {
396 sp_object_unref(SP_OBJECT(_items[i].first), NULL);
397 }
399 sp_canvas_item_hide(_norm);
400 sp_canvas_item_hide(_grip);
402 if (_show == SHOW_OUTLINE) {
403 for (int i = 0; i < 4; i++)
404 sp_canvas_item_hide(_l[i]);
405 }
407 if (_stamp_cache) {
408 g_slist_free(_stamp_cache);
409 _stamp_cache = NULL;
410 }
412 _message_context.clear();
414 if (!_empty && _changed) {
415 sp_selection_apply_affine(selection, _current_relative_affine, (_show == SHOW_OUTLINE)? true : false);
416 if (_center) {
417 *_center *= _current_relative_affine;
418 _center_is_set = true;
419 }
421 // If dragging showed content live, sp_selection_apply_affine cannot change the centers
422 // appropriately - it does not know the original positions of the centers (all objects already have
423 // the new bboxes). So we need to reset the centers from our saved array.
424 if (_show != SHOW_OUTLINE && !_current_relative_affine.is_translation()) {
425 for (unsigned i = 0; i < _items_centers.size(); i++) {
426 SPItem *currentItem = _items_centers[i].first;
427 if (currentItem->isCenterSet()) { // only if it's already set
428 currentItem->setCenter (_items_centers[i].second * _current_relative_affine);
429 SP_OBJECT(currentItem)->updateRepr();
430 }
431 }
432 }
434 _items.clear();
435 _items_centers.clear();
437 if (_current_relative_affine.is_translation()) {
438 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
439 _("Move"));
440 } else if (_current_relative_affine.is_scale()) {
441 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
442 _("Scale"));
443 } else if (_current_relative_affine.is_rotation()) {
444 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
445 _("Rotate"));
446 } else {
447 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
448 _("Skew"));
449 }
451 } else {
453 if (_center_is_set) {
454 // we were dragging center; update reprs and commit undoable action
455 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
456 SPItem *it = (SPItem*)SP_OBJECT(l->data);
457 SP_OBJECT(it)->updateRepr();
458 }
459 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
460 _("Set center"));
461 }
463 _items.clear();
464 _items_centers.clear();
465 _updateHandles();
466 }
467 }
469 /* fixme: This is really bad, as we compare positions for each stamp (Lauris) */
470 /* fixme: IMHO the best way to keep sort cache would be to implement timestamping at last */
472 void Inkscape::SelTrans::stamp()
473 {
474 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
476 bool fixup = !_grabbed;
477 if ( fixup && _stamp_cache ) {
478 // TODO - give a proper fix. Simple temproary work-around for the grab() issue
479 g_slist_free(_stamp_cache);
480 _stamp_cache = NULL;
481 }
483 /* stamping mode */
484 if (!_empty) {
485 GSList *l;
486 if (_stamp_cache) {
487 l = _stamp_cache;
488 } else {
489 /* Build cache */
490 l = g_slist_copy((GSList *) selection->itemList());
491 l = g_slist_sort(l, (GCompareFunc) sp_object_compare_position);
492 _stamp_cache = l;
493 }
495 while (l) {
496 SPItem *original_item = SP_ITEM(l->data);
497 Inkscape::XML::Node *original_repr = SP_OBJECT_REPR(original_item);
499 // remember the position of the item
500 gint pos = original_repr->position();
501 // remember parent
502 Inkscape::XML::Node *parent = sp_repr_parent(original_repr);
504 Inkscape::XML::Node *copy_repr = original_repr->duplicate(parent->document());
506 // add the new repr to the parent
507 parent->appendChild(copy_repr);
508 // move to the saved position
509 copy_repr->setPosition(pos > 0 ? pos : 0);
511 SPItem *copy_item = (SPItem *) sp_desktop_document(_desktop)->getObjectByRepr(copy_repr);
513 NR::Matrix const *new_affine;
514 if (_show == SHOW_OUTLINE) {
515 NR::Matrix const i2d(sp_item_i2d_affine(original_item));
516 NR::Matrix const i2dnew( i2d * _current_relative_affine );
517 sp_item_set_i2d_affine(copy_item, i2dnew);
518 new_affine = ©_item->transform;
519 } else {
520 new_affine = &original_item->transform;
521 }
523 sp_item_write_transform(copy_item, copy_repr, *new_affine);
525 if ( copy_item->isCenterSet() && _center ) {
526 copy_item->setCenter(*_center * _current_relative_affine);
527 }
529 Inkscape::GC::release(copy_repr);
530 l = l->next;
531 }
532 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
533 _("Stamp"));
534 }
536 if ( fixup && _stamp_cache ) {
537 // TODO - give a proper fix. Simple temproary work-around for the grab() issue
538 g_slist_free(_stamp_cache);
539 _stamp_cache = NULL;
540 }
541 }
543 void Inkscape::SelTrans::_updateHandles()
544 {
545 if ( !_show_handles || _empty )
546 {
547 sp_remove_handles(_shandle, 8);
548 sp_remove_handles(_rhandle, 8);
549 sp_remove_handles(&_chandle, 1);
550 return;
551 }
553 // center handle
554 if ( _chandle == NULL ) {
555 _chandle = sp_knot_new(_desktop, _("<b>Center</b> of rotation and skewing: drag to reposition; scaling with Shift also uses this center"));
557 _chandle->setShape (SP_CTRL_SHAPE_BITMAP);
558 _chandle->setSize (13);
559 _chandle->setAnchor (handle_center.anchor);
560 _chandle->setMode (SP_CTRL_MODE_XOR);
561 _chandle->setFill(0x00000000, 0x00000000, 0x00000000);
562 _chandle->setStroke(0x000000ff, 0xff0000b0, 0xff0000b0);
563 _chandle->setPixbuf(handles[handle_center.control]);
564 sp_knot_update_ctrl(_chandle);
566 g_signal_connect(G_OBJECT(_chandle), "request",
567 G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle_center);
568 g_signal_connect(G_OBJECT(_chandle), "moved",
569 G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle_center);
570 g_signal_connect(G_OBJECT(_chandle), "grabbed",
571 G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle_center);
572 g_signal_connect(G_OBJECT(_chandle), "ungrabbed",
573 G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle_center);
574 g_signal_connect(G_OBJECT(_chandle), "clicked",
575 G_CALLBACK(sp_sel_trans_handle_click), (gpointer) &handle_center);
576 }
578 sp_remove_handles(&_chandle, 1);
579 if ( _state == STATE_SCALE ) {
580 sp_remove_handles(_rhandle, 8);
581 _showHandles(_shandle, handles_scale, 8,
582 _("<b>Squeeze or stretch</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"),
583 _("<b>Scale</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"));
584 } else {
585 sp_remove_handles(_shandle, 8);
586 _showHandles(_rhandle, handles_rotate, 8,
587 _("<b>Skew</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to skew around the opposite side"),
588 _("<b>Rotate</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to rotate around the opposite corner"));
589 }
591 if (!_center_is_set) {
592 _center = _desktop->selection->center();
593 _center_is_set = true;
594 }
596 if ( _state == STATE_SCALE || !_center ) {
597 sp_knot_hide(_chandle);
598 } else {
599 sp_knot_show(_chandle);
600 sp_knot_moveto(_chandle, &*_center);
601 }
602 }
604 void Inkscape::SelTrans::_updateVolatileState()
605 {
606 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
607 _empty = selection->isEmpty();
609 if (_empty) {
610 return;
611 }
613 //Update the bboxes
614 _bbox = selection->bounds(_snap_bbox_type);
615 _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX);
617 if (!_bbox) {
618 _empty = true;
619 return;
620 }
622 _strokewidth = stroke_average_width (selection->itemList());
623 }
625 static void sp_remove_handles(SPKnot *knot[], gint num)
626 {
627 for (int i = 0; i < num; i++) {
628 if (knot[i] != NULL) {
629 sp_knot_hide(knot[i]);
630 }
631 }
632 }
634 void Inkscape::SelTrans::_showHandles(SPKnot *knot[], SPSelTransHandle const handle[], gint num,
635 gchar const *even_tip, gchar const *odd_tip)
636 {
637 g_return_if_fail( !_empty );
639 for (int i = 0; i < num; i++) {
640 if (knot[i] == NULL) {
641 knot[i] = sp_knot_new(_desktop, i % 2 ? even_tip : odd_tip);
643 knot[i]->setShape (SP_CTRL_SHAPE_BITMAP);
644 knot[i]->setSize (13);
645 knot[i]->setAnchor (handle[i].anchor);
646 knot[i]->setMode (SP_CTRL_MODE_XOR);
647 knot[i]->setFill(0x000000ff, 0x00ff6600, 0x00ff6600); // inversion, green, green
648 knot[i]->setStroke(0x000000ff, 0x000000ff, 0x000000ff); // inversion
649 knot[i]->setPixbuf(handles[handle[i].control]);
650 sp_knot_update_ctrl(knot[i]);
652 g_signal_connect(G_OBJECT(knot[i]), "request",
653 G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle[i]);
654 g_signal_connect(G_OBJECT(knot[i]), "moved",
655 G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle[i]);
656 g_signal_connect(G_OBJECT(knot[i]), "grabbed",
657 G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle[i]);
658 g_signal_connect(G_OBJECT(knot[i]), "ungrabbed",
659 G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle[i]);
660 g_signal_connect(G_OBJECT(knot[i]), "event", G_CALLBACK(sp_seltrans_handle_event), (gpointer) &handle[i]);
661 }
662 sp_knot_show(knot[i]);
664 NR::Point const handle_pt(handle[i].x, handle[i].y);
665 // shouldn't have nullary bbox, but knots
666 g_assert(_bbox);
667 NR::Point p( _bbox->min()
668 + ( _bbox->dimensions()
669 * NR::scale(handle_pt) ) );
671 sp_knot_moveto(knot[i], &p);
672 }
673 }
675 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data)
676 {
677 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleGrab(
678 knot, state, *(SPSelTransHandle const *) data
679 );
680 }
682 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint /*state*/, gpointer /*data*/)
683 {
684 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->ungrab();
685 }
687 static void sp_sel_trans_handle_new_event(SPKnot *knot, NR::Point *position, guint state, gpointer data)
688 {
689 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleNewEvent(
690 knot, position, state, *(SPSelTransHandle const *) data
691 );
692 }
694 static gboolean sp_sel_trans_handle_request(SPKnot *knot, NR::Point *position, guint state, gboolean *data)
695 {
696 return SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleRequest(
697 knot, position, state, *(SPSelTransHandle const *) data
698 );
699 }
701 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data)
702 {
703 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleClick(
704 knot, state, *(SPSelTransHandle const *) data
705 );
706 }
708 void Inkscape::SelTrans::handleClick(SPKnot */*knot*/, guint state, SPSelTransHandle const &handle)
709 {
710 switch (handle.anchor) {
711 case GTK_ANCHOR_CENTER:
712 if (state & GDK_SHIFT_MASK) {
713 // Unset the center position for all selected items
714 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
715 SPItem *it = (SPItem*)(SP_OBJECT(l->data));
716 it->unsetCenter();
717 SP_OBJECT(it)->updateRepr();
718 _center_is_set = false; // center has changed
719 _updateHandles();
720 }
721 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
722 _("Reset center"));
723 }
724 break;
725 default:
726 break;
727 }
728 }
730 void Inkscape::SelTrans::handleGrab(SPKnot *knot, guint /*state*/, SPSelTransHandle const &handle)
731 {
732 switch (handle.anchor) {
733 case GTK_ANCHOR_CENTER:
734 g_object_set(G_OBJECT(_grip),
735 "shape", SP_CTRL_SHAPE_BITMAP,
736 "size", 13.0,
737 NULL);
738 sp_canvas_item_show(_grip);
739 break;
740 default:
741 g_object_set(G_OBJECT(_grip),
742 "shape", SP_CTRL_SHAPE_CROSS,
743 "size", 7.0,
744 NULL);
745 sp_canvas_item_show(_norm);
746 sp_canvas_item_show(_grip);
748 break;
749 }
751 grab(sp_knot_position(knot), handle.x, handle.y, FALSE);
752 }
755 void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, NR::Point *position, guint state, SPSelTransHandle const &handle)
756 {
757 if (!SP_KNOT_IS_GRABBED(knot)) {
758 return;
759 }
761 // in case items have been unhooked from the document, don't
762 // try to continue processing events for them.
763 for (unsigned int i = 0; i < _items.size(); i++) {
764 if (!SP_OBJECT_DOCUMENT(SP_OBJECT(_items[i].first)) ) {
765 return;
766 }
767 }
769 handle.action(this, handle, *position, state);
770 }
773 gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, NR::Point *position, guint state, SPSelTransHandle const &handle)
774 {
775 if (!SP_KNOT_IS_GRABBED(knot)) {
776 return TRUE;
777 }
779 knot->desktop->setPosition(*position);
781 // When holding shift while rotating or skewing, the transformation will be
782 // relative to the point opposite of the handle; otherwise it will be relative
783 // to the center as set for the selection
784 if ((!(state & GDK_SHIFT_MASK) == !(_state == STATE_ROTATE)) && (&handle != &handle_center)) {
785 _origin = _opposite;
786 _origin_for_bboxpoints = _opposite_for_bboxpoints;
787 _origin_for_specpoints = _opposite_for_specpoints;
788 } else if (_center) {
789 _origin = *_center;
790 _origin_for_bboxpoints = *_center;
791 _origin_for_specpoints = *_center;
792 } else {
793 // FIXME
794 return TRUE;
795 }
796 if (handle.request(this, handle, *position, state)) {
797 sp_knot_set_position(knot, position, state);
798 SP_CTRL(_grip)->moveto(*position);
799 SP_CTRL(_norm)->moveto(_origin);
800 }
802 return TRUE;
803 }
806 void Inkscape::SelTrans::_selChanged(Inkscape::Selection */*selection*/)
807 {
808 if (!_grabbed) {
809 // reread in case it changed on the fly:
810 gchar const *prefs_bbox = prefs_get_string_attribute("tools", "bounding_box");
811 _snap_bbox_type = (prefs_bbox != NULL && strcmp(prefs_bbox, "geometric")==0)? SPItem::GEOMETRIC_BBOX : SPItem::APPROXIMATE_BBOX;
812 //SPItem::APPROXIMATE_BBOX will be replaced by SPItem::VISUAL_BBOX, as soon as the latter is implemented properly
814 _updateVolatileState();
815 _current_relative_affine.set_identity();
816 _center_is_set = false; // center(s) may have changed
817 _updateHandles();
818 }
819 }
821 void Inkscape::SelTrans::_selModified(Inkscape::Selection */*selection*/, guint /*flags*/)
822 {
823 if (!_grabbed) {
824 _updateVolatileState();
825 _current_relative_affine.set_identity();
827 // reset internal flag
828 _changed = false;
830 _center_is_set = false; // center(s) may have changed
832 _updateHandles();
833 }
834 }
836 /*
837 * handlers for handle move-request
838 */
840 /** Returns -1 or 1 according to the sign of x. Returns 1 for 0 and NaN. */
841 static double sign(double const x)
842 {
843 return ( x < 0
844 ? -1
845 : 1 );
846 }
848 gboolean sp_sel_trans_scale_request(Inkscape::SelTrans *seltrans,
849 SPSelTransHandle const &, NR::Point &pt, guint state)
850 {
851 return seltrans->scaleRequest(pt, state);
852 }
854 gboolean sp_sel_trans_stretch_request(Inkscape::SelTrans *seltrans,
855 SPSelTransHandle const &handle, NR::Point &pt, guint state)
856 {
857 return seltrans->stretchRequest(handle, pt, state);
858 }
860 gboolean sp_sel_trans_skew_request(Inkscape::SelTrans *seltrans,
861 SPSelTransHandle const &handle, NR::Point &pt, guint state)
862 {
863 return seltrans->skewRequest(handle, pt, state);
864 }
866 gboolean sp_sel_trans_rotate_request(Inkscape::SelTrans *seltrans,
867 SPSelTransHandle const &, NR::Point &pt, guint state)
868 {
869 return seltrans->rotateRequest(pt, state);
870 }
872 gboolean sp_sel_trans_center_request(Inkscape::SelTrans *seltrans,
873 SPSelTransHandle const &, NR::Point &pt, guint state)
874 {
875 return seltrans->centerRequest(pt, state);
876 }
878 gboolean Inkscape::SelTrans::scaleRequest(NR::Point &pt, guint state)
879 {
881 // Calculate the scale factors, which can be either visual or geometric
882 // depending on which type of bbox is currently being used (see preferences -> selector tool)
883 NR::scale default_scale = calcScaleFactors(_point, pt, _origin);
885 // Find the scale factors for the geometric bbox
886 NR::Point pt_geom = _getGeomHandlePos(pt);
887 NR::scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
889 _absolute_affine = NR::identity(); //Initialize the scaler
891 if (state & GDK_MOD1_MASK) { // scale by an integer multiplier/divider
892 // We're scaling either the visual or the geometric bbox here (see the comment above)
893 for ( unsigned int i = 0 ; i < 2 ; i++ ) {
894 if (fabs(default_scale[i]) > 1) {
895 default_scale[i] = round(default_scale[i]);
896 } else if (default_scale[i] != 0) {
897 default_scale[i] = 1/round(1/(MIN(default_scale[i], 10)));
898 }
899 }
900 // Update the knot position
901 pt = _calcAbsAffineDefault(default_scale);
902 // When scaling by an integer, snapping is not needed
903 } else {
904 // In all other cases we should try to snap now
905 SnapManager const &m = _desktop->namedview->snap_manager;
907 /* Get a STL list of the selected items.
908 ** FIXME: this should probably be done by Inkscape::Selection.
909 */
910 std::list<SPItem const*> it;
911 for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
912 it.push_back(reinterpret_cast<SPItem*>(i->data));
913 }
915 std::pair<NR::scale, bool> bb = std::make_pair(NR::scale(1,1), false);
916 std::pair<NR::scale, bool> sn = std::make_pair(NR::scale(1,1), false);
917 NR::Coord bd(NR_HUGE);
918 NR::Coord sd(NR_HUGE);
920 if ((state & GDK_CONTROL_MASK) || _desktop->isToolboxButtonActive ("lock")) {
921 // Scale is locked to a 1:1 aspect ratio, so that s[X] must be made to equal s[Y].
922 //
923 // The aspect-ratio must be locked before snapping
924 if (fabs(default_scale[NR::X]) > fabs(default_scale[NR::Y])) {
925 default_scale[NR::X] = fabs(default_scale[NR::Y]) * sign(default_scale[NR::X]);
926 geom_scale[NR::X] = fabs(geom_scale[NR::Y]) * sign(geom_scale[NR::X]);
927 } else {
928 default_scale[NR::Y] = fabs(default_scale[NR::X]) * sign(default_scale[NR::Y]);
929 geom_scale[NR::Y] = fabs(geom_scale[NR::X]) * sign(geom_scale[NR::Y]);
930 }
932 // Snap along a suitable constraint vector from the origin.
933 bb = m.constrainedSnapScale(Snapper::SNAPPOINT_BBOX, _bbox_points, it, default_scale, _origin_for_bboxpoints);
934 sn = m.constrainedSnapScale(Snapper::SNAPPOINT_NODE, _snap_points, it, geom_scale, _origin_for_specpoints);
936 /* Choose the smaller difference in scale. Since s[X] == s[Y] we can
937 ** just compare difference in s[X].
938 */
939 bd = bb.second ? fabs(bb.first[NR::X] - default_scale[NR::X]) : NR_HUGE;
940 sd = sn.second ? fabs(sn.first[NR::X] - geom_scale[NR::X]) : NR_HUGE;
941 } else {
942 /* Scale aspect ratio is unlocked */
943 bb = m.freeSnapScale(Snapper::SNAPPOINT_BBOX, _bbox_points, it, default_scale, _origin_for_bboxpoints);
944 sn = m.freeSnapScale(Snapper::SNAPPOINT_NODE, _snap_points, it, geom_scale, _origin_for_specpoints);
946 /* Pick the snap that puts us closest to the original scale */
947 bd = bb.second ? fabs(NR::L2(bb.first.point()) - NR::L2(default_scale.point())) : NR_HUGE;
948 sd = sn.second ? fabs(NR::L2(sn.first.point()) - NR::L2(geom_scale.point())) : NR_HUGE;
949 }
951 if (!(bb.second || sn.second)) {
952 // We didn't snap at all! Don't update the handle position, just calculate the new transformation
953 _calcAbsAffineDefault(default_scale);
954 } else if (bd < sd) {
955 // We snapped the bbox (which is either visual or geometric)
956 default_scale = bb.first;
957 // Calculate the new transformation and update the handle position
958 pt = _calcAbsAffineDefault(default_scale);
959 } else {
960 // We snapped the special points (e.g. nodes), which are not at the visual bbox
961 // The handle location however (pt) might however be at the visual bbox, so we
962 // will have to calculate pt taking the stroke width into account
963 geom_scale = sn.first;
964 pt = _calcAbsAffineGeom(geom_scale);
965 }
966 }
968 /* Status text */
969 _message_context.setF(Inkscape::NORMAL_MESSAGE,
970 _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
971 100 * _absolute_affine[0], 100 * _absolute_affine[3]);
973 return TRUE;
974 }
976 gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, NR::Point &pt, guint state)
977 {
978 NR::Dim2 axis, perp;
979 switch (handle.cursor) {
980 case GDK_TOP_SIDE:
981 case GDK_BOTTOM_SIDE:
982 axis = NR::Y;
983 perp = NR::X;
984 break;
985 case GDK_LEFT_SIDE:
986 case GDK_RIGHT_SIDE:
987 axis = NR::X;
988 perp = NR::Y;
989 break;
990 default:
991 g_assert_not_reached();
992 return TRUE;
993 };
995 // Calculate the scale factors, which can be either visual or geometric
996 // depending on which type of bbox is currently being used (see preferences -> selector tool)
997 NR::scale default_scale = calcScaleFactors(_point, pt, _origin);
998 default_scale[perp] = 1;
1000 // Find the scale factors for the geometric bbox
1001 NR::Point pt_geom = _getGeomHandlePos(pt);
1002 NR::scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
1003 geom_scale[perp] = 1;
1005 _absolute_affine = NR::identity(); //Initialize the scaler
1007 if (state & GDK_MOD1_MASK) { // stretch by an integer multiplier/divider
1008 if (fabs(default_scale[axis]) > 1) {
1009 default_scale[axis] = round(default_scale[axis]);
1010 } else if (default_scale[axis] != 0) {
1011 default_scale[axis] = 1/round(1/(MIN(default_scale[axis], 10)));
1012 }
1013 // Calculate the new transformation and update the handle position
1014 pt = _calcAbsAffineDefault(default_scale);
1015 // When stretching by an integer, snapping is not needed
1016 } else {
1017 // In all other cases we should try to snap now
1019 /* Get a STL list of the selected items.
1020 ** FIXME: this should probably be done by Inkscape::Selection.
1021 */
1022 std::list<SPItem const*> it;
1023 for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
1024 it.push_back(reinterpret_cast<SPItem*>(i->data));
1025 }
1027 SnapManager const &m = _desktop->namedview->snap_manager;
1029 std::pair<NR::Coord, bool> bb = std::make_pair(NR_HUGE, false);
1030 std::pair<NR::Coord, bool> sn = std::make_pair(NR_HUGE, false);
1031 NR::Coord bd(NR_HUGE);
1032 NR::Coord sd(NR_HUGE);
1034 bool symmetrical = state & GDK_CONTROL_MASK;
1036 bb = m.constrainedSnapStretch(Snapper::SNAPPOINT_BBOX, _bbox_points, it, default_scale[axis], _origin_for_bboxpoints, axis, symmetrical);
1037 sn = m.constrainedSnapStretch(Snapper::SNAPPOINT_NODE, _snap_points, it, geom_scale[axis], _origin_for_specpoints, axis, symmetrical);
1039 if (bb.second) {
1040 // We snapped the bbox (which is either visual or geometric)
1041 bd = fabs(bb.first - default_scale[axis]);
1042 default_scale[axis] = bb.first;
1043 }
1045 if (sn.second) {
1046 sd = fabs(sn.first - geom_scale[axis]);
1047 geom_scale[axis] = sn.first;
1048 }
1050 if (symmetrical) {
1051 // on ctrl, apply symmetrical scaling instead of stretching
1052 // Preserve aspect ratio, but never flip in the dimension not being edited (by using fabs())
1053 default_scale[perp] = fabs(default_scale[axis]);
1054 geom_scale[perp] = fabs(geom_scale[axis]);
1055 }
1057 if (!(bb.second || sn.second)) {
1058 // We didn't snap at all! Don't update the handle position, just calculate the new transformation
1059 _calcAbsAffineDefault(default_scale);
1060 } else if (bd < sd) {
1061 // Calculate the new transformation and update the handle position
1062 pt = _calcAbsAffineDefault(default_scale);
1063 } else {
1064 // We snapped the special points (e.g. nodes), which are not at the visual bbox
1065 // The handle location however (pt) might however be at the visual bbox, so we
1066 // will have to calculate pt taking the stroke width into account
1067 pt = _calcAbsAffineGeom(geom_scale);
1068 }
1069 }
1071 // status text
1072 _message_context.setF(Inkscape::NORMAL_MESSAGE,
1073 _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1074 100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1076 return TRUE;
1077 }
1079 gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, NR::Point &pt, guint state)
1080 {
1081 /* When skewing (or rotating):
1082 * 1) the stroke width will not change. This makes life much easier because we don't have to
1083 * account for that (like for scaling or stretching). As a consequence, all points will
1084 * have the same origin for the transformation and for the snapping.
1085 * 2) When holding shift, the transformation will be relative to the point opposite of
1086 * the handle; otherwise it will be relative to the center as set for the selection
1087 */
1089 NR::Dim2 dim_a;
1090 NR::Dim2 dim_b;
1092 switch (handle.cursor) {
1093 case GDK_SB_H_DOUBLE_ARROW:
1094 dim_a = NR::Y;
1095 dim_b = NR::X;
1096 break;
1097 case GDK_SB_V_DOUBLE_ARROW:
1098 dim_a = NR::X;
1099 dim_b = NR::Y;
1100 break;
1101 default:
1102 g_assert_not_reached();
1103 abort();
1104 break;
1105 }
1107 NR::Point const initial_delta = _point - _origin;
1109 if (fabs(initial_delta[dim_a]) < 1e-15) {
1110 return false;
1111 }
1113 // Calculate the scale factors, which can be either visual or geometric
1114 // depending on which type of bbox is currently being used (see preferences -> selector tool)
1115 NR::scale scale = calcScaleFactors(_point, pt, _origin, false);
1116 NR::scale skew = calcScaleFactors(_point, pt, _origin, true);
1117 scale[dim_b] = 1;
1118 skew[dim_b] = 1;
1120 if (fabs(scale[dim_a]) < 1) {
1121 // Prevent shrinking of the selected object, while allowing mirroring
1122 scale[dim_a] = sign(scale[dim_a]);
1123 } else {
1124 // Allow expanding of the selected object by integer multiples
1125 scale[dim_a] = floor(scale[dim_a] + 0.5);
1126 }
1128 double radians = atan(skew[dim_a] / scale[dim_a]);
1130 if (state & GDK_CONTROL_MASK) {
1131 // Snap to defined angle increments
1132 int snaps = prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12);
1133 if (snaps) {
1134 double sections = floor(radians * snaps / M_PI + .5);
1135 if (fabs(sections) >= snaps / 2) {
1136 sections = sign(sections) * (snaps / 2 - 1);
1137 }
1138 radians = (M_PI / snaps) * sections;
1139 }
1140 skew[dim_a] = tan(radians) * scale[dim_a];
1141 } else {
1142 // Snap to objects, grids, guides
1144 /* Get a STL list of the selected items.
1145 ** FIXME: this should probably be done by Inkscape::Selection.
1146 */
1147 std::list<SPItem const*> it;
1148 for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
1149 it.push_back(reinterpret_cast<SPItem*>(i->data));
1150 }
1152 SnapManager const &m = _desktop->namedview->snap_manager;
1154 std::pair<NR::Coord, bool> bb = m.freeSnapSkew(Inkscape::Snapper::SNAPPOINT_BBOX, _bbox_points, it, skew[dim_a], _origin, dim_b);
1155 std::pair<NR::Coord, bool> sn = m.freeSnapSkew(Inkscape::Snapper::SNAPPOINT_NODE, _snap_points, it, skew[dim_a], _origin, dim_b);
1157 if (bb.second || sn.second) {
1158 // We snapped something, so change the skew to reflect it
1159 NR::Coord const bd = bb.second ? bb.first : NR_HUGE;
1160 NR::Coord const sd = sn.second ? sn.first : NR_HUGE;
1161 skew[dim_a] = std::min(bd, sd);
1162 }
1163 }
1165 // Update the handle position
1166 pt[dim_b] = initial_delta[dim_a] * skew[dim_a] + _point[dim_b];
1167 pt[dim_a] = initial_delta[dim_a] * scale[dim_a] + _origin[dim_a];
1169 // Calculate the relative affine
1170 _relative_affine = NR::identity();
1171 _relative_affine[2*dim_a + dim_a] = (pt[dim_a] - _origin[dim_a]) / initial_delta[dim_a];
1172 _relative_affine[2*dim_a + (dim_b)] = (pt[dim_b] - _point[dim_b]) / initial_delta[dim_a];
1173 _relative_affine[2*(dim_b) + (dim_a)] = 0;
1174 _relative_affine[2*(dim_b) + (dim_b)] = 1;
1176 for (int i = 0; i < 2; i++) {
1177 if (fabs(_relative_affine[3*i]) < 1e-15) {
1178 _relative_affine[3*i] = 1e-15;
1179 }
1180 }
1182 // Update the status text
1183 double degrees = mod360symm(Geom::rad_to_deg(radians));
1184 _message_context.setF(Inkscape::NORMAL_MESSAGE,
1185 // TRANSLATORS: don't modify the first ";"
1186 // (it will NOT be displayed as ";" - only the second one will be)
1187 _("<b>Skew</b>: %0.2f°; with <b>Ctrl</b> to snap angle"),
1188 degrees);
1190 return TRUE;
1191 }
1193 gboolean Inkscape::SelTrans::rotateRequest(NR::Point &pt, guint state)
1194 {
1195 /* When rotating (or skewing):
1196 * 1) the stroke width will not change. This makes life much easier because we don't have to
1197 * account for that (like for scaling or stretching). As a consequence, all points will
1198 * have the same origin for the transformation and for the snapping.
1199 * 2) When holding shift, the transformation will be relative to the point opposite of
1200 * the handle; otherwise it will be relative to the center as set for the selection
1201 */
1203 int snaps = prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12);
1205 // rotate affine in rotate
1206 NR::Point const d1 = _point - _origin;
1207 NR::Point const d2 = pt - _origin;
1209 NR::Coord const h1 = NR::L2(d1); // initial radius
1210 if (h1 < 1e-15) return FALSE;
1211 NR::Point q1 = d1 / h1; // normalized initial vector to handle
1212 NR::Coord const h2 = NR::L2(d2); // new radius
1213 if (fabs(h2) < 1e-15) return FALSE;
1214 NR::Point q2 = d2 / h2; // normalized new vector to handle
1216 double radians;
1217 if (state & GDK_CONTROL_MASK) {
1218 // Snap to defined angle increments
1219 double cos_t = NR::dot(q1, q2);
1220 double sin_t = NR::dot(NR::rot90(q1), q2);
1221 radians = atan2(sin_t, cos_t);
1222 if (snaps) {
1223 radians = ( M_PI / snaps ) * floor( radians * snaps / M_PI + .5 );
1224 }
1225 q1 = NR::Point(1, 0);
1226 q2 = NR::Point(cos(radians), sin(radians));
1227 } else {
1228 radians = atan2(NR::dot(NR::rot90(d1), d2),
1229 NR::dot(d1, d2));
1230 }
1232 NR::rotate const r1(q1);
1233 NR::rotate const r2(q2);
1235 // Calculate the relative affine
1236 _relative_affine = NR::Matrix(r2/r1);
1238 // Update the handle position
1239 pt = _point * NR::translate(-_origin) * _relative_affine * NR::translate(_origin);
1241 // Update the status text
1242 double degrees = mod360symm(Geom::rad_to_deg(radians));
1243 _message_context.setF(Inkscape::NORMAL_MESSAGE,
1244 // TRANSLATORS: don't modify the first ";"
1245 // (it will NOT be displayed as ";" - only the second one will be)
1246 _("<b>Rotate</b>: %0.2f°; with <b>Ctrl</b> to snap angle"), degrees);
1248 return TRUE;
1249 }
1251 gboolean Inkscape::SelTrans::centerRequest(NR::Point &pt, guint state)
1252 {
1253 SnapManager const &m = _desktop->namedview->snap_manager;
1254 pt = m.freeSnap(Snapper::SNAPPOINT_NODE, pt, NULL).getPoint();
1256 if (state & GDK_CONTROL_MASK) {
1257 if ( fabs(_point[NR::X] - pt[NR::X]) > fabs(_point[NR::Y] - pt[NR::Y]) ) {
1258 pt[NR::Y] = _point[NR::Y];
1259 } else {
1260 pt[NR::X] = _point[NR::X];
1261 }
1262 }
1264 if ( !(state & GDK_SHIFT_MASK) && _bbox ) {
1265 // screen pixels to snap center to bbox
1266 #define SNAP_DIST 5
1267 // FIXME: take from prefs
1268 double snap_dist = SNAP_DIST / _desktop->current_zoom();
1270 for (int i = 0; i < 2; i++) {
1271 if (fabs(pt[i] - _bbox->min()[i]) < snap_dist) {
1272 pt[i] = _bbox->min()[i];
1273 }
1274 if (fabs(pt[i] - _bbox->midpoint()[i]) < snap_dist) {
1275 pt[i] = _bbox->midpoint()[i];
1276 }
1277 if (fabs(pt[i] - _bbox->max()[i]) < snap_dist) {
1278 pt[i] = _bbox->max()[i];
1279 }
1280 }
1281 }
1283 // status text
1284 GString *xs = SP_PX_TO_METRIC_STRING(pt[NR::X], _desktop->namedview->getDefaultMetric());
1285 GString *ys = SP_PX_TO_METRIC_STRING(pt[NR::Y], _desktop->namedview->getDefaultMetric());
1286 _message_context.setF(Inkscape::NORMAL_MESSAGE, _("Move <b>center</b> to %s, %s"), xs->str, ys->str);
1287 g_string_free(xs, FALSE);
1288 g_string_free(ys, FALSE);
1290 return TRUE;
1291 }
1293 /*
1294 * handlers for handle movement
1295 *
1296 */
1298 void sp_sel_trans_stretch(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, NR::Point &pt, guint state)
1299 {
1300 seltrans->stretch(handle, pt, state);
1301 }
1303 void sp_sel_trans_scale(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
1304 {
1305 seltrans->scale(pt, state);
1306 }
1308 void sp_sel_trans_skew(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, NR::Point &pt, guint state)
1309 {
1310 seltrans->skew(handle, pt, state);
1311 }
1313 void sp_sel_trans_rotate(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
1314 {
1315 seltrans->rotate(pt, state);
1316 }
1318 void Inkscape::SelTrans::stretch(SPSelTransHandle const &handle, NR::Point &pt, guint state)
1319 {
1320 transform(_absolute_affine, NR::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1321 }
1323 void Inkscape::SelTrans::scale(NR::Point &pt, guint /*state*/)
1324 {
1325 transform(_absolute_affine, NR::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1326 }
1328 void Inkscape::SelTrans::skew(SPSelTransHandle const &handle, NR::Point &pt, guint /*state*/)
1329 {
1330 transform(_relative_affine, _origin);
1331 }
1333 void Inkscape::SelTrans::rotate(NR::Point &pt, guint /*state*/)
1334 {
1335 transform(_relative_affine, _origin);
1336 }
1338 void sp_sel_trans_center(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint /*state*/)
1339 {
1340 seltrans->setCenter(pt);
1341 }
1344 void Inkscape::SelTrans::moveTo(NR::Point const &xy, guint state)
1345 {
1346 SnapManager const &m = _desktop->namedview->snap_manager;
1348 /* The amount that we've moved by during this drag */
1349 NR::Point dxy = xy - _point;
1351 /* Get a STL list of the selected items.
1352 ** FIXME: this should probably be done by Inkscape::Selection.
1353 */
1354 std::list<SPItem const*> it;
1355 for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
1356 it.push_back(reinterpret_cast<SPItem*>(i->data));
1357 }
1359 bool const alt = (state & GDK_MOD1_MASK);
1360 bool const control = (state & GDK_CONTROL_MASK);
1361 bool const shift = (state & GDK_SHIFT_MASK);
1363 if (alt) {
1365 /* Alt pressed means keep offset: snap the moved distance to the grid.
1366 ** FIXME: this will snap to more than just the grid, nowadays.
1367 */
1369 dxy = m.freeSnap(Snapper::SNAPPOINT_NODE, dxy, NULL).getPoint();
1371 } else if (!shift) {
1373 /* We're snapping to things, possibly with a constraint to horizontal or
1374 ** vertical movement. Obtain a list of possible translations and then
1375 ** pick the smallest.
1376 */
1378 /* This will be our list of possible translations */
1379 std::list<std::pair<NR::Point, bool> > s;
1381 if (control) {
1383 /* Snap to things, and also constrain to horizontal or vertical movement */
1385 for (unsigned int dim = 0; dim < 2; dim++) {
1386 s.push_back(m.constrainedSnapTranslation(Inkscape::Snapper::SNAPPOINT_BBOX,
1387 _bbox_points,
1388 it,
1389 Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1390 dxy));
1392 s.push_back(m.constrainedSnapTranslation(Inkscape::Snapper::SNAPPOINT_NODE,
1393 _snap_points,
1394 it,
1395 Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1396 dxy));
1397 }
1399 } else {
1401 // Let's leave this timer code here for a while. I'll probably need it in the near future (Diederik van Lierop)
1402 /* GTimeVal starttime;
1403 GTimeVal endtime;
1404 g_get_current_time(&starttime); */
1406 /* Snap to things with no constraint */
1407 s.push_back(m.freeSnapTranslation(Inkscape::Snapper::SNAPPOINT_BBOX,
1408 _bbox_points, it, dxy));
1409 s.push_back(m.freeSnapTranslation(Inkscape::Snapper::SNAPPOINT_NODE,
1410 _snap_points, it, dxy));
1412 /*g_get_current_time(&endtime);
1413 double elapsed = ((((double)endtime.tv_sec - starttime.tv_sec) * G_USEC_PER_SEC + (endtime.tv_usec - starttime.tv_usec))) / 1000.0;
1414 std::cout << "Time spent snapping: " << elapsed << std::endl; */
1415 }
1417 /* Pick one */
1418 NR::Coord best = NR_HUGE;
1419 for (std::list<std::pair<NR::Point, bool> >::const_iterator i = s.begin(); i != s.end(); i++) {
1420 if (i->second) {
1421 NR::Coord const m = NR::L2(i->first);
1422 if (m < best) {
1423 best = m;
1424 dxy = i->first;
1425 }
1426 }
1427 }
1428 }
1430 if (control) {
1431 /* Ensure that the horizontal and vertical constraint has been applied */
1432 if (fabs(dxy[NR::X]) > fabs(dxy[NR::Y])) {
1433 dxy[NR::Y] = 0;
1434 } else {
1435 dxy[NR::X] = 0;
1436 }
1437 }
1439 NR::Matrix const move((NR::translate(dxy)));
1440 NR::Point const norm(0, 0);
1441 transform(move, norm);
1443 // status text
1444 GString *xs = SP_PX_TO_METRIC_STRING(dxy[NR::X], _desktop->namedview->getDefaultMetric());
1445 GString *ys = SP_PX_TO_METRIC_STRING(dxy[NR::Y], _desktop->namedview->getDefaultMetric());
1446 _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);
1447 g_string_free(xs, TRUE);
1448 g_string_free(ys, TRUE);
1449 }
1451 // Given a location of a handle at the visual bounding box, find the corresponding location at the
1452 // geometrical bounding box
1453 NR::Point Inkscape::SelTrans::_getGeomHandlePos(NR::Point const &visual_handle_pos)
1454 {
1455 if ( _snap_bbox_type == SPItem::GEOMETRIC_BBOX) {
1456 // When the selector tool is using geometric bboxes, then the handle is already
1457 // located at one of the geometric bbox corners
1458 return visual_handle_pos;
1459 }
1461 if (!_geometric_bbox) {
1462 //_getGeomHandlePos() can only be used after _geometric_bbox has been defined!
1463 return visual_handle_pos;
1464 }
1466 // Using the NR::Rect constructor below ensures that "min() < max()", which is important
1467 // because this will also hold for _bbox, and which is required for get_scale_transform_with_stroke()
1468 NR::Rect new_bbox = NR::Rect(_origin_for_bboxpoints, visual_handle_pos); // new visual bounding box
1469 // Please note that the new_bbox might in fact be just a single line, for example when stretching (in
1470 // which case the handle and origin will be aligned vertically or horizontally)
1471 NR::Point normalized_handle_pos = (visual_handle_pos - new_bbox.min()) * NR::scale(new_bbox.dimensions()).inverse();
1473 // Calculate the absolute affine while taking into account the scaling of the stroke width
1474 int transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1475 NR::Matrix abs_affine = get_scale_transform_with_stroke (*_bbox, _strokewidth, transform_stroke,
1476 new_bbox.min()[NR::X], new_bbox.min()[NR::Y], new_bbox.max()[NR::X], new_bbox.max()[NR::Y]);
1478 // Calculate the scaled geometrical bbox
1479 NR::Rect new_geom_bbox = NR::Rect(_geometric_bbox->min() * abs_affine, _geometric_bbox->max() * abs_affine);
1480 // Find the location of the handle on this new geometrical bbox
1481 return normalized_handle_pos * NR::scale(new_geom_bbox.dimensions()) + new_geom_bbox.min(); //new position of the geometric handle
1482 }
1484 NR::scale Inkscape::calcScaleFactors(NR::Point const &initial_point, NR::Point const &new_point, NR::Point const &origin, bool const skew)
1485 {
1486 // Work out the new scale factors for the bbox
1488 NR::Point const initial_delta = initial_point - origin;
1489 NR::Point const new_delta = new_point - origin;
1490 NR::Point const offset = new_point - initial_point;
1491 NR::scale scale(1, 1);
1493 for ( unsigned int i = 0 ; i < 2 ; i++ ) {
1494 if ( fabs(initial_delta[i]) > 1e-6 ) {
1495 if (skew) {
1496 scale[i] = offset[1-i] / initial_delta[i];
1497 } else {
1498 scale[i] = new_delta[i] / initial_delta[i];
1499 }
1500 }
1501 }
1503 return scale;
1504 }
1506 // Only for scaling/stretching
1507 NR::Point Inkscape::SelTrans::_calcAbsAffineDefault(NR::scale const default_scale)
1508 {
1509 NR::Matrix abs_affine = NR::translate(-_origin) * NR::Matrix(default_scale) * NR::translate(_origin);
1510 NR::Point new_bbox_min = _approximate_bbox->min() * abs_affine;
1511 NR::Point new_bbox_max = _approximate_bbox->max() * abs_affine;
1513 int transform_stroke = false;
1514 gdouble strokewidth = 0;
1516 if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
1517 transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1518 strokewidth = _strokewidth;
1519 }
1521 _absolute_affine = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
1522 new_bbox_min[NR::X], new_bbox_min[NR::Y], new_bbox_max[NR::X], new_bbox_max[NR::Y]);
1524 // return the new handle position
1525 return ( _point - _origin ) * default_scale + _origin;
1526 }
1528 // Only for scaling/stretching
1529 NR::Point Inkscape::SelTrans::_calcAbsAffineGeom(NR::scale const geom_scale)
1530 {
1531 _relative_affine = NR::Matrix(geom_scale);
1532 _absolute_affine = NR::translate(-_origin_for_specpoints) * _relative_affine * NR::translate(_origin_for_specpoints);
1534 bool const transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1535 NR::Rect visual_bbox = get_visual_bbox(_geometric_bbox, _absolute_affine, _strokewidth, transform_stroke);
1537 // return the new handle position
1538 return visual_bbox.min() + visual_bbox.dimensions() * NR::scale(_handle_x, _handle_y);
1539 }
1542 /*
1543 Local Variables:
1544 mode:c++
1545 c-file-style:"stroustrup"
1546 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1547 indent-tabs-mode:nil
1548 fill-column:99
1549 End:
1550 */
1551 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :