1 #define __SELTRANS_C__
3 /*
4 * Helper object for transforming selected items
5 *
6 * Authors:
7 * Lauris Kaplinski <lauris@kaplinski.com>
8 * bulia byak <buliabyak@users.sf.net>
9 * Carl Hetherington <inkscape@carlh.net>
10 * Diederik van Lierop <mail@diedenrezi.nl>
11 *
12 * Copyright (C) 1999-2002 Lauris Kaplinski
13 * Copyright (C) 1999-2008 Authors
14 *
15 * Released under GNU GPL, read the file 'COPYING' for more information
16 */
18 #ifdef HAVE_CONFIG_H
19 # include <config.h>
20 #endif
21 #include <cstring>
22 #include <string>
24 #include <libnr/nr-matrix-ops.h>
25 #include <libnr/nr-matrix-translate-ops.h>
26 #include <libnr/nr-rotate-ops.h>
27 #include <libnr/nr-scale-ops.h>
28 #include <libnr/nr-translate-matrix-ops.h>
29 #include <libnr/nr-translate-ops.h>
30 #include <gdk/gdkkeysyms.h>
31 #include "document.h"
32 #include "sp-namedview.h"
33 #include "desktop.h"
34 #include "desktop-handles.h"
35 #include "desktop-style.h"
36 #include "knot.h"
37 #include "snap.h"
38 #include "selection.h"
39 #include "select-context.h"
40 #include "sp-item.h"
41 #include "sp-item-transform.h"
42 #include "seltrans-handles.h"
43 #include "seltrans.h"
44 #include "selection-chemistry.h"
45 #include "sp-metrics.h"
46 #include "verbs.h"
47 #include <glibmm/i18n.h>
48 #include "display/sp-ctrlline.h"
49 #include "prefs-utils.h"
50 #include "xml/repr.h"
51 #include "mod360.h"
52 #include "2geom/angle.h"
53 #include "display/snap-indicator.h"
55 #include "isnan.h" //temp fix. make sure included last
57 static void sp_remove_handles(SPKnot *knot[], gint num);
59 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data);
60 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint state, gpointer data);
61 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data);
62 static void sp_sel_trans_handle_new_event(SPKnot *knot, NR::Point *position, guint32 state, gpointer data);
63 static gboolean sp_sel_trans_handle_request(SPKnot *knot, NR::Point *p, guint state, gboolean *data);
65 extern GdkPixbuf *handles[];
67 static gboolean sp_seltrans_handle_event(SPKnot *knot, GdkEvent *event, gpointer)
68 {
69 switch (event->type) {
70 case GDK_MOTION_NOTIFY:
71 break;
72 case GDK_KEY_PRESS:
73 if (get_group0_keyval (&event->key) == GDK_space) {
74 /* stamping mode: both mode(show content and outline) operation with knot */
75 if (!SP_KNOT_IS_GRABBED(knot)) {
76 return FALSE;
77 }
78 SPDesktop *desktop = knot->desktop;
79 Inkscape::SelTrans *seltrans = SP_SELECT_CONTEXT(desktop->event_context)->_seltrans;
80 seltrans->stamp();
81 return TRUE;
82 }
83 break;
84 default:
85 break;
86 }
88 return FALSE;
89 }
91 Inkscape::SelTrans::SelTrans(SPDesktop *desktop) :
92 _desktop(desktop),
93 _selcue(desktop),
94 _state(STATE_SCALE),
95 _show(SHOW_CONTENT),
96 _grabbed(false),
97 _show_handles(true),
98 _bbox(NR::Nothing()),
99 _approximate_bbox(NR::Nothing()),
100 _absolute_affine(NR::scale(1,1)),
101 _opposite(NR::Point(0,0)),
102 _opposite_for_specpoints(NR::Point(0,0)),
103 _opposite_for_bboxpoints(NR::Point(0,0)),
104 _origin_for_specpoints(NR::Point(0,0)),
105 _origin_for_bboxpoints(NR::Point(0,0)),
106 _chandle(NULL),
107 _stamp_cache(NULL),
108 _message_context(desktop->messageStack())
109 {
110 int prefs_bbox = prefs_get_int_attribute("tools", "bounding_box", 0);
111 _snap_bbox_type = (prefs_bbox ==0)?
112 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
114 g_return_if_fail(desktop != NULL);
116 for (int i = 0; i < 8; i++) {
117 _shandle[i] = NULL;
118 _rhandle[i] = NULL;
119 }
121 _updateVolatileState();
122 _current_relative_affine.set_identity();
124 _center_is_set = false; // reread _center from items, or set to bbox midpoint
126 _updateHandles();
128 _selection = sp_desktop_selection(desktop);
130 _norm = sp_canvas_item_new(sp_desktop_controls(desktop),
131 SP_TYPE_CTRL,
132 "anchor", GTK_ANCHOR_CENTER,
133 "mode", SP_CTRL_MODE_COLOR,
134 "shape", SP_CTRL_SHAPE_BITMAP,
135 "size", 13.0,
136 "filled", TRUE,
137 "fill_color", 0x00000000,
138 "stroked", TRUE,
139 "stroke_color", 0x000000a0,
140 "pixbuf", handles[12],
141 NULL);
143 _grip = sp_canvas_item_new(sp_desktop_controls(desktop),
144 SP_TYPE_CTRL,
145 "anchor", GTK_ANCHOR_CENTER,
146 "mode", SP_CTRL_MODE_XOR,
147 "shape", SP_CTRL_SHAPE_CROSS,
148 "size", 7.0,
149 "filled", TRUE,
150 "fill_color", 0xffffff7f,
151 "stroked", TRUE,
152 "stroke_color", 0xffffffff,
153 "pixbuf", handles[12],
154 NULL);
156 sp_canvas_item_hide(_grip);
157 sp_canvas_item_hide(_norm);
159 for (int i = 0; i < 4; i++) {
160 _l[i] = sp_canvas_item_new(sp_desktop_controls(desktop), SP_TYPE_CTRLLINE, NULL);
161 sp_canvas_item_hide(_l[i]);
162 }
164 _sel_changed_connection = _selection->connectChanged(
165 sigc::mem_fun(*this, &Inkscape::SelTrans::_selChanged)
166 );
168 _sel_modified_connection = _selection->connectModified(
169 sigc::mem_fun(*this, &Inkscape::SelTrans::_selModified)
170 );
171 }
173 Inkscape::SelTrans::~SelTrans()
174 {
175 _sel_changed_connection.disconnect();
176 _sel_modified_connection.disconnect();
178 for (unsigned int i = 0; i < 8; i++) {
179 if (_shandle[i]) {
180 g_object_unref(G_OBJECT(_shandle[i]));
181 _shandle[i] = NULL;
182 }
183 if (_rhandle[i]) {
184 g_object_unref(G_OBJECT(_rhandle[i]));
185 _rhandle[i] = NULL;
186 }
187 }
188 if (_chandle) {
189 g_object_unref(G_OBJECT(_chandle));
190 _chandle = NULL;
191 }
193 if (_norm) {
194 gtk_object_destroy(GTK_OBJECT(_norm));
195 _norm = NULL;
196 }
197 if (_grip) {
198 gtk_object_destroy(GTK_OBJECT(_grip));
199 _grip = NULL;
200 }
201 for (int i = 0; i < 4; i++) {
202 if (_l[i]) {
203 gtk_object_destroy(GTK_OBJECT(_l[i]));
204 _l[i] = NULL;
205 }
206 }
208 for (unsigned i = 0; i < _items.size(); i++) {
209 sp_object_unref(SP_OBJECT(_items[i]), NULL);
210 }
212 _items.clear();
213 _items_const.clear();
214 _items_affines.clear();
215 _items_centers.clear();
216 }
218 void Inkscape::SelTrans::resetState()
219 {
220 _state = STATE_SCALE;
221 }
223 void Inkscape::SelTrans::increaseState()
224 {
225 if (_state == STATE_SCALE) {
226 _state = STATE_ROTATE;
227 } else {
228 _state = STATE_SCALE;
229 }
231 _center_is_set = true; // no need to reread center
233 _updateHandles();
234 }
236 void Inkscape::SelTrans::setCenter(NR::Point const &p)
237 {
238 _center = p;
239 _center_is_set = true;
241 // Write the new center position into all selected items
242 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
243 SPItem *it = (SPItem*)SP_OBJECT(l->data);
244 it->setCenter(p);
245 // only set the value; updating repr and document_done will be done once, on ungrab
246 }
248 _updateHandles();
249 }
251 void Inkscape::SelTrans::grab(NR::Point const &p, gdouble x, gdouble y, bool show_handles)
252 {
253 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
255 g_return_if_fail(!_grabbed);
257 _grabbed = true;
258 _show_handles = show_handles;
259 _updateVolatileState();
260 _current_relative_affine.set_identity();
262 _changed = false;
264 if (_empty) {
265 return;
266 }
268 for (GSList const *l = selection->itemList(); l; l = l->next) {
269 SPItem *it = (SPItem *)sp_object_ref(SP_OBJECT(l->data), NULL);
270 _items.push_back(it);
271 _items_const.push_back(it);
272 _items_affines.push_back(sp_item_i2d_affine(it));
273 _items_centers.push_back(it->getCenter()); // for content-dragging, we need to remember original centers
274 }
276 _handle_x = x;
277 _handle_y = y;
279 // The selector tool should snap the bbox, special snappoints, and path nodes
280 // (The special points are the handles, center, rotation axis, font baseline, ends of spiral, etc.)
282 // First, determine the bounding box for snapping ...
283 _bbox = selection->bounds(_snap_bbox_type);
284 _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX); // Used for correctly scaling the strokewidth
285 _geometric_bbox = selection->bounds(SPItem::GEOMETRIC_BBOX);
286 _point = p;
287 if (_geometric_bbox) {
288 _point_geom = _geometric_bbox->min() + _geometric_bbox->dimensions() * NR::scale(x, y);
289 } else {
290 _point_geom = p;
291 }
293 // Next, get all points to consider for snapping
294 SnapManager const &m = _desktop->namedview->snap_manager;
295 _snap_points = selection->getSnapPoints(m.getIncludeItemCenter());
296 std::vector<NR::Point> snap_points_hull = selection->getSnapPointsConvexHull();
297 if (_snap_points.size() > 100) {
298 /* Snapping a huge number of nodes will take way too long, so limit the number of snappable nodes
299 An average user would rarely ever try to snap such a large number of nodes anyway, because
300 (s)he could hardly discern which node would be snapping */
301 _snap_points = snap_points_hull;
302 // Unfortunately, by now we will have lost the font-baseline snappoints :-(
303 }
305 // Find bbox hulling all special points, which excludes stroke width. Here we need to include the
306 // path nodes, for example because a rectangle which has been converted to a path doesn't have
307 // any other special points
308 NR::Rect snap_points_bbox;
309 if ( snap_points_hull.empty() == false ) {
310 std::vector<NR::Point>::iterator i = snap_points_hull.begin();
311 snap_points_bbox = NR::Rect(*i, *i);
312 i++;
313 while (i != snap_points_hull.end()) {
314 snap_points_bbox.expandTo(*i);
315 i++;
316 }
317 }
319 _bbox_points.clear();
320 if (_bbox) {
321 // ... and add the bbox corners to _bbox_points
322 for ( unsigned i = 0 ; i < 4 ; i++ ) {
323 _bbox_points.push_back(_bbox->corner(i));
324 }
325 // There are two separate "opposites" (i.e. opposite w.r.t. the handle being dragged):
326 // - one for snapping the boundingbox, which can be either visual or geometric
327 // - one for snapping the special points
328 // The "opposite" in case of a geometric boundingbox always coincides with the "opposite" for the special points
329 // These distinct "opposites" are needed in the snapmanager to avoid bugs such as #sf1540195 (in which
330 // a box is caught between two guides)
331 _opposite_for_bboxpoints = _bbox->min() + _bbox->dimensions() * NR::scale(1-x, 1-y);
332 _opposite_for_specpoints = snap_points_bbox.min() + snap_points_bbox.dimensions() * NR::scale(1-x, 1-y);
333 _opposite = _opposite_for_bboxpoints;
334 }
336 // The lines below are usefull for debugging any snapping issues, as they'll spit out all points that are considered for snapping
338 /*std::cout << "Number of snap points: " << _snap_points.size() << std::endl;
339 for (std::vector<NR::Point>::const_iterator i = _snap_points.begin(); i != _snap_points.end(); i++)
340 {
341 std::cout << " " << *i << std::endl;
342 }
344 std::cout << "Number of bbox points: " << _bbox_points.size() << std::endl;
345 for (std::vector<NR::Point>::const_iterator i = _bbox_points.begin(); i != _bbox_points.end(); i++)
346 {
347 std::cout << " " << *i << std::endl;
348 }*/
350 if ((x != -1) && (y != -1)) {
351 sp_canvas_item_show(_norm);
352 sp_canvas_item_show(_grip);
353 }
355 if (_show == SHOW_OUTLINE) {
356 for (int i = 0; i < 4; i++)
357 sp_canvas_item_show(_l[i]);
358 }
360 _updateHandles();
361 g_return_if_fail(_stamp_cache == NULL);
362 }
364 void Inkscape::SelTrans::transform(NR::Matrix const &rel_affine, NR::Point const &norm)
365 {
366 g_return_if_fail(_grabbed);
367 g_return_if_fail(!_empty);
369 NR::Matrix const affine( NR::translate(-norm) * rel_affine * NR::translate(norm) );
371 if (_show == SHOW_CONTENT) {
372 // update the content
373 for (unsigned i = 0; i < _items.size(); i++) {
374 SPItem &item = *_items[i];
375 NR::Matrix const &prev_transform = _items_affines[i];
376 sp_item_set_i2d_affine(&item, prev_transform * affine);
377 }
378 } else {
379 if (_bbox) {
380 NR::Point p[4];
381 /* update the outline */
382 for (unsigned i = 0 ; i < 4 ; i++) {
383 p[i] = _bbox->corner(i) * affine;
384 }
385 for (unsigned i = 0 ; i < 4 ; i++) {
386 sp_ctrlline_set_coords(SP_CTRLLINE(_l[i]), p[i], p[(i+1)%4]);
387 }
388 }
389 }
391 _current_relative_affine = affine;
392 _changed = true;
393 _updateHandles();
394 }
396 void Inkscape::SelTrans::ungrab()
397 {
398 g_return_if_fail(_grabbed);
399 _grabbed = false;
400 _show_handles = true;
402 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
403 _updateVolatileState();
405 for (unsigned i = 0; i < _items.size(); i++) {
406 sp_object_unref(SP_OBJECT(_items[i]), NULL);
407 }
409 sp_canvas_item_hide(_norm);
410 sp_canvas_item_hide(_grip);
412 if (_show == SHOW_OUTLINE) {
413 for (int i = 0; i < 4; i++)
414 sp_canvas_item_hide(_l[i]);
415 }
417 if (_stamp_cache) {
418 g_slist_free(_stamp_cache);
419 _stamp_cache = NULL;
420 }
422 _message_context.clear();
424 if (!_empty && _changed) {
425 sp_selection_apply_affine(selection, _current_relative_affine, (_show == SHOW_OUTLINE)? true : false);
426 if (_center) {
427 *_center *= _current_relative_affine;
428 _center_is_set = true;
429 }
431 // If dragging showed content live, sp_selection_apply_affine cannot change the centers
432 // appropriately - it does not know the original positions of the centers (all objects already have
433 // the new bboxes). So we need to reset the centers from our saved array.
434 if (_show != SHOW_OUTLINE && !_current_relative_affine.is_translation()) {
435 for (unsigned i = 0; i < _items_centers.size(); i++) {
436 SPItem *currentItem = _items[i];
437 if (currentItem->isCenterSet()) { // only if it's already set
438 currentItem->setCenter (_items_centers[i] * _current_relative_affine);
439 SP_OBJECT(currentItem)->updateRepr();
440 }
441 }
442 }
444 _items.clear();
445 _items_const.clear();
446 _items_affines.clear();
447 _items_centers.clear();
449 if (_current_relative_affine.is_translation()) {
450 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
451 _("Move"));
452 } else if (_current_relative_affine.is_scale()) {
453 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
454 _("Scale"));
455 } else if (_current_relative_affine.is_rotation()) {
456 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
457 _("Rotate"));
458 } else {
459 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
460 _("Skew"));
461 }
463 } else {
465 if (_center_is_set) {
466 // we were dragging center; update reprs and commit undoable action
467 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
468 SPItem *it = (SPItem*)SP_OBJECT(l->data);
469 SP_OBJECT(it)->updateRepr();
470 }
471 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
472 _("Set center"));
473 }
475 _items.clear();
476 _items_const.clear();
477 _items_affines.clear();
478 _items_centers.clear();
479 _updateHandles();
480 }
481 }
483 /* fixme: This is really bad, as we compare positions for each stamp (Lauris) */
484 /* fixme: IMHO the best way to keep sort cache would be to implement timestamping at last */
486 void Inkscape::SelTrans::stamp()
487 {
488 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
490 bool fixup = !_grabbed;
491 if ( fixup && _stamp_cache ) {
492 // TODO - give a proper fix. Simple temproary work-around for the grab() issue
493 g_slist_free(_stamp_cache);
494 _stamp_cache = NULL;
495 }
497 /* stamping mode */
498 if (!_empty) {
499 GSList *l;
500 if (_stamp_cache) {
501 l = _stamp_cache;
502 } else {
503 /* Build cache */
504 l = g_slist_copy((GSList *) selection->itemList());
505 l = g_slist_sort(l, (GCompareFunc) sp_object_compare_position);
506 _stamp_cache = l;
507 }
509 while (l) {
510 SPItem *original_item = SP_ITEM(l->data);
511 Inkscape::XML::Node *original_repr = SP_OBJECT_REPR(original_item);
513 // remember the position of the item
514 gint pos = original_repr->position();
515 // remember parent
516 Inkscape::XML::Node *parent = sp_repr_parent(original_repr);
518 Inkscape::XML::Node *copy_repr = original_repr->duplicate(parent->document());
520 // add the new repr to the parent
521 parent->appendChild(copy_repr);
522 // move to the saved position
523 copy_repr->setPosition(pos > 0 ? pos : 0);
525 SPItem *copy_item = (SPItem *) sp_desktop_document(_desktop)->getObjectByRepr(copy_repr);
527 NR::Matrix const *new_affine;
528 if (_show == SHOW_OUTLINE) {
529 NR::Matrix const i2d(sp_item_i2d_affine(original_item));
530 NR::Matrix const i2dnew( i2d * _current_relative_affine );
531 sp_item_set_i2d_affine(copy_item, i2dnew);
532 new_affine = ©_item->transform;
533 } else {
534 new_affine = &original_item->transform;
535 }
537 sp_item_write_transform(copy_item, copy_repr, *new_affine);
539 if ( copy_item->isCenterSet() && _center ) {
540 copy_item->setCenter(*_center * _current_relative_affine);
541 }
543 Inkscape::GC::release(copy_repr);
544 l = l->next;
545 }
546 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
547 _("Stamp"));
548 }
550 if ( fixup && _stamp_cache ) {
551 // TODO - give a proper fix. Simple temproary work-around for the grab() issue
552 g_slist_free(_stamp_cache);
553 _stamp_cache = NULL;
554 }
555 }
557 void Inkscape::SelTrans::_updateHandles()
558 {
559 if ( !_show_handles || _empty )
560 {
561 sp_remove_handles(_shandle, 8);
562 sp_remove_handles(_rhandle, 8);
563 sp_remove_handles(&_chandle, 1);
564 return;
565 }
567 // center handle
568 if ( _chandle == NULL ) {
569 _chandle = sp_knot_new(_desktop, _("<b>Center</b> of rotation and skewing: drag to reposition; scaling with Shift also uses this center"));
571 _chandle->setShape (SP_CTRL_SHAPE_BITMAP);
572 _chandle->setSize (13);
573 _chandle->setAnchor (handle_center.anchor);
574 _chandle->setMode (SP_CTRL_MODE_XOR);
575 _chandle->setFill(0x00000000, 0x00000000, 0x00000000);
576 _chandle->setStroke(0x000000ff, 0xff0000b0, 0xff0000b0);
577 _chandle->setPixbuf(handles[handle_center.control]);
578 sp_knot_update_ctrl(_chandle);
580 g_signal_connect(G_OBJECT(_chandle), "request",
581 G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle_center);
582 g_signal_connect(G_OBJECT(_chandle), "moved",
583 G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle_center);
584 g_signal_connect(G_OBJECT(_chandle), "grabbed",
585 G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle_center);
586 g_signal_connect(G_OBJECT(_chandle), "ungrabbed",
587 G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle_center);
588 g_signal_connect(G_OBJECT(_chandle), "clicked",
589 G_CALLBACK(sp_sel_trans_handle_click), (gpointer) &handle_center);
590 }
592 sp_remove_handles(&_chandle, 1);
593 if ( _state == STATE_SCALE ) {
594 sp_remove_handles(_rhandle, 8);
595 _showHandles(_shandle, handles_scale, 8,
596 _("<b>Squeeze or stretch</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"),
597 _("<b>Scale</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"));
598 } else {
599 sp_remove_handles(_shandle, 8);
600 _showHandles(_rhandle, handles_rotate, 8,
601 _("<b>Skew</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to skew around the opposite side"),
602 _("<b>Rotate</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to rotate around the opposite corner"));
603 }
605 if (!_center_is_set) {
606 _center = _desktop->selection->center();
607 _center_is_set = true;
608 }
610 if ( _state == STATE_SCALE || !_center ) {
611 sp_knot_hide(_chandle);
612 } else {
613 sp_knot_show(_chandle);
614 sp_knot_moveto(_chandle, &*_center);
615 }
616 }
618 void Inkscape::SelTrans::_updateVolatileState()
619 {
620 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
621 _empty = selection->isEmpty();
623 if (_empty) {
624 return;
625 }
627 //Update the bboxes
628 _bbox = selection->bounds(_snap_bbox_type);
629 _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX);
631 if (!_bbox) {
632 _empty = true;
633 return;
634 }
636 _strokewidth = stroke_average_width (selection->itemList());
637 }
639 static void sp_remove_handles(SPKnot *knot[], gint num)
640 {
641 for (int i = 0; i < num; i++) {
642 if (knot[i] != NULL) {
643 sp_knot_hide(knot[i]);
644 }
645 }
646 }
648 void Inkscape::SelTrans::_showHandles(SPKnot *knot[], SPSelTransHandle const handle[], gint num,
649 gchar const *even_tip, gchar const *odd_tip)
650 {
651 g_return_if_fail( !_empty );
653 for (int i = 0; i < num; i++) {
654 if (knot[i] == NULL) {
655 knot[i] = sp_knot_new(_desktop, i % 2 ? even_tip : odd_tip);
657 knot[i]->setShape (SP_CTRL_SHAPE_BITMAP);
658 knot[i]->setSize (13);
659 knot[i]->setAnchor (handle[i].anchor);
660 knot[i]->setMode (SP_CTRL_MODE_XOR);
661 knot[i]->setFill(0x000000ff, 0x00ff6600, 0x00ff6600); // inversion, green, green
662 knot[i]->setStroke(0x000000ff, 0x000000ff, 0x000000ff); // inversion
663 knot[i]->setPixbuf(handles[handle[i].control]);
664 sp_knot_update_ctrl(knot[i]);
666 g_signal_connect(G_OBJECT(knot[i]), "request",
667 G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle[i]);
668 g_signal_connect(G_OBJECT(knot[i]), "moved",
669 G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle[i]);
670 g_signal_connect(G_OBJECT(knot[i]), "grabbed",
671 G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle[i]);
672 g_signal_connect(G_OBJECT(knot[i]), "ungrabbed",
673 G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle[i]);
674 g_signal_connect(G_OBJECT(knot[i]), "event", G_CALLBACK(sp_seltrans_handle_event), (gpointer) &handle[i]);
675 }
676 sp_knot_show(knot[i]);
678 NR::Point const handle_pt(handle[i].x, handle[i].y);
679 // shouldn't have nullary bbox, but knots
680 g_assert(_bbox);
681 NR::Point p( _bbox->min()
682 + ( _bbox->dimensions()
683 * NR::scale(handle_pt) ) );
685 sp_knot_moveto(knot[i], &p);
686 }
687 }
689 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data)
690 {
691 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleGrab(
692 knot, state, *(SPSelTransHandle const *) data
693 );
694 }
696 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint /*state*/, gpointer /*data*/)
697 {
698 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->ungrab();
699 }
701 static void sp_sel_trans_handle_new_event(SPKnot *knot, NR::Point *position, guint state, gpointer data)
702 {
703 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleNewEvent(
704 knot, position, state, *(SPSelTransHandle const *) data
705 );
706 }
708 static gboolean sp_sel_trans_handle_request(SPKnot *knot, NR::Point *position, guint state, gboolean *data)
709 {
710 return SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleRequest(
711 knot, position, state, *(SPSelTransHandle const *) data
712 );
713 }
715 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data)
716 {
717 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleClick(
718 knot, state, *(SPSelTransHandle const *) data
719 );
720 }
722 void Inkscape::SelTrans::handleClick(SPKnot */*knot*/, guint state, SPSelTransHandle const &handle)
723 {
724 switch (handle.anchor) {
725 case GTK_ANCHOR_CENTER:
726 if (state & GDK_SHIFT_MASK) {
727 // Unset the center position for all selected items
728 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
729 SPItem *it = (SPItem*)(SP_OBJECT(l->data));
730 it->unsetCenter();
731 SP_OBJECT(it)->updateRepr();
732 _center_is_set = false; // center has changed
733 _updateHandles();
734 }
735 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
736 _("Reset center"));
737 }
738 break;
739 default:
740 break;
741 }
742 }
744 void Inkscape::SelTrans::handleGrab(SPKnot *knot, guint /*state*/, SPSelTransHandle const &handle)
745 {
746 switch (handle.anchor) {
747 case GTK_ANCHOR_CENTER:
748 g_object_set(G_OBJECT(_grip),
749 "shape", SP_CTRL_SHAPE_BITMAP,
750 "size", 13.0,
751 NULL);
752 sp_canvas_item_show(_grip);
753 break;
754 default:
755 g_object_set(G_OBJECT(_grip),
756 "shape", SP_CTRL_SHAPE_CROSS,
757 "size", 7.0,
758 NULL);
759 sp_canvas_item_show(_norm);
760 sp_canvas_item_show(_grip);
762 break;
763 }
765 grab(sp_knot_position(knot), handle.x, handle.y, FALSE);
766 }
769 void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, NR::Point *position, guint state, SPSelTransHandle const &handle)
770 {
771 if (!SP_KNOT_IS_GRABBED(knot)) {
772 return;
773 }
775 // in case items have been unhooked from the document, don't
776 // try to continue processing events for them.
777 for (unsigned int i = 0; i < _items.size(); i++) {
778 if (!SP_OBJECT_DOCUMENT(SP_OBJECT(_items[i])) ) {
779 return;
780 }
781 }
783 handle.action(this, handle, *position, state);
784 }
787 gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, NR::Point *position, guint state, SPSelTransHandle const &handle)
788 {
789 if (!SP_KNOT_IS_GRABBED(knot)) {
790 return TRUE;
791 }
793 knot->desktop->setPosition(*position);
795 // When holding shift while rotating or skewing, the transformation will be
796 // relative to the point opposite of the handle; otherwise it will be relative
797 // to the center as set for the selection
798 if ((!(state & GDK_SHIFT_MASK) == !(_state == STATE_ROTATE)) && (&handle != &handle_center)) {
799 _origin = _opposite;
800 _origin_for_bboxpoints = _opposite_for_bboxpoints;
801 _origin_for_specpoints = _opposite_for_specpoints;
802 } else if (_center) {
803 _origin = *_center;
804 _origin_for_bboxpoints = *_center;
805 _origin_for_specpoints = *_center;
806 } else {
807 // FIXME
808 return TRUE;
809 }
810 if (handle.request(this, handle, *position, state)) {
811 sp_knot_set_position(knot, position, state);
812 SP_CTRL(_grip)->moveto(*position);
813 SP_CTRL(_norm)->moveto(_origin);
814 }
816 return TRUE;
817 }
820 void Inkscape::SelTrans::_selChanged(Inkscape::Selection */*selection*/)
821 {
822 if (!_grabbed) {
823 // reread in case it changed on the fly:
824 int prefs_bbox = prefs_get_int_attribute("tools", "bounding_box", 0);
825 _snap_bbox_type = (prefs_bbox ==0)?
826 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
827 //SPItem::APPROXIMATE_BBOX will be replaced by SPItem::VISUAL_BBOX, as soon as the latter is implemented properly
829 _updateVolatileState();
830 _current_relative_affine.set_identity();
831 _center_is_set = false; // center(s) may have changed
832 _updateHandles();
833 }
834 }
836 void Inkscape::SelTrans::_selModified(Inkscape::Selection */*selection*/, guint /*flags*/)
837 {
838 if (!_grabbed) {
839 _updateVolatileState();
840 _current_relative_affine.set_identity();
842 // reset internal flag
843 _changed = false;
845 _center_is_set = false; // center(s) may have changed
847 _updateHandles();
848 }
849 }
851 /*
852 * handlers for handle move-request
853 */
855 /** Returns -1 or 1 according to the sign of x. Returns 1 for 0 and NaN. */
856 static double sign(double const x)
857 {
858 return ( x < 0
859 ? -1
860 : 1 );
861 }
863 gboolean sp_sel_trans_scale_request(Inkscape::SelTrans *seltrans,
864 SPSelTransHandle const &, NR::Point &pt, guint state)
865 {
866 return seltrans->scaleRequest(pt, state);
867 }
869 gboolean sp_sel_trans_stretch_request(Inkscape::SelTrans *seltrans,
870 SPSelTransHandle const &handle, NR::Point &pt, guint state)
871 {
872 return seltrans->stretchRequest(handle, pt, state);
873 }
875 gboolean sp_sel_trans_skew_request(Inkscape::SelTrans *seltrans,
876 SPSelTransHandle const &handle, NR::Point &pt, guint state)
877 {
878 return seltrans->skewRequest(handle, pt, state);
879 }
881 gboolean sp_sel_trans_rotate_request(Inkscape::SelTrans *seltrans,
882 SPSelTransHandle const &, NR::Point &pt, guint state)
883 {
884 return seltrans->rotateRequest(pt, state);
885 }
887 gboolean sp_sel_trans_center_request(Inkscape::SelTrans *seltrans,
888 SPSelTransHandle const &, NR::Point &pt, guint state)
889 {
890 return seltrans->centerRequest(pt, state);
891 }
893 gboolean Inkscape::SelTrans::scaleRequest(NR::Point &pt, guint state)
894 {
896 // Calculate the scale factors, which can be either visual or geometric
897 // depending on which type of bbox is currently being used (see preferences -> selector tool)
898 NR::scale default_scale = calcScaleFactors(_point, pt, _origin);
900 // Find the scale factors for the geometric bbox
901 NR::Point pt_geom = _getGeomHandlePos(pt);
902 NR::scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
904 _absolute_affine = NR::identity(); //Initialize the scaler
906 if (state & GDK_MOD1_MASK) { // scale by an integer multiplier/divider
907 // We're scaling either the visual or the geometric bbox here (see the comment above)
908 for ( unsigned int i = 0 ; i < 2 ; i++ ) {
909 if (fabs(default_scale[i]) > 1) {
910 default_scale[i] = round(default_scale[i]);
911 } else if (default_scale[i] != 0) {
912 default_scale[i] = 1/round(1/(MIN(default_scale[i], 10)));
913 }
914 }
915 // Update the knot position
916 pt = _calcAbsAffineDefault(default_scale);
917 // When scaling by an integer, snapping is not needed
918 } else {
919 // In all other cases we should try to snap now
920 SnapManager const &m = _desktop->namedview->snap_manager;
922 Inkscape::SnappedPoint bb, sn;
923 NR::Coord bd(NR_HUGE);
924 NR::Coord sd(NR_HUGE);
926 if ((state & GDK_CONTROL_MASK) || _desktop->isToolboxButtonActive ("lock")) {
927 // Scale is locked to a 1:1 aspect ratio, so that s[X] must be made to equal s[Y].
928 //
929 // The aspect-ratio must be locked before snapping
930 if (fabs(default_scale[NR::X]) > fabs(default_scale[NR::Y])) {
931 default_scale[NR::X] = fabs(default_scale[NR::Y]) * sign(default_scale[NR::X]);
932 geom_scale[NR::X] = fabs(geom_scale[NR::Y]) * sign(geom_scale[NR::X]);
933 } else {
934 default_scale[NR::Y] = fabs(default_scale[NR::X]) * sign(default_scale[NR::Y]);
935 geom_scale[NR::Y] = fabs(geom_scale[NR::X]) * sign(geom_scale[NR::Y]);
936 }
938 // Snap along a suitable constraint vector from the origin.
939 bb = m.constrainedSnapScale(Snapper::SNAPPOINT_BBOX, _bbox_points, _items_const, default_scale, _origin_for_bboxpoints);
940 sn = m.constrainedSnapScale(Snapper::SNAPPOINT_NODE, _snap_points, _items_const, geom_scale, _origin_for_specpoints);
942 /* Choose the smaller difference in scale. Since s[X] == s[Y] we can
943 ** just compare difference in s[X].
944 */
945 bd = bb.getSnapped() ? fabs(bb.getTransformation()[NR::X] - default_scale[NR::X]) : NR_HUGE;
946 sd = sn.getSnapped() ? fabs(sn.getTransformation()[NR::X] - geom_scale[NR::X]) : NR_HUGE;
947 } else {
948 /* Scale aspect ratio is unlocked */
949 bb = m.freeSnapScale(Snapper::SNAPPOINT_BBOX, _bbox_points, _items_const, default_scale, _origin_for_bboxpoints);
950 sn = m.freeSnapScale(Snapper::SNAPPOINT_NODE, _snap_points, _items_const, geom_scale, _origin_for_specpoints);
952 /* Pick the snap that puts us closest to the original scale */
953 bd = bb.getSnapped() ? fabs(NR::L2(bb.getTransformation()) - NR::L2(default_scale.point())) : NR_HUGE;
954 sd = sn.getSnapped() ? fabs(NR::L2(sn.getTransformation()) - NR::L2(geom_scale.point())) : NR_HUGE;
955 }
957 if (!(bb.getSnapped() || sn.getSnapped())) {
958 // We didn't snap at all! Don't update the handle position, just calculate the new transformation
959 _calcAbsAffineDefault(default_scale);
960 } else if (bd < sd) {
961 // We snapped the bbox (which is either visual or geometric)
962 _desktop->snapindicator->set_new_snappoint(bb);
963 default_scale = NR::scale(bb.getTransformation());
964 // Calculate the new transformation and update the handle position
965 pt = _calcAbsAffineDefault(default_scale);
966 } else {
967 _desktop->snapindicator->set_new_snappoint(sn);
968 // We snapped the special points (e.g. nodes), which are not at the visual bbox
969 // The handle location however (pt) might however be at the visual bbox, so we
970 // will have to calculate pt taking the stroke width into account
971 geom_scale = NR::scale(sn.getTransformation());
972 pt = _calcAbsAffineGeom(geom_scale);
973 }
974 }
976 /* Status text */
977 _message_context.setF(Inkscape::NORMAL_MESSAGE,
978 _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
979 100 * _absolute_affine[0], 100 * _absolute_affine[3]);
981 return TRUE;
982 }
984 gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, NR::Point &pt, guint state)
985 {
986 NR::Dim2 axis, perp;
987 switch (handle.cursor) {
988 case GDK_TOP_SIDE:
989 case GDK_BOTTOM_SIDE:
990 axis = NR::Y;
991 perp = NR::X;
992 break;
993 case GDK_LEFT_SIDE:
994 case GDK_RIGHT_SIDE:
995 axis = NR::X;
996 perp = NR::Y;
997 break;
998 default:
999 g_assert_not_reached();
1000 return TRUE;
1001 };
1003 // Calculate the scale factors, which can be either visual or geometric
1004 // depending on which type of bbox is currently being used (see preferences -> selector tool)
1005 NR::scale default_scale = calcScaleFactors(_point, pt, _origin);
1006 default_scale[perp] = 1;
1008 // Find the scale factors for the geometric bbox
1009 NR::Point pt_geom = _getGeomHandlePos(pt);
1010 NR::scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
1011 geom_scale[perp] = 1;
1013 _absolute_affine = NR::identity(); //Initialize the scaler
1015 if (state & GDK_MOD1_MASK) { // stretch by an integer multiplier/divider
1016 if (fabs(default_scale[axis]) > 1) {
1017 default_scale[axis] = round(default_scale[axis]);
1018 } else if (default_scale[axis] != 0) {
1019 default_scale[axis] = 1/round(1/(MIN(default_scale[axis], 10)));
1020 }
1021 // Calculate the new transformation and update the handle position
1022 pt = _calcAbsAffineDefault(default_scale);
1023 // When stretching by an integer, snapping is not needed
1024 } else {
1025 // In all other cases we should try to snap now
1027 SnapManager const &m = _desktop->namedview->snap_manager;
1029 Inkscape::SnappedPoint bb, sn;
1030 g_assert(bb.getSnapped() == false); // Check initialization to catch any regression
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, _items_const, default_scale[axis], _origin_for_bboxpoints, axis, symmetrical);
1037 sn = m.constrainedSnapStretch(Snapper::SNAPPOINT_NODE, _snap_points, _items_const, geom_scale[axis], _origin_for_specpoints, axis, symmetrical);
1039 if (bb.getSnapped()) {
1040 // We snapped the bbox (which is either visual or geometric)
1041 bd = fabs(bb.getTransformation()[axis] - default_scale[axis]);
1042 default_scale[axis] = bb.getTransformation()[axis];
1043 }
1045 if (sn.getSnapped()) {
1046 sd = fabs(sn.getTransformation()[axis] - geom_scale[axis]);
1047 geom_scale[axis] = sn.getTransformation()[axis];
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.getSnapped() || sn.getSnapped())) {
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 _desktop->snapindicator->set_new_snappoint(bb);
1062 // Calculate the new transformation and update the handle position
1063 pt = _calcAbsAffineDefault(default_scale);
1064 } else {
1065 _desktop->snapindicator->set_new_snappoint(sn);
1066 // We snapped the special points (e.g. nodes), which are not at the visual bbox
1067 // The handle location however (pt) might however be at the visual bbox, so we
1068 // will have to calculate pt taking the stroke width into account
1069 pt = _calcAbsAffineGeom(geom_scale);
1070 }
1071 }
1073 // status text
1074 _message_context.setF(Inkscape::NORMAL_MESSAGE,
1075 _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1076 100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1078 return TRUE;
1079 }
1081 gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, NR::Point &pt, guint state)
1082 {
1083 /* When skewing (or rotating):
1084 * 1) the stroke width will not change. This makes life much easier because we don't have to
1085 * account for that (like for scaling or stretching). As a consequence, all points will
1086 * have the same origin for the transformation and for the snapping.
1087 * 2) When holding shift, the transformation will be relative to the point opposite of
1088 * the handle; otherwise it will be relative to the center as set for the selection
1089 */
1091 NR::Dim2 dim_a;
1092 NR::Dim2 dim_b;
1094 switch (handle.cursor) {
1095 case GDK_SB_H_DOUBLE_ARROW:
1096 dim_a = NR::Y;
1097 dim_b = NR::X;
1098 break;
1099 case GDK_SB_V_DOUBLE_ARROW:
1100 dim_a = NR::X;
1101 dim_b = NR::Y;
1102 break;
1103 default:
1104 g_assert_not_reached();
1105 abort();
1106 break;
1107 }
1109 NR::Point const initial_delta = _point - _origin;
1111 if (fabs(initial_delta[dim_a]) < 1e-15) {
1112 return false;
1113 }
1115 // Calculate the scale factors, which can be either visual or geometric
1116 // depending on which type of bbox is currently being used (see preferences -> selector tool)
1117 NR::scale scale = calcScaleFactors(_point, pt, _origin, false);
1118 NR::scale skew = calcScaleFactors(_point, pt, _origin, true);
1119 scale[dim_b] = 1;
1120 skew[dim_b] = 1;
1122 if (fabs(scale[dim_a]) < 1) {
1123 // Prevent shrinking of the selected object, while allowing mirroring
1124 scale[dim_a] = sign(scale[dim_a]);
1125 } else {
1126 // Allow expanding of the selected object by integer multiples
1127 scale[dim_a] = floor(scale[dim_a] + 0.5);
1128 }
1130 double radians = atan(skew[dim_a] / scale[dim_a]);
1132 if (state & GDK_CONTROL_MASK) {
1133 // Snap to defined angle increments
1134 int snaps = prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12);
1135 if (snaps) {
1136 double sections = floor(radians * snaps / M_PI + .5);
1137 if (fabs(sections) >= snaps / 2) {
1138 sections = sign(sections) * (snaps / 2 - 1);
1139 }
1140 radians = (M_PI / snaps) * sections;
1141 }
1142 skew[dim_a] = tan(radians) * scale[dim_a];
1143 } else {
1144 // Snap to objects, grids, guides
1146 SnapManager const &m = _desktop->namedview->snap_manager;
1148 //TODO: While skewing, scaling in the opposite direction by integer multiples is also allowed. This is not handled though by freeSnapSkew / _snapTransformed yet!
1149 //TODO: We need a constrainedSnapSkew instead of a freeSnapSkew
1150 Inkscape::SnappedPoint bb = m.freeSnapSkew(Inkscape::Snapper::SNAPPOINT_BBOX, _bbox_points, _items_const, skew[dim_a], _origin, dim_b);
1151 Inkscape::SnappedPoint sn = m.freeSnapSkew(Inkscape::Snapper::SNAPPOINT_NODE, _snap_points, _items_const, skew[dim_a], _origin, dim_b);
1153 if (bb.getSnapped() || sn.getSnapped()) {
1154 // We snapped something, so change the skew to reflect it
1155 NR::Coord const bd = bb.getSnapped() ? bb.getTransformation()[dim_b] : NR_HUGE;
1156 NR::Coord const sd = sn.getSnapped() ? sn.getTransformation()[dim_b] : NR_HUGE;
1157 if (bd < sd) {
1158 _desktop->snapindicator->set_new_snappoint(bb);
1159 skew[dim_a] = bd;
1160 } else {
1161 _desktop->snapindicator->set_new_snappoint(sn);
1162 skew[dim_a] = sd;
1163 }
1164 }
1165 }
1167 // Update the handle position
1168 pt[dim_b] = initial_delta[dim_a] * skew[dim_a] + _point[dim_b];
1169 pt[dim_a] = initial_delta[dim_a] * scale[dim_a] + _origin[dim_a];
1171 // Calculate the relative affine
1172 _relative_affine = NR::identity();
1173 _relative_affine[2*dim_a + dim_a] = (pt[dim_a] - _origin[dim_a]) / initial_delta[dim_a];
1174 _relative_affine[2*dim_a + (dim_b)] = (pt[dim_b] - _point[dim_b]) / initial_delta[dim_a];
1175 _relative_affine[2*(dim_b) + (dim_a)] = 0;
1176 _relative_affine[2*(dim_b) + (dim_b)] = 1;
1178 for (int i = 0; i < 2; i++) {
1179 if (fabs(_relative_affine[3*i]) < 1e-15) {
1180 _relative_affine[3*i] = 1e-15;
1181 }
1182 }
1184 // Update the status text
1185 double degrees = mod360symm(Geom::rad_to_deg(radians));
1186 _message_context.setF(Inkscape::NORMAL_MESSAGE,
1187 // TRANSLATORS: don't modify the first ";"
1188 // (it will NOT be displayed as ";" - only the second one will be)
1189 _("<b>Skew</b>: %0.2f°; with <b>Ctrl</b> to snap angle"),
1190 degrees);
1192 return TRUE;
1193 }
1195 gboolean Inkscape::SelTrans::rotateRequest(NR::Point &pt, guint state)
1196 {
1197 /* When rotating (or skewing):
1198 * 1) the stroke width will not change. This makes life much easier because we don't have to
1199 * account for that (like for scaling or stretching). As a consequence, all points will
1200 * have the same origin for the transformation and for the snapping.
1201 * 2) When holding shift, the transformation will be relative to the point opposite of
1202 * the handle; otherwise it will be relative to the center as set for the selection
1203 */
1205 int snaps = prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12);
1207 // rotate affine in rotate
1208 NR::Point const d1 = _point - _origin;
1209 NR::Point const d2 = pt - _origin;
1211 NR::Coord const h1 = NR::L2(d1); // initial radius
1212 if (h1 < 1e-15) return FALSE;
1213 NR::Point q1 = d1 / h1; // normalized initial vector to handle
1214 NR::Coord const h2 = NR::L2(d2); // new radius
1215 if (fabs(h2) < 1e-15) return FALSE;
1216 NR::Point q2 = d2 / h2; // normalized new vector to handle
1218 double radians;
1219 if (state & GDK_CONTROL_MASK) {
1220 // Snap to defined angle increments
1221 double cos_t = NR::dot(q1, q2);
1222 double sin_t = NR::dot(NR::rot90(q1), q2);
1223 radians = atan2(sin_t, cos_t);
1224 if (snaps) {
1225 radians = ( M_PI / snaps ) * floor( radians * snaps / M_PI + .5 );
1226 }
1227 q1 = NR::Point(1, 0);
1228 q2 = NR::Point(cos(radians), sin(radians));
1229 } else {
1230 radians = atan2(NR::dot(NR::rot90(d1), d2),
1231 NR::dot(d1, d2));
1232 }
1234 NR::rotate const r1(q1);
1235 NR::rotate const r2(q2);
1237 // Calculate the relative affine
1238 _relative_affine = NR::Matrix(r2/r1);
1240 // Update the handle position
1241 pt = _point * NR::translate(-_origin) * _relative_affine * NR::translate(_origin);
1243 // Update the status text
1244 double degrees = mod360symm(Geom::rad_to_deg(radians));
1245 _message_context.setF(Inkscape::NORMAL_MESSAGE,
1246 // TRANSLATORS: don't modify the first ";"
1247 // (it will NOT be displayed as ";" - only the second one will be)
1248 _("<b>Rotate</b>: %0.2f°; with <b>Ctrl</b> to snap angle"), degrees);
1250 return TRUE;
1251 }
1253 gboolean Inkscape::SelTrans::centerRequest(NR::Point &pt, guint state)
1254 {
1255 SnapManager const &m = _desktop->namedview->snap_manager;
1256 pt = m.freeSnap(Snapper::SNAPPOINT_NODE, pt, NULL).getPoint();
1258 if (state & GDK_CONTROL_MASK) {
1259 if ( fabs(_point[NR::X] - pt[NR::X]) > fabs(_point[NR::Y] - pt[NR::Y]) ) {
1260 pt[NR::Y] = _point[NR::Y];
1261 } else {
1262 pt[NR::X] = _point[NR::X];
1263 }
1264 }
1266 if ( !(state & GDK_SHIFT_MASK) && _bbox ) {
1267 // screen pixels to snap center to bbox
1268 #define SNAP_DIST 5
1269 // FIXME: take from prefs
1270 double snap_dist = SNAP_DIST / _desktop->current_zoom();
1272 for (int i = 0; i < 2; i++) {
1273 if (fabs(pt[i] - _bbox->min()[i]) < snap_dist) {
1274 pt[i] = _bbox->min()[i];
1275 }
1276 if (fabs(pt[i] - _bbox->midpoint()[i]) < snap_dist) {
1277 pt[i] = _bbox->midpoint()[i];
1278 }
1279 if (fabs(pt[i] - _bbox->max()[i]) < snap_dist) {
1280 pt[i] = _bbox->max()[i];
1281 }
1282 }
1283 }
1285 // status text
1286 GString *xs = SP_PX_TO_METRIC_STRING(pt[NR::X], _desktop->namedview->getDefaultMetric());
1287 GString *ys = SP_PX_TO_METRIC_STRING(pt[NR::Y], _desktop->namedview->getDefaultMetric());
1288 _message_context.setF(Inkscape::NORMAL_MESSAGE, _("Move <b>center</b> to %s, %s"), xs->str, ys->str);
1289 g_string_free(xs, FALSE);
1290 g_string_free(ys, FALSE);
1292 return TRUE;
1293 }
1295 /*
1296 * handlers for handle movement
1297 *
1298 */
1300 void sp_sel_trans_stretch(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, NR::Point &pt, guint state)
1301 {
1302 seltrans->stretch(handle, pt, state);
1303 }
1305 void sp_sel_trans_scale(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
1306 {
1307 seltrans->scale(pt, state);
1308 }
1310 void sp_sel_trans_skew(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, NR::Point &pt, guint state)
1311 {
1312 seltrans->skew(handle, pt, state);
1313 }
1315 void sp_sel_trans_rotate(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
1316 {
1317 seltrans->rotate(pt, state);
1318 }
1320 void Inkscape::SelTrans::stretch(SPSelTransHandle const &handle, NR::Point &pt, guint state)
1321 {
1322 transform(_absolute_affine, NR::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1323 }
1325 void Inkscape::SelTrans::scale(NR::Point &pt, guint /*state*/)
1326 {
1327 transform(_absolute_affine, NR::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1328 }
1330 void Inkscape::SelTrans::skew(SPSelTransHandle const &handle, NR::Point &pt, guint /*state*/)
1331 {
1332 transform(_relative_affine, _origin);
1333 }
1335 void Inkscape::SelTrans::rotate(NR::Point &pt, guint /*state*/)
1336 {
1337 transform(_relative_affine, _origin);
1338 }
1340 void sp_sel_trans_center(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint /*state*/)
1341 {
1342 seltrans->setCenter(pt);
1343 }
1346 void Inkscape::SelTrans::moveTo(NR::Point const &xy, guint state)
1347 {
1348 SnapManager const &m = _desktop->namedview->snap_manager;
1350 /* The amount that we've moved by during this drag */
1351 NR::Point dxy = xy - _point;
1353 bool const alt = (state & GDK_MOD1_MASK);
1354 bool const control = (state & GDK_CONTROL_MASK);
1355 bool const shift = (state & GDK_SHIFT_MASK);
1357 if (alt) {
1359 /* Alt pressed means keep offset: snap the moved distance to the grid.
1360 ** FIXME: this will snap to more than just the grid, nowadays.
1361 */
1363 dxy = m.freeSnap(Snapper::SNAPPOINT_NODE, dxy, NULL).getPoint();
1365 } else if (!shift) {
1367 /* We're snapping to things, possibly with a constraint to horizontal or
1368 ** vertical movement. Obtain a list of possible translations and then
1369 ** pick the smallest.
1370 */
1372 /* This will be our list of possible translations */
1373 std::list<Inkscape::SnappedPoint> s;
1375 if (control) {
1377 /* Snap to things, and also constrain to horizontal or vertical movement */
1379 for (unsigned int dim = 0; dim < 2; dim++) {
1380 s.push_back(m.constrainedSnapTranslation(Inkscape::Snapper::SNAPPOINT_BBOX,
1381 _bbox_points,
1382 _items_const,
1383 Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1384 dxy));
1386 s.push_back(m.constrainedSnapTranslation(Inkscape::Snapper::SNAPPOINT_NODE,
1387 _snap_points,
1388 _items_const,
1389 Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1390 dxy));
1391 }
1393 } else {
1395 // Let's leave this timer code here for a while. I'll probably need it in the near future (Diederik van Lierop)
1396 /* GTimeVal starttime;
1397 GTimeVal endtime;
1398 g_get_current_time(&starttime); */
1400 /* Snap to things with no constraint */
1401 s.push_back(m.freeSnapTranslation(Inkscape::Snapper::SNAPPOINT_BBOX,
1402 _bbox_points, _items_const, dxy));
1403 s.push_back(m.freeSnapTranslation(Inkscape::Snapper::SNAPPOINT_NODE,
1404 _snap_points, _items_const, dxy));
1406 /*g_get_current_time(&endtime);
1407 double elapsed = ((((double)endtime.tv_sec - starttime.tv_sec) * G_USEC_PER_SEC + (endtime.tv_usec - starttime.tv_usec))) / 1000.0;
1408 std::cout << "Time spent snapping: " << elapsed << std::endl; */
1409 }
1411 /* Pick one */
1412 Inkscape::SnappedPoint best_snapped_point;
1413 g_assert(best_snapped_point.getDistance() == NR_HUGE);
1414 for (std::list<Inkscape::SnappedPoint>::const_iterator i = s.begin(); i != s.end(); i++) {
1415 if (i->getSnapped()) {
1416 // std::cout << "moveTo() -> snapped to point: " << i->getPoint() << " with transformation: " << i->getTransformation();
1417 if (i->getDistance() < best_snapped_point.getDistance()) {
1418 best_snapped_point = *i;
1419 dxy = i->getTransformation();
1420 // std::cout << " SEL";
1421 }
1422 //std::cout << std::endl;
1423 }
1424 }
1425 if (best_snapped_point.getSnapped()) {
1426 _desktop->snapindicator->set_new_snappoint(best_snapped_point);
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 :