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"
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 int prefs_bbox = prefs_get_int_attribute("tools", "bounding_box", 0);
110 _snap_bbox_type = (prefs_bbox ==0)?
111 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
113 g_return_if_fail(desktop != NULL);
115 for (int i = 0; i < 8; i++) {
116 _shandle[i] = NULL;
117 _rhandle[i] = NULL;
118 }
120 _updateVolatileState();
121 _current_relative_affine.set_identity();
123 _center_is_set = false; // reread _center from items, or set to bbox midpoint
125 _updateHandles();
127 _selection = sp_desktop_selection(desktop);
129 _norm = sp_canvas_item_new(sp_desktop_controls(desktop),
130 SP_TYPE_CTRL,
131 "anchor", GTK_ANCHOR_CENTER,
132 "mode", SP_CTRL_MODE_COLOR,
133 "shape", SP_CTRL_SHAPE_BITMAP,
134 "size", 13.0,
135 "filled", TRUE,
136 "fill_color", 0x00000000,
137 "stroked", TRUE,
138 "stroke_color", 0x000000a0,
139 "pixbuf", handles[12],
140 NULL);
142 _grip = sp_canvas_item_new(sp_desktop_controls(desktop),
143 SP_TYPE_CTRL,
144 "anchor", GTK_ANCHOR_CENTER,
145 "mode", SP_CTRL_MODE_XOR,
146 "shape", SP_CTRL_SHAPE_CROSS,
147 "size", 7.0,
148 "filled", TRUE,
149 "fill_color", 0xffffff7f,
150 "stroked", TRUE,
151 "stroke_color", 0xffffffff,
152 "pixbuf", handles[12],
153 NULL);
155 sp_canvas_item_hide(_grip);
156 sp_canvas_item_hide(_norm);
158 for (int i = 0; i < 4; i++) {
159 _l[i] = sp_canvas_item_new(sp_desktop_controls(desktop), SP_TYPE_CTRLLINE, NULL);
160 sp_canvas_item_hide(_l[i]);
161 }
163 _sel_changed_connection = _selection->connectChanged(
164 sigc::mem_fun(*this, &Inkscape::SelTrans::_selChanged)
165 );
167 _sel_modified_connection = _selection->connectModified(
168 sigc::mem_fun(*this, &Inkscape::SelTrans::_selModified)
169 );
170 }
172 Inkscape::SelTrans::~SelTrans()
173 {
174 _sel_changed_connection.disconnect();
175 _sel_modified_connection.disconnect();
177 for (unsigned int i = 0; i < 8; i++) {
178 if (_shandle[i]) {
179 g_object_unref(G_OBJECT(_shandle[i]));
180 _shandle[i] = NULL;
181 }
182 if (_rhandle[i]) {
183 g_object_unref(G_OBJECT(_rhandle[i]));
184 _rhandle[i] = NULL;
185 }
186 }
187 if (_chandle) {
188 g_object_unref(G_OBJECT(_chandle));
189 _chandle = NULL;
190 }
192 if (_norm) {
193 gtk_object_destroy(GTK_OBJECT(_norm));
194 _norm = NULL;
195 }
196 if (_grip) {
197 gtk_object_destroy(GTK_OBJECT(_grip));
198 _grip = NULL;
199 }
200 for (int i = 0; i < 4; i++) {
201 if (_l[i]) {
202 gtk_object_destroy(GTK_OBJECT(_l[i]));
203 _l[i] = NULL;
204 }
205 }
207 for (unsigned i = 0; i < _items.size(); i++) {
208 sp_object_unref(SP_OBJECT(_items[i]), NULL);
209 }
211 _items.clear();
212 _items_const.clear();
213 _items_affines.clear();
214 _items_centers.clear();
215 }
217 void Inkscape::SelTrans::resetState()
218 {
219 _state = STATE_SCALE;
220 }
222 void Inkscape::SelTrans::increaseState()
223 {
224 if (_state == STATE_SCALE) {
225 _state = STATE_ROTATE;
226 } else {
227 _state = STATE_SCALE;
228 }
230 _center_is_set = true; // no need to reread center
232 _updateHandles();
233 }
235 void Inkscape::SelTrans::setCenter(NR::Point const &p)
236 {
237 _center = p;
238 _center_is_set = true;
240 // Write the new center position into all selected items
241 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
242 SPItem *it = (SPItem*)SP_OBJECT(l->data);
243 it->setCenter(p);
244 // only set the value; updating repr and document_done will be done once, on ungrab
245 }
247 _updateHandles();
248 }
250 void Inkscape::SelTrans::grab(NR::Point const &p, gdouble x, gdouble y, bool show_handles)
251 {
252 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
254 g_return_if_fail(!_grabbed);
256 _grabbed = true;
257 _show_handles = show_handles;
258 _updateVolatileState();
259 _current_relative_affine.set_identity();
261 _changed = false;
263 if (_empty) {
264 return;
265 }
267 for (GSList const *l = selection->itemList(); l; l = l->next) {
268 SPItem *it = (SPItem *)sp_object_ref(SP_OBJECT(l->data), NULL);
269 _items.push_back(it);
270 _items_const.push_back(it);
271 _items_affines.push_back(from_2geom(sp_item_i2d_affine(it)));
272 _items_centers.push_back(it->getCenter()); // for content-dragging, we need to remember original centers
273 }
275 _handle_x = x;
276 _handle_y = y;
278 // The selector tool should snap the bbox, special snappoints, and path nodes
279 // (The special points are the handles, center, rotation axis, font baseline, ends of spiral, etc.)
281 // First, determine the bounding box for snapping ...
282 _bbox = selection->bounds(_snap_bbox_type);
283 _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX); // Used for correctly scaling the strokewidth
284 _geometric_bbox = selection->bounds(SPItem::GEOMETRIC_BBOX);
285 _point = p;
286 if (_geometric_bbox) {
287 _point_geom = _geometric_bbox->min() + _geometric_bbox->dimensions() * NR::scale(x, y);
288 } else {
289 _point_geom = p;
290 }
292 // Next, get all points to consider for snapping
293 SnapManager const &m = _desktop->namedview->snap_manager;
294 _snap_points = selection->getSnapPoints(m.getIncludeItemCenter());
295 std::vector<NR::Point> snap_points_hull = selection->getSnapPointsConvexHull();
296 if (_snap_points.size() > 100) {
297 /* Snapping a huge number of nodes will take way too long, so limit the number of snappable nodes
298 An average user would rarely ever try to snap such a large number of nodes anyway, because
299 (s)he could hardly discern which node would be snapping */
300 _snap_points = snap_points_hull;
301 // Unfortunately, by now we will have lost the font-baseline snappoints :-(
302 }
304 // Find bbox hulling all special points, which excludes stroke width. Here we need to include the
305 // path nodes, for example because a rectangle which has been converted to a path doesn't have
306 // any other special points
307 NR::Rect snap_points_bbox;
308 if ( snap_points_hull.empty() == false ) {
309 std::vector<NR::Point>::iterator i = snap_points_hull.begin();
310 snap_points_bbox = NR::Rect(*i, *i);
311 i++;
312 while (i != snap_points_hull.end()) {
313 snap_points_bbox.expandTo(*i);
314 i++;
315 }
316 }
318 _bbox_points.clear();
319 if (_bbox) {
320 // ... and add the bbox corners to _bbox_points
321 for ( unsigned i = 0 ; i < 4 ; i++ ) {
322 _bbox_points.push_back(_bbox->corner(i));
323 }
324 // There are two separate "opposites" (i.e. opposite w.r.t. the handle being dragged):
325 // - one for snapping the boundingbox, which can be either visual or geometric
326 // - one for snapping the special points
327 // The "opposite" in case of a geometric boundingbox always coincides with the "opposite" for the special points
328 // These distinct "opposites" are needed in the snapmanager to avoid bugs such as #sf1540195 (in which
329 // a box is caught between two guides)
330 _opposite_for_bboxpoints = _bbox->min() + _bbox->dimensions() * NR::scale(1-x, 1-y);
331 _opposite_for_specpoints = snap_points_bbox.min() + snap_points_bbox.dimensions() * NR::scale(1-x, 1-y);
332 _opposite = _opposite_for_bboxpoints;
333 }
335 // The lines below are usefull for debugging any snapping issues, as they'll spit out all points that are considered for snapping
337 /*std::cout << "Number of snap points: " << _snap_points.size() << std::endl;
338 for (std::vector<NR::Point>::const_iterator i = _snap_points.begin(); i != _snap_points.end(); i++)
339 {
340 std::cout << " " << *i << std::endl;
341 }
343 std::cout << "Number of bbox points: " << _bbox_points.size() << std::endl;
344 for (std::vector<NR::Point>::const_iterator i = _bbox_points.begin(); i != _bbox_points.end(); i++)
345 {
346 std::cout << " " << *i << std::endl;
347 }*/
349 if ((x != -1) && (y != -1)) {
350 sp_canvas_item_show(_norm);
351 sp_canvas_item_show(_grip);
352 }
354 if (_show == SHOW_OUTLINE) {
355 for (int i = 0; i < 4; i++)
356 sp_canvas_item_show(_l[i]);
357 }
359 _updateHandles();
360 g_return_if_fail(_stamp_cache == NULL);
361 }
363 void Inkscape::SelTrans::transform(NR::Matrix const &rel_affine, NR::Point const &norm)
364 {
365 g_return_if_fail(_grabbed);
366 g_return_if_fail(!_empty);
368 NR::Matrix const affine( NR::translate(-norm) * rel_affine * NR::translate(norm) );
370 if (_show == SHOW_CONTENT) {
371 // update the content
372 for (unsigned i = 0; i < _items.size(); i++) {
373 SPItem &item = *_items[i];
374 NR::Matrix const &prev_transform = _items_affines[i];
375 sp_item_set_i2d_affine(&item, to_2geom(prev_transform * affine));
376 }
377 } else {
378 if (_bbox) {
379 NR::Point p[4];
380 /* update the outline */
381 for (unsigned i = 0 ; i < 4 ; i++) {
382 p[i] = _bbox->corner(i) * affine;
383 }
384 for (unsigned i = 0 ; i < 4 ; i++) {
385 sp_ctrlline_set_coords(SP_CTRLLINE(_l[i]), p[i], p[(i+1)%4]);
386 }
387 }
388 }
390 _current_relative_affine = affine;
391 _changed = true;
392 _updateHandles();
393 }
395 void Inkscape::SelTrans::ungrab()
396 {
397 g_return_if_fail(_grabbed);
398 _grabbed = false;
399 _show_handles = true;
401 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
402 _updateVolatileState();
404 for (unsigned i = 0; i < _items.size(); i++) {
405 sp_object_unref(SP_OBJECT(_items[i]), NULL);
406 }
408 sp_canvas_item_hide(_norm);
409 sp_canvas_item_hide(_grip);
411 if (_show == SHOW_OUTLINE) {
412 for (int i = 0; i < 4; i++)
413 sp_canvas_item_hide(_l[i]);
414 }
416 if (_stamp_cache) {
417 g_slist_free(_stamp_cache);
418 _stamp_cache = NULL;
419 }
421 _message_context.clear();
423 if (!_empty && _changed) {
424 sp_selection_apply_affine(selection, _current_relative_affine, (_show == SHOW_OUTLINE)? true : false);
425 if (_center) {
426 *_center *= _current_relative_affine;
427 _center_is_set = true;
428 }
430 // If dragging showed content live, sp_selection_apply_affine cannot change the centers
431 // appropriately - it does not know the original positions of the centers (all objects already have
432 // the new bboxes). So we need to reset the centers from our saved array.
433 if (_show != SHOW_OUTLINE && !_current_relative_affine.is_translation()) {
434 for (unsigned i = 0; i < _items_centers.size(); i++) {
435 SPItem *currentItem = _items[i];
436 if (currentItem->isCenterSet()) { // only if it's already set
437 currentItem->setCenter (_items_centers[i] * _current_relative_affine);
438 SP_OBJECT(currentItem)->updateRepr();
439 }
440 }
441 }
443 _items.clear();
444 _items_const.clear();
445 _items_affines.clear();
446 _items_centers.clear();
448 if (_current_relative_affine.is_translation()) {
449 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
450 _("Move"));
451 } else if (_current_relative_affine.is_scale()) {
452 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
453 _("Scale"));
454 } else if (_current_relative_affine.is_rotation()) {
455 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
456 _("Rotate"));
457 } else {
458 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
459 _("Skew"));
460 }
462 } else {
464 if (_center_is_set) {
465 // we were dragging center; update reprs and commit undoable action
466 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
467 SPItem *it = (SPItem*)SP_OBJECT(l->data);
468 SP_OBJECT(it)->updateRepr();
469 }
470 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
471 _("Set center"));
472 }
474 _items.clear();
475 _items_const.clear();
476 _items_affines.clear();
477 _items_centers.clear();
478 _updateHandles();
479 }
480 }
482 /* fixme: This is really bad, as we compare positions for each stamp (Lauris) */
483 /* fixme: IMHO the best way to keep sort cache would be to implement timestamping at last */
485 void Inkscape::SelTrans::stamp()
486 {
487 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
489 bool fixup = !_grabbed;
490 if ( fixup && _stamp_cache ) {
491 // TODO - give a proper fix. Simple temproary work-around for the grab() issue
492 g_slist_free(_stamp_cache);
493 _stamp_cache = NULL;
494 }
496 /* stamping mode */
497 if (!_empty) {
498 GSList *l;
499 if (_stamp_cache) {
500 l = _stamp_cache;
501 } else {
502 /* Build cache */
503 l = g_slist_copy((GSList *) selection->itemList());
504 l = g_slist_sort(l, (GCompareFunc) sp_object_compare_position);
505 _stamp_cache = l;
506 }
508 while (l) {
509 SPItem *original_item = SP_ITEM(l->data);
510 Inkscape::XML::Node *original_repr = SP_OBJECT_REPR(original_item);
512 // remember the position of the item
513 gint pos = original_repr->position();
514 // remember parent
515 Inkscape::XML::Node *parent = sp_repr_parent(original_repr);
517 Inkscape::XML::Node *copy_repr = original_repr->duplicate(parent->document());
519 // add the new repr to the parent
520 parent->appendChild(copy_repr);
521 // move to the saved position
522 copy_repr->setPosition(pos > 0 ? pos : 0);
524 SPItem *copy_item = (SPItem *) sp_desktop_document(_desktop)->getObjectByRepr(copy_repr);
526 NR::Matrix const *new_affine;
527 if (_show == SHOW_OUTLINE) {
528 NR::Matrix const i2d(from_2geom(sp_item_i2d_affine(original_item)));
529 NR::Matrix const i2dnew( i2d * _current_relative_affine );
530 sp_item_set_i2d_affine(copy_item, to_2geom(i2dnew));
531 new_affine = ©_item->transform;
532 } else {
533 new_affine = &original_item->transform;
534 }
536 sp_item_write_transform(copy_item, copy_repr, *new_affine);
538 if ( copy_item->isCenterSet() && _center ) {
539 copy_item->setCenter(*_center * _current_relative_affine);
540 }
542 Inkscape::GC::release(copy_repr);
543 l = l->next;
544 }
545 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
546 _("Stamp"));
547 }
549 if ( fixup && _stamp_cache ) {
550 // TODO - give a proper fix. Simple temproary work-around for the grab() issue
551 g_slist_free(_stamp_cache);
552 _stamp_cache = NULL;
553 }
554 }
556 void Inkscape::SelTrans::_updateHandles()
557 {
558 if ( !_show_handles || _empty )
559 {
560 sp_remove_handles(_shandle, 8);
561 sp_remove_handles(_rhandle, 8);
562 sp_remove_handles(&_chandle, 1);
563 return;
564 }
566 // center handle
567 if ( _chandle == NULL ) {
568 _chandle = sp_knot_new(_desktop, _("<b>Center</b> of rotation and skewing: drag to reposition; scaling with Shift also uses this center"));
570 _chandle->setShape (SP_CTRL_SHAPE_BITMAP);
571 _chandle->setSize (13);
572 _chandle->setAnchor (handle_center.anchor);
573 _chandle->setMode (SP_CTRL_MODE_XOR);
574 _chandle->setFill(0x00000000, 0x00000000, 0x00000000);
575 _chandle->setStroke(0x000000ff, 0xff0000b0, 0xff0000b0);
576 _chandle->setPixbuf(handles[handle_center.control]);
577 sp_knot_update_ctrl(_chandle);
579 g_signal_connect(G_OBJECT(_chandle), "request",
580 G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle_center);
581 g_signal_connect(G_OBJECT(_chandle), "moved",
582 G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle_center);
583 g_signal_connect(G_OBJECT(_chandle), "grabbed",
584 G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle_center);
585 g_signal_connect(G_OBJECT(_chandle), "ungrabbed",
586 G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle_center);
587 g_signal_connect(G_OBJECT(_chandle), "clicked",
588 G_CALLBACK(sp_sel_trans_handle_click), (gpointer) &handle_center);
589 }
591 sp_remove_handles(&_chandle, 1);
592 if ( _state == STATE_SCALE ) {
593 sp_remove_handles(_rhandle, 8);
594 _showHandles(_shandle, handles_scale, 8,
595 _("<b>Squeeze or stretch</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"),
596 _("<b>Scale</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"));
597 } else {
598 sp_remove_handles(_shandle, 8);
599 _showHandles(_rhandle, handles_rotate, 8,
600 _("<b>Skew</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to skew around the opposite side"),
601 _("<b>Rotate</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to rotate around the opposite corner"));
602 }
604 if (!_center_is_set) {
605 _center = _desktop->selection->center();
606 _center_is_set = true;
607 }
609 if ( _state == STATE_SCALE || !_center ) {
610 sp_knot_hide(_chandle);
611 } else {
612 sp_knot_show(_chandle);
613 sp_knot_moveto(_chandle, &*_center);
614 }
615 }
617 void Inkscape::SelTrans::_updateVolatileState()
618 {
619 Inkscape::Selection *selection = sp_desktop_selection(_desktop);
620 _empty = selection->isEmpty();
622 if (_empty) {
623 return;
624 }
626 //Update the bboxes
627 _bbox = selection->bounds(_snap_bbox_type);
628 _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX);
630 if (!_bbox) {
631 _empty = true;
632 return;
633 }
635 _strokewidth = stroke_average_width (selection->itemList());
636 }
638 static void sp_remove_handles(SPKnot *knot[], gint num)
639 {
640 for (int i = 0; i < num; i++) {
641 if (knot[i] != NULL) {
642 sp_knot_hide(knot[i]);
643 }
644 }
645 }
647 void Inkscape::SelTrans::_showHandles(SPKnot *knot[], SPSelTransHandle const handle[], gint num,
648 gchar const *even_tip, gchar const *odd_tip)
649 {
650 g_return_if_fail( !_empty );
652 for (int i = 0; i < num; i++) {
653 if (knot[i] == NULL) {
654 knot[i] = sp_knot_new(_desktop, i % 2 ? even_tip : odd_tip);
656 knot[i]->setShape (SP_CTRL_SHAPE_BITMAP);
657 knot[i]->setSize (13);
658 knot[i]->setAnchor (handle[i].anchor);
659 knot[i]->setMode (SP_CTRL_MODE_XOR);
660 knot[i]->setFill(0x000000ff, 0x00ff6600, 0x00ff6600); // inversion, green, green
661 knot[i]->setStroke(0x000000ff, 0x000000ff, 0x000000ff); // inversion
662 knot[i]->setPixbuf(handles[handle[i].control]);
663 sp_knot_update_ctrl(knot[i]);
665 g_signal_connect(G_OBJECT(knot[i]), "request",
666 G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle[i]);
667 g_signal_connect(G_OBJECT(knot[i]), "moved",
668 G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle[i]);
669 g_signal_connect(G_OBJECT(knot[i]), "grabbed",
670 G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle[i]);
671 g_signal_connect(G_OBJECT(knot[i]), "ungrabbed",
672 G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle[i]);
673 g_signal_connect(G_OBJECT(knot[i]), "event", G_CALLBACK(sp_seltrans_handle_event), (gpointer) &handle[i]);
674 }
675 sp_knot_show(knot[i]);
677 NR::Point const handle_pt(handle[i].x, handle[i].y);
678 // shouldn't have nullary bbox, but knots
679 g_assert(_bbox);
680 NR::Point p( _bbox->min()
681 + ( _bbox->dimensions()
682 * NR::scale(handle_pt) ) );
684 sp_knot_moveto(knot[i], &p);
685 }
686 }
688 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data)
689 {
690 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleGrab(
691 knot, state, *(SPSelTransHandle const *) data
692 );
693 }
695 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint /*state*/, gpointer /*data*/)
696 {
697 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->ungrab();
698 }
700 static void sp_sel_trans_handle_new_event(SPKnot *knot, NR::Point *position, guint state, gpointer data)
701 {
702 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleNewEvent(
703 knot, position, state, *(SPSelTransHandle const *) data
704 );
705 }
707 static gboolean sp_sel_trans_handle_request(SPKnot *knot, NR::Point *position, guint state, gboolean *data)
708 {
709 return SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleRequest(
710 knot, position, state, *(SPSelTransHandle const *) data
711 );
712 }
714 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data)
715 {
716 SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleClick(
717 knot, state, *(SPSelTransHandle const *) data
718 );
719 }
721 void Inkscape::SelTrans::handleClick(SPKnot */*knot*/, guint state, SPSelTransHandle const &handle)
722 {
723 switch (handle.anchor) {
724 case GTK_ANCHOR_CENTER:
725 if (state & GDK_SHIFT_MASK) {
726 // Unset the center position for all selected items
727 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
728 SPItem *it = (SPItem*)(SP_OBJECT(l->data));
729 it->unsetCenter();
730 SP_OBJECT(it)->updateRepr();
731 _center_is_set = false; // center has changed
732 _updateHandles();
733 }
734 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
735 _("Reset center"));
736 }
737 break;
738 default:
739 break;
740 }
741 }
743 void Inkscape::SelTrans::handleGrab(SPKnot *knot, guint /*state*/, SPSelTransHandle const &handle)
744 {
745 switch (handle.anchor) {
746 case GTK_ANCHOR_CENTER:
747 g_object_set(G_OBJECT(_grip),
748 "shape", SP_CTRL_SHAPE_BITMAP,
749 "size", 13.0,
750 NULL);
751 sp_canvas_item_show(_grip);
752 break;
753 default:
754 g_object_set(G_OBJECT(_grip),
755 "shape", SP_CTRL_SHAPE_CROSS,
756 "size", 7.0,
757 NULL);
758 sp_canvas_item_show(_norm);
759 sp_canvas_item_show(_grip);
761 break;
762 }
764 grab(sp_knot_position(knot), handle.x, handle.y, FALSE);
765 }
768 void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, NR::Point *position, guint state, SPSelTransHandle const &handle)
769 {
770 if (!SP_KNOT_IS_GRABBED(knot)) {
771 return;
772 }
774 // in case items have been unhooked from the document, don't
775 // try to continue processing events for them.
776 for (unsigned int i = 0; i < _items.size(); i++) {
777 if (!SP_OBJECT_DOCUMENT(SP_OBJECT(_items[i])) ) {
778 return;
779 }
780 }
782 handle.action(this, handle, *position, state);
783 }
786 gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, NR::Point *position, guint state, SPSelTransHandle const &handle)
787 {
788 if (!SP_KNOT_IS_GRABBED(knot)) {
789 return TRUE;
790 }
792 knot->desktop->setPosition(*position);
794 // When holding shift while rotating or skewing, the transformation will be
795 // relative to the point opposite of the handle; otherwise it will be relative
796 // to the center as set for the selection
797 if ((!(state & GDK_SHIFT_MASK) == !(_state == STATE_ROTATE)) && (&handle != &handle_center)) {
798 _origin = _opposite;
799 _origin_for_bboxpoints = _opposite_for_bboxpoints;
800 _origin_for_specpoints = _opposite_for_specpoints;
801 } else if (_center) {
802 _origin = *_center;
803 _origin_for_bboxpoints = *_center;
804 _origin_for_specpoints = *_center;
805 } else {
806 // FIXME
807 return TRUE;
808 }
809 if (handle.request(this, handle, *position, state)) {
810 sp_knot_set_position(knot, position, state);
811 SP_CTRL(_grip)->moveto(*position);
812 SP_CTRL(_norm)->moveto(_origin);
813 }
815 return TRUE;
816 }
819 void Inkscape::SelTrans::_selChanged(Inkscape::Selection */*selection*/)
820 {
821 if (!_grabbed) {
822 // reread in case it changed on the fly:
823 int prefs_bbox = prefs_get_int_attribute("tools", "bounding_box", 0);
824 _snap_bbox_type = (prefs_bbox ==0)?
825 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
826 //SPItem::APPROXIMATE_BBOX will be replaced by SPItem::VISUAL_BBOX, as soon as the latter is implemented properly
828 _updateVolatileState();
829 _current_relative_affine.set_identity();
830 _center_is_set = false; // center(s) may have changed
831 _updateHandles();
832 }
833 }
835 void Inkscape::SelTrans::_selModified(Inkscape::Selection */*selection*/, guint /*flags*/)
836 {
837 if (!_grabbed) {
838 _updateVolatileState();
839 _current_relative_affine.set_identity();
841 // reset internal flag
842 _changed = false;
844 _center_is_set = false; // center(s) may have changed
846 _updateHandles();
847 }
848 }
850 /*
851 * handlers for handle move-request
852 */
854 /** Returns -1 or 1 according to the sign of x. Returns 1 for 0 and NaN. */
855 static double sign(double const x)
856 {
857 return ( x < 0
858 ? -1
859 : 1 );
860 }
862 gboolean sp_sel_trans_scale_request(Inkscape::SelTrans *seltrans,
863 SPSelTransHandle const &, NR::Point &pt, guint state)
864 {
865 return seltrans->scaleRequest(pt, state);
866 }
868 gboolean sp_sel_trans_stretch_request(Inkscape::SelTrans *seltrans,
869 SPSelTransHandle const &handle, NR::Point &pt, guint state)
870 {
871 return seltrans->stretchRequest(handle, pt, state);
872 }
874 gboolean sp_sel_trans_skew_request(Inkscape::SelTrans *seltrans,
875 SPSelTransHandle const &handle, NR::Point &pt, guint state)
876 {
877 return seltrans->skewRequest(handle, pt, state);
878 }
880 gboolean sp_sel_trans_rotate_request(Inkscape::SelTrans *seltrans,
881 SPSelTransHandle const &, NR::Point &pt, guint state)
882 {
883 return seltrans->rotateRequest(pt, state);
884 }
886 gboolean sp_sel_trans_center_request(Inkscape::SelTrans *seltrans,
887 SPSelTransHandle const &, NR::Point &pt, guint state)
888 {
889 return seltrans->centerRequest(pt, state);
890 }
892 gboolean Inkscape::SelTrans::scaleRequest(NR::Point &pt, guint state)
893 {
895 // Calculate the scale factors, which can be either visual or geometric
896 // depending on which type of bbox is currently being used (see preferences -> selector tool)
897 NR::scale default_scale = calcScaleFactors(_point, pt, _origin);
899 // Find the scale factors for the geometric bbox
900 NR::Point pt_geom = _getGeomHandlePos(pt);
901 NR::scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
903 _absolute_affine = NR::identity(); //Initialize the scaler
905 if (state & GDK_MOD1_MASK) { // scale by an integer multiplier/divider
906 // We're scaling either the visual or the geometric bbox here (see the comment above)
907 for ( unsigned int i = 0 ; i < 2 ; i++ ) {
908 if (fabs(default_scale[i]) > 1) {
909 default_scale[i] = round(default_scale[i]);
910 } else if (default_scale[i] != 0) {
911 default_scale[i] = 1/round(1/(MIN(default_scale[i], 10)));
912 }
913 }
914 // Update the knot position
915 pt = _calcAbsAffineDefault(default_scale);
916 // When scaling by an integer, snapping is not needed
917 } else {
918 // In all other cases we should try to snap now
919 SnapManager &m = _desktop->namedview->snap_manager;
920 m.setup(NULL, _items_const);
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, default_scale, _origin_for_bboxpoints);
940 sn = m.constrainedSnapScale(Snapper::SNAPPOINT_NODE, _snap_points, 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, default_scale, _origin_for_bboxpoints);
950 sn = m.freeSnapScale(Snapper::SNAPPOINT_NODE, _snap_points, 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 _desktop->snapindicator->remove_snappoint();
961 } else if (bd < sd) {
962 // We snapped the bbox (which is either visual or geometric)
963 _desktop->snapindicator->set_new_snappoint(bb);
964 default_scale = NR::scale(bb.getTransformation());
965 // Calculate the new transformation and update the handle position
966 pt = _calcAbsAffineDefault(default_scale);
967 } else {
968 _desktop->snapindicator->set_new_snappoint(sn);
969 // We snapped the special points (e.g. nodes), which are not at the visual bbox
970 // The handle location however (pt) might however be at the visual bbox, so we
971 // will have to calculate pt taking the stroke width into account
972 geom_scale = NR::scale(sn.getTransformation());
973 pt = _calcAbsAffineGeom(geom_scale);
974 }
975 }
977 /* Status text */
978 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
979 _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
980 100 * _absolute_affine[0], 100 * _absolute_affine[3]);
982 return TRUE;
983 }
985 gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, NR::Point &pt, guint state)
986 {
987 NR::Dim2 axis, perp;
988 switch (handle.cursor) {
989 case GDK_TOP_SIDE:
990 case GDK_BOTTOM_SIDE:
991 axis = NR::Y;
992 perp = NR::X;
993 break;
994 case GDK_LEFT_SIDE:
995 case GDK_RIGHT_SIDE:
996 axis = NR::X;
997 perp = NR::Y;
998 break;
999 default:
1000 g_assert_not_reached();
1001 return TRUE;
1002 };
1004 // Calculate the scale factors, which can be either visual or geometric
1005 // depending on which type of bbox is currently being used (see preferences -> selector tool)
1006 NR::scale default_scale = calcScaleFactors(_point, pt, _origin);
1007 default_scale[perp] = 1;
1009 // Find the scale factors for the geometric bbox
1010 NR::Point pt_geom = _getGeomHandlePos(pt);
1011 NR::scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
1012 geom_scale[perp] = 1;
1014 _absolute_affine = NR::identity(); //Initialize the scaler
1016 if (state & GDK_MOD1_MASK) { // stretch by an integer multiplier/divider
1017 if (fabs(default_scale[axis]) > 1) {
1018 default_scale[axis] = round(default_scale[axis]);
1019 } else if (default_scale[axis] != 0) {
1020 default_scale[axis] = 1/round(1/(MIN(default_scale[axis], 10)));
1021 }
1022 // Calculate the new transformation and update the handle position
1023 pt = _calcAbsAffineDefault(default_scale);
1024 // When stretching by an integer, snapping is not needed
1025 } else {
1026 // In all other cases we should try to snap now
1028 SnapManager &m = _desktop->namedview->snap_manager;
1029 m.setup(NULL, _items_const);
1031 Inkscape::SnappedPoint bb, sn;
1032 g_assert(bb.getSnapped() == false); // Check initialization to catch any regression
1033 NR::Coord bd(NR_HUGE);
1034 NR::Coord sd(NR_HUGE);
1036 bool symmetrical = state & GDK_CONTROL_MASK;
1038 bb = m.constrainedSnapStretch(Snapper::SNAPPOINT_BBOX, _bbox_points, default_scale[axis], _origin_for_bboxpoints, axis, symmetrical);
1039 sn = m.constrainedSnapStretch(Snapper::SNAPPOINT_NODE, _snap_points, geom_scale[axis], _origin_for_specpoints, axis, symmetrical);
1041 if (bb.getSnapped()) {
1042 // We snapped the bbox (which is either visual or geometric)
1043 bd = fabs(bb.getTransformation()[axis] - default_scale[axis]);
1044 default_scale[axis] = bb.getTransformation()[axis];
1045 }
1047 if (sn.getSnapped()) {
1048 sd = fabs(sn.getTransformation()[axis] - geom_scale[axis]);
1049 geom_scale[axis] = sn.getTransformation()[axis];
1050 }
1052 if (symmetrical) {
1053 // on ctrl, apply symmetrical scaling instead of stretching
1054 // Preserve aspect ratio, but never flip in the dimension not being edited (by using fabs())
1055 default_scale[perp] = fabs(default_scale[axis]);
1056 geom_scale[perp] = fabs(geom_scale[axis]);
1057 }
1059 if (!(bb.getSnapped() || sn.getSnapped())) {
1060 // We didn't snap at all! Don't update the handle position, just calculate the new transformation
1061 _calcAbsAffineDefault(default_scale);
1062 _desktop->snapindicator->remove_snappoint();
1063 } else if (bd < sd) {
1064 _desktop->snapindicator->set_new_snappoint(bb);
1065 // Calculate the new transformation and update the handle position
1066 pt = _calcAbsAffineDefault(default_scale);
1067 } else {
1068 _desktop->snapindicator->set_new_snappoint(sn);
1069 // We snapped the special points (e.g. nodes), which are not at the visual bbox
1070 // The handle location however (pt) might however be at the visual bbox, so we
1071 // will have to calculate pt taking the stroke width into account
1072 pt = _calcAbsAffineGeom(geom_scale);
1073 }
1074 }
1076 // status text
1077 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1078 _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1079 100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1081 return TRUE;
1082 }
1084 gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, NR::Point &pt, guint state)
1085 {
1086 /* When skewing (or rotating):
1087 * 1) the stroke width will not change. This makes life much easier because we don't have to
1088 * account for that (like for scaling or stretching). As a consequence, all points will
1089 * have the same origin for the transformation and for the snapping.
1090 * 2) When holding shift, the transformation will be relative to the point opposite of
1091 * the handle; otherwise it will be relative to the center as set for the selection
1092 */
1094 NR::Dim2 dim_a;
1095 NR::Dim2 dim_b;
1097 switch (handle.cursor) {
1098 case GDK_SB_H_DOUBLE_ARROW:
1099 dim_a = NR::Y;
1100 dim_b = NR::X;
1101 break;
1102 case GDK_SB_V_DOUBLE_ARROW:
1103 dim_a = NR::X;
1104 dim_b = NR::Y;
1105 break;
1106 default:
1107 g_assert_not_reached();
1108 abort();
1109 break;
1110 }
1112 NR::Point const initial_delta = _point - _origin;
1114 if (fabs(initial_delta[dim_a]) < 1e-15) {
1115 return false;
1116 }
1118 // Calculate the scale factors, which can be either visual or geometric
1119 // depending on which type of bbox is currently being used (see preferences -> selector tool)
1120 NR::scale scale = calcScaleFactors(_point, pt, _origin, false);
1121 NR::scale skew = calcScaleFactors(_point, pt, _origin, true);
1122 scale[dim_b] = 1;
1123 skew[dim_b] = 1;
1125 if (fabs(scale[dim_a]) < 1) {
1126 // Prevent shrinking of the selected object, while allowing mirroring
1127 scale[dim_a] = sign(scale[dim_a]);
1128 } else {
1129 // Allow expanding of the selected object by integer multiples
1130 scale[dim_a] = floor(scale[dim_a] + 0.5);
1131 }
1133 double radians = atan(skew[dim_a] / scale[dim_a]);
1135 if (state & GDK_CONTROL_MASK) {
1136 // Snap to defined angle increments
1137 int snaps = prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12);
1138 if (snaps) {
1139 double sections = floor(radians * snaps / M_PI + .5);
1140 if (fabs(sections) >= snaps / 2) {
1141 sections = sign(sections) * (snaps / 2 - 1);
1142 }
1143 radians = (M_PI / snaps) * sections;
1144 }
1145 skew[dim_a] = tan(radians) * scale[dim_a];
1146 } else {
1147 // Snap to objects, grids, guides
1149 SnapManager &m = _desktop->namedview->snap_manager;
1150 m.setup(NULL, _items_const);
1152 Inkscape::Snapper::ConstraintLine const constraint(component_vectors[dim_b]);
1153 NR::Point const s(skew[dim_a], scale[dim_a]);
1154 Inkscape::SnappedPoint bb = m.constrainedSnapSkew(Inkscape::Snapper::SNAPPOINT_BBOX, _bbox_points, constraint, s, _origin, dim_b);
1155 Inkscape::SnappedPoint sn = m.constrainedSnapSkew(Inkscape::Snapper::SNAPPOINT_NODE, _snap_points, constraint, s, _origin, dim_b);
1157 if (bb.getSnapped() || sn.getSnapped()) {
1158 // We snapped something, so change the skew to reflect it
1159 NR::Coord const bd = bb.getSnapped() ? bb.getTransformation()[0] : NR_HUGE;
1160 NR::Coord const sd = sn.getSnapped() ? sn.getTransformation()[0] : NR_HUGE;
1161 if (bd < sd) {
1162 _desktop->snapindicator->set_new_snappoint(bb);
1163 skew[dim_a] = bd;
1164 } else {
1165 _desktop->snapindicator->set_new_snappoint(sn);
1166 skew[dim_a] = sd;
1167 }
1168 } else {
1169 _desktop->snapindicator->remove_snappoint();
1170 }
1171 }
1173 // Update the handle position
1174 pt[dim_b] = initial_delta[dim_a] * skew[dim_a] + _point[dim_b];
1175 pt[dim_a] = initial_delta[dim_a] * scale[dim_a] + _origin[dim_a];
1177 // Calculate the relative affine
1178 _relative_affine = NR::identity();
1179 _relative_affine[2*dim_a + dim_a] = (pt[dim_a] - _origin[dim_a]) / initial_delta[dim_a];
1180 _relative_affine[2*dim_a + (dim_b)] = (pt[dim_b] - _point[dim_b]) / initial_delta[dim_a];
1181 _relative_affine[2*(dim_b) + (dim_a)] = 0;
1182 _relative_affine[2*(dim_b) + (dim_b)] = 1;
1184 for (int i = 0; i < 2; i++) {
1185 if (fabs(_relative_affine[3*i]) < 1e-15) {
1186 _relative_affine[3*i] = 1e-15;
1187 }
1188 }
1190 // Update the status text
1191 double degrees = mod360symm(Geom::rad_to_deg(radians));
1192 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1193 // TRANSLATORS: don't modify the first ";"
1194 // (it will NOT be displayed as ";" - only the second one will be)
1195 _("<b>Skew</b>: %0.2f°; with <b>Ctrl</b> to snap angle"),
1196 degrees);
1198 return TRUE;
1199 }
1201 gboolean Inkscape::SelTrans::rotateRequest(NR::Point &pt, guint state)
1202 {
1203 /* When rotating (or skewing):
1204 * 1) the stroke width will not change. This makes life much easier because we don't have to
1205 * account for that (like for scaling or stretching). As a consequence, all points will
1206 * have the same origin for the transformation and for the snapping.
1207 * 2) When holding shift, the transformation will be relative to the point opposite of
1208 * the handle; otherwise it will be relative to the center as set for the selection
1209 */
1211 int snaps = prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12);
1213 // rotate affine in rotate
1214 NR::Point const d1 = _point - _origin;
1215 NR::Point const d2 = pt - _origin;
1217 NR::Coord const h1 = NR::L2(d1); // initial radius
1218 if (h1 < 1e-15) return FALSE;
1219 NR::Point q1 = d1 / h1; // normalized initial vector to handle
1220 NR::Coord const h2 = NR::L2(d2); // new radius
1221 if (fabs(h2) < 1e-15) return FALSE;
1222 NR::Point q2 = d2 / h2; // normalized new vector to handle
1224 double radians;
1225 if (state & GDK_CONTROL_MASK) {
1226 // Snap to defined angle increments
1227 double cos_t = NR::dot(q1, q2);
1228 double sin_t = NR::dot(NR::rot90(q1), q2);
1229 radians = atan2(sin_t, cos_t);
1230 if (snaps) {
1231 radians = ( M_PI / snaps ) * floor( radians * snaps / M_PI + .5 );
1232 }
1233 q1 = NR::Point(1, 0);
1234 q2 = NR::Point(cos(radians), sin(radians));
1235 } else {
1236 radians = atan2(NR::dot(NR::rot90(d1), d2),
1237 NR::dot(d1, d2));
1238 }
1240 NR::rotate const r1(q1);
1241 NR::rotate const r2(q2);
1243 // Calculate the relative affine
1244 _relative_affine = NR::Matrix(r2/r1);
1246 // Update the handle position
1247 pt = _point * NR::translate(-_origin) * _relative_affine * NR::translate(_origin);
1249 // Update the status text
1250 double degrees = mod360symm(Geom::rad_to_deg(radians));
1251 _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1252 // TRANSLATORS: don't modify the first ";"
1253 // (it will NOT be displayed as ";" - only the second one will be)
1254 _("<b>Rotate</b>: %0.2f°; with <b>Ctrl</b> to snap angle"), degrees);
1256 return TRUE;
1257 }
1259 gboolean Inkscape::SelTrans::centerRequest(NR::Point &pt, guint state)
1260 {
1261 SnapManager &m = _desktop->namedview->snap_manager;
1262 m.setup(_desktop);
1263 m.freeSnapReturnByRef(Snapper::SNAPPOINT_NODE, pt);
1265 if (state & GDK_CONTROL_MASK) {
1266 if ( fabs(_point[NR::X] - pt[NR::X]) > fabs(_point[NR::Y] - pt[NR::Y]) ) {
1267 pt[NR::Y] = _point[NR::Y];
1268 } else {
1269 pt[NR::X] = _point[NR::X];
1270 }
1271 }
1273 if ( !(state & GDK_SHIFT_MASK) && _bbox ) {
1274 // screen pixels to snap center to bbox
1275 #define SNAP_DIST 5
1276 // FIXME: take from prefs
1277 double snap_dist = SNAP_DIST / _desktop->current_zoom();
1279 for (int i = 0; i < 2; i++) {
1280 if (fabs(pt[i] - _bbox->min()[i]) < snap_dist) {
1281 pt[i] = _bbox->min()[i];
1282 }
1283 if (fabs(pt[i] - _bbox->midpoint()[i]) < snap_dist) {
1284 pt[i] = _bbox->midpoint()[i];
1285 }
1286 if (fabs(pt[i] - _bbox->max()[i]) < snap_dist) {
1287 pt[i] = _bbox->max()[i];
1288 }
1289 }
1290 }
1292 // status text
1293 GString *xs = SP_PX_TO_METRIC_STRING(pt[NR::X], _desktop->namedview->getDefaultMetric());
1294 GString *ys = SP_PX_TO_METRIC_STRING(pt[NR::Y], _desktop->namedview->getDefaultMetric());
1295 _message_context.setF(Inkscape::NORMAL_MESSAGE, _("Move <b>center</b> to %s, %s"), xs->str, ys->str);
1296 g_string_free(xs, FALSE);
1297 g_string_free(ys, FALSE);
1299 return TRUE;
1300 }
1302 /*
1303 * handlers for handle movement
1304 *
1305 */
1307 void sp_sel_trans_stretch(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, NR::Point &pt, guint state)
1308 {
1309 seltrans->stretch(handle, pt, state);
1310 }
1312 void sp_sel_trans_scale(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
1313 {
1314 seltrans->scale(pt, state);
1315 }
1317 void sp_sel_trans_skew(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, NR::Point &pt, guint state)
1318 {
1319 seltrans->skew(handle, pt, state);
1320 }
1322 void sp_sel_trans_rotate(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
1323 {
1324 seltrans->rotate(pt, state);
1325 }
1327 void Inkscape::SelTrans::stretch(SPSelTransHandle const &/*handle*/, NR::Point &/*pt*/, guint /*state*/)
1328 {
1329 transform(_absolute_affine, NR::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1330 }
1332 void Inkscape::SelTrans::scale(NR::Point &/*pt*/, guint /*state*/)
1333 {
1334 transform(_absolute_affine, NR::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1335 }
1337 void Inkscape::SelTrans::skew(SPSelTransHandle const &/*handle*/, NR::Point &/*pt*/, guint /*state*/)
1338 {
1339 transform(_relative_affine, _origin);
1340 }
1342 void Inkscape::SelTrans::rotate(NR::Point &/*pt*/, guint /*state*/)
1343 {
1344 transform(_relative_affine, _origin);
1345 }
1347 void sp_sel_trans_center(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint /*state*/)
1348 {
1349 seltrans->setCenter(pt);
1350 }
1353 void Inkscape::SelTrans::moveTo(NR::Point const &xy, guint state)
1354 {
1355 SnapManager &m = _desktop->namedview->snap_manager;
1356 m.setup(_desktop, _items_const);
1358 /* The amount that we've moved by during this drag */
1359 NR::Point dxy = xy - _point;
1361 bool const alt = (state & GDK_MOD1_MASK);
1362 bool const control = (state & GDK_CONTROL_MASK);
1363 bool const shift = (state & GDK_SHIFT_MASK);
1365 if (alt) {
1367 /* Alt pressed means keep offset: snap the moved distance to the grid.
1368 ** FIXME: this will snap to more than just the grid, nowadays.
1369 */
1371 m.freeSnapReturnByRef(Snapper::SNAPPOINT_NODE, dxy);
1373 } else if (!shift) {
1375 /* We're snapping to things, possibly with a constraint to horizontal or
1376 ** vertical movement. Obtain a list of possible translations and then
1377 ** pick the smallest.
1378 */
1380 /* This will be our list of possible translations */
1381 std::list<Inkscape::SnappedPoint> s;
1383 if (control) {
1385 /* Snap to things, and also constrain to horizontal or vertical movement */
1387 for (unsigned int dim = 0; dim < 2; dim++) {
1388 // When doing a constrained translation, all points will move in the same direction, i.e.
1389 // either horizontally or vertically. Therefore we only have to specify the direction of
1390 // the constraint-line once. The constraint lines are parallel, but might not be colinear.
1391 // Therefore we will have to set the point through which the constraint-line runs
1392 // individually for each point to be snapped; this will be handled however by _snapTransformed()
1393 s.push_back(m.constrainedSnapTranslation(Inkscape::Snapper::SNAPPOINT_BBOX,
1394 _bbox_points,
1395 Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1396 dxy));
1398 s.push_back(m.constrainedSnapTranslation(Inkscape::Snapper::SNAPPOINT_NODE,
1399 _snap_points,
1400 Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1401 dxy));
1402 }
1404 } else {
1406 // Let's leave this timer code here for a while. I'll probably need it in the near future (Diederik van Lierop)
1407 /* GTimeVal starttime;
1408 GTimeVal endtime;
1409 g_get_current_time(&starttime); */
1411 /* Snap to things with no constraint */
1412 s.push_back(m.freeSnapTranslation(Inkscape::Snapper::SNAPPOINT_BBOX, _bbox_points, dxy));
1413 s.push_back(m.freeSnapTranslation(Inkscape::Snapper::SNAPPOINT_NODE, _snap_points, dxy));
1415 /*g_get_current_time(&endtime);
1416 double elapsed = ((((double)endtime.tv_sec - starttime.tv_sec) * G_USEC_PER_SEC + (endtime.tv_usec - starttime.tv_usec))) / 1000.0;
1417 std::cout << "Time spent snapping: " << elapsed << std::endl; */
1418 }
1420 /* Pick one */
1421 Inkscape::SnappedPoint best_snapped_point;
1422 g_assert(best_snapped_point.getDistance() == NR_HUGE);
1423 for (std::list<Inkscape::SnappedPoint>::const_iterator i = s.begin(); i != s.end(); i++) {
1424 if (i->getSnapped()) {
1425 if (i->getDistance() < best_snapped_point.getDistance()) {
1426 best_snapped_point = *i;
1427 dxy = i->getTransformation();
1428 }
1429 }
1430 }
1431 if (best_snapped_point.getSnapped()) {
1432 _desktop->snapindicator->set_new_snappoint(best_snapped_point);
1433 } else {
1434 // We didn't snap, so remove any previous snap indicator
1435 _desktop->snapindicator->remove_snappoint();
1436 if (control) {
1437 // If we didn't snap, then we should still constrain horizontally or vertically
1438 // (When we did snap, then this constraint has already been enforced by
1439 // calling constrainedSnapTranslation() above)
1440 if (fabs(dxy[NR::X]) > fabs(dxy[NR::Y])) {
1441 dxy[NR::Y] = 0;
1442 } else {
1443 dxy[NR::X] = 0;
1444 }
1445 }
1446 }
1447 }
1449 NR::Matrix const move((NR::translate(dxy)));
1450 NR::Point const norm(0, 0);
1451 transform(move, norm);
1453 // status text
1454 GString *xs = SP_PX_TO_METRIC_STRING(dxy[NR::X], _desktop->namedview->getDefaultMetric());
1455 GString *ys = SP_PX_TO_METRIC_STRING(dxy[NR::Y], _desktop->namedview->getDefaultMetric());
1456 _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);
1457 g_string_free(xs, TRUE);
1458 g_string_free(ys, TRUE);
1459 }
1461 // Given a location of a handle at the visual bounding box, find the corresponding location at the
1462 // geometrical bounding box
1463 NR::Point Inkscape::SelTrans::_getGeomHandlePos(NR::Point const &visual_handle_pos)
1464 {
1465 if ( _snap_bbox_type == SPItem::GEOMETRIC_BBOX) {
1466 // When the selector tool is using geometric bboxes, then the handle is already
1467 // located at one of the geometric bbox corners
1468 return visual_handle_pos;
1469 }
1471 if (!_geometric_bbox) {
1472 //_getGeomHandlePos() can only be used after _geometric_bbox has been defined!
1473 return visual_handle_pos;
1474 }
1476 // Using the NR::Rect constructor below ensures that "min() < max()", which is important
1477 // because this will also hold for _bbox, and which is required for get_scale_transform_with_stroke()
1478 NR::Rect new_bbox = NR::Rect(_origin_for_bboxpoints, visual_handle_pos); // new visual bounding box
1479 // Please note that the new_bbox might in fact be just a single line, for example when stretching (in
1480 // which case the handle and origin will be aligned vertically or horizontally)
1481 NR::Point normalized_handle_pos = (visual_handle_pos - new_bbox.min()) * NR::scale(new_bbox.dimensions()).inverse();
1483 // Calculate the absolute affine while taking into account the scaling of the stroke width
1484 int transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1485 NR::Matrix abs_affine = get_scale_transform_with_stroke (*_bbox, _strokewidth, transform_stroke,
1486 new_bbox.min()[NR::X], new_bbox.min()[NR::Y], new_bbox.max()[NR::X], new_bbox.max()[NR::Y]);
1488 // Calculate the scaled geometrical bbox
1489 NR::Rect new_geom_bbox = NR::Rect(_geometric_bbox->min() * abs_affine, _geometric_bbox->max() * abs_affine);
1490 // Find the location of the handle on this new geometrical bbox
1491 return normalized_handle_pos * NR::scale(new_geom_bbox.dimensions()) + new_geom_bbox.min(); //new position of the geometric handle
1492 }
1494 NR::scale Inkscape::calcScaleFactors(NR::Point const &initial_point, NR::Point const &new_point, NR::Point const &origin, bool const skew)
1495 {
1496 // Work out the new scale factors for the bbox
1498 NR::Point const initial_delta = initial_point - origin;
1499 NR::Point const new_delta = new_point - origin;
1500 NR::Point const offset = new_point - initial_point;
1501 NR::scale scale(1, 1);
1503 for ( unsigned int i = 0 ; i < 2 ; i++ ) {
1504 if ( fabs(initial_delta[i]) > 1e-6 ) {
1505 if (skew) {
1506 scale[i] = offset[1-i] / initial_delta[i];
1507 } else {
1508 scale[i] = new_delta[i] / initial_delta[i];
1509 }
1510 }
1511 }
1513 return scale;
1514 }
1516 // Only for scaling/stretching
1517 NR::Point Inkscape::SelTrans::_calcAbsAffineDefault(NR::scale const default_scale)
1518 {
1519 NR::Matrix abs_affine = NR::translate(-_origin) * NR::Matrix(default_scale) * NR::translate(_origin);
1520 NR::Point new_bbox_min = _approximate_bbox->min() * abs_affine;
1521 NR::Point new_bbox_max = _approximate_bbox->max() * abs_affine;
1523 int transform_stroke = false;
1524 gdouble strokewidth = 0;
1526 if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
1527 transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1528 strokewidth = _strokewidth;
1529 }
1531 _absolute_affine = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
1532 new_bbox_min[NR::X], new_bbox_min[NR::Y], new_bbox_max[NR::X], new_bbox_max[NR::Y]);
1534 // return the new handle position
1535 return ( _point - _origin ) * default_scale + _origin;
1536 }
1538 // Only for scaling/stretching
1539 NR::Point Inkscape::SelTrans::_calcAbsAffineGeom(NR::scale const geom_scale)
1540 {
1541 _relative_affine = NR::Matrix(geom_scale);
1542 _absolute_affine = NR::translate(-_origin_for_specpoints) * _relative_affine * NR::translate(_origin_for_specpoints);
1544 bool const transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1545 NR::Rect visual_bbox = get_visual_bbox(_geometric_bbox, _absolute_affine, _strokewidth, transform_stroke);
1547 // return the new handle position
1548 return visual_bbox.min() + visual_bbox.dimensions() * NR::scale(_handle_x, _handle_y);
1549 }
1552 /*
1553 Local Variables:
1554 mode:c++
1555 c-file-style:"stroustrup"
1556 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1557 indent-tabs-mode:nil
1558 fill-column:99
1559 End:
1560 */
1561 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :