Code

Fixed directory for inkscape executable.
[inkscape.git] / src / seltrans.cpp
1 /** @file
2  * @brief Helper object for transforming selected items
3  */
4 /* Authors:
5  *   Lauris Kaplinski <lauris@kaplinski.com>
6  *   bulia byak <buliabyak@users.sf.net>
7  *   Carl Hetherington <inkscape@carlh.net>
8  *   Diederik van Lierop <mail@diedenrezi.nl>
9  *
10  * Copyright (C) 1999-2002 Lauris Kaplinski
11  * Copyright (C) 1999-2008 Authors
12  *
13  * Released under GNU GPL, read the file 'COPYING' for more information
14  */
16 #ifdef HAVE_CONFIG_H
17 # include <config.h>
18 #endif
19 #include <cstring>
20 #include <string>
22 #include <2geom/transforms.h>
23 #include <gdk/gdkkeysyms.h>
24 #include "document.h"
25 #include "sp-namedview.h"
26 #include "desktop.h"
27 #include "desktop-handles.h"
28 #include "desktop-style.h"
29 #include "knot.h"
30 #include "snap.h"
31 #include "selection.h"
32 #include "select-context.h"
33 #include "sp-item.h"
34 #include "sp-item-transform.h"
35 #include "seltrans-handles.h"
36 #include "seltrans.h"
37 #include "selection-chemistry.h"
38 #include "sp-metrics.h"
39 #include "verbs.h"
40 #include <glibmm/i18n.h>
41 #include "display/sp-ctrlline.h"
42 #include "preferences.h"
43 #include "xml/repr.h"
44 #include "mod360.h"
45 #include <2geom/angle.h>
46 #include "display/snap-indicator.h"
49 static void sp_remove_handles(SPKnot *knot[], gint num);
51 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data);
52 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint state, gpointer data);
53 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data);
54 static void sp_sel_trans_handle_new_event(SPKnot *knot, Geom::Point *position, guint32 state, gpointer data);
55 static gboolean sp_sel_trans_handle_request(SPKnot *knot, Geom::Point *p, guint state, gboolean *data);
57 extern GdkPixbuf *handles[];
59 static gboolean sp_seltrans_handle_event(SPKnot *knot, GdkEvent *event, gpointer)
60 {
61     switch (event->type) {
62         case GDK_MOTION_NOTIFY:
63             break;
64         case GDK_KEY_PRESS:
65             if (get_group0_keyval (&event->key) == GDK_space) {
66                 /* stamping mode: both mode(show content and outline) operation with knot */
67                 if (!SP_KNOT_IS_GRABBED(knot)) {
68                     return FALSE;
69                 }
70                 SPDesktop *desktop = knot->desktop;
71                 Inkscape::SelTrans *seltrans = SP_SELECT_CONTEXT(desktop->event_context)->_seltrans;
72                 seltrans->stamp();
73                 return TRUE;
74             }
75             break;
76         default:
77             break;
78     }
80     return FALSE;
81 }
83 Inkscape::SelTrans::SelTrans(SPDesktop *desktop) :
84     _desktop(desktop),
85     _selcue(desktop),
86     _state(STATE_SCALE),
87     _show(SHOW_CONTENT),
88     _grabbed(false),
89     _show_handles(true),
90     _bbox(),
91     _approximate_bbox(),
92     _absolute_affine(Geom::Scale(1,1)),
93     _opposite(Geom::Point(0,0)),
94     _opposite_for_specpoints(Geom::Point(0,0)),
95     _opposite_for_bboxpoints(Geom::Point(0,0)),
96     _origin_for_specpoints(Geom::Point(0,0)),
97     _origin_for_bboxpoints(Geom::Point(0,0)),
98     _chandle(NULL),
99     _stamp_cache(NULL),
100     _message_context(desktop->messageStack())
102     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
103     int prefs_bbox = prefs->getBool("/tools/bounding_box");
104     _snap_bbox_type = !prefs_bbox ?
105         SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
107     g_return_if_fail(desktop != NULL);
109     for (int i = 0; i < 8; i++) {
110         _shandle[i] = NULL;
111         _rhandle[i] = NULL;
112     }
114     _updateVolatileState();
115     _current_relative_affine.setIdentity();
117     _center_is_set = false; // reread _center from items, or set to bbox midpoint
119     _updateHandles();
121     _selection = sp_desktop_selection(desktop);
123     _norm = sp_canvas_item_new(sp_desktop_controls(desktop),
124                                SP_TYPE_CTRL,
125                                "anchor", GTK_ANCHOR_CENTER,
126                                "mode", SP_CTRL_MODE_COLOR,
127                                "shape", SP_CTRL_SHAPE_BITMAP,
128                                "size", 13.0,
129                                "filled", TRUE,
130                                "fill_color", 0x00000000,
131                                "stroked", TRUE,
132                                "stroke_color", 0x000000a0,
133                                "pixbuf", handles[12],
134                                NULL);
136     _grip = sp_canvas_item_new(sp_desktop_controls(desktop),
137                                SP_TYPE_CTRL,
138                                "anchor", GTK_ANCHOR_CENTER,
139                                "mode", SP_CTRL_MODE_XOR,
140                                "shape", SP_CTRL_SHAPE_CROSS,
141                                "size", 7.0,
142                                "filled", TRUE,
143                                "fill_color", 0xffffff7f,
144                                "stroked", TRUE,
145                                "stroke_color", 0xffffffff,
146                                "pixbuf", handles[12],
147                                NULL);
149     sp_canvas_item_hide(_grip);
150     sp_canvas_item_hide(_norm);
152     for (int i = 0; i < 4; i++) {
153         _l[i] = sp_canvas_item_new(sp_desktop_controls(desktop), SP_TYPE_CTRLLINE, NULL);
154         sp_canvas_item_hide(_l[i]);
155     }
157     _sel_changed_connection = _selection->connectChanged(
158         sigc::mem_fun(*this, &Inkscape::SelTrans::_selChanged)
159         );
161     _sel_modified_connection = _selection->connectModified(
162         sigc::mem_fun(*this, &Inkscape::SelTrans::_selModified)
163         );
166 Inkscape::SelTrans::~SelTrans()
168     _sel_changed_connection.disconnect();
169     _sel_modified_connection.disconnect();
171     for (unsigned int i = 0; i < 8; i++) {
172         if (_shandle[i]) {
173             g_object_unref(G_OBJECT(_shandle[i]));
174             _shandle[i] = NULL;
175         }
176         if (_rhandle[i]) {
177             g_object_unref(G_OBJECT(_rhandle[i]));
178             _rhandle[i] = NULL;
179         }
180     }
181     if (_chandle) {
182         g_object_unref(G_OBJECT(_chandle));
183         _chandle = NULL;
184     }
186     if (_norm) {
187         gtk_object_destroy(GTK_OBJECT(_norm));
188         _norm = NULL;
189     }
190     if (_grip) {
191         gtk_object_destroy(GTK_OBJECT(_grip));
192         _grip = NULL;
193     }
194     for (int i = 0; i < 4; i++) {
195         if (_l[i]) {
196             gtk_object_destroy(GTK_OBJECT(_l[i]));
197             _l[i] = NULL;
198         }
199     }
201     for (unsigned i = 0; i < _items.size(); i++) {
202         sp_object_unref(SP_OBJECT(_items[i]), NULL);
203     }
205     _items.clear();
206     _items_const.clear();
207     _items_affines.clear();
208     _items_centers.clear();
211 void Inkscape::SelTrans::resetState()
213     _state = STATE_SCALE;
216 void Inkscape::SelTrans::increaseState()
218     if (_state == STATE_SCALE) {
219         _state = STATE_ROTATE;
220     } else {
221         _state = STATE_SCALE;
222     }
224     _center_is_set = true; // no need to reread center
226     _updateHandles();
229 void Inkscape::SelTrans::setCenter(Geom::Point const &p)
231     _center = p;
232     _center_is_set = true;
234     // Write the new center position into all selected items
235     for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
236         SPItem *it = (SPItem*)SP_OBJECT(l->data);
237         it->setCenter(p);
238         // only set the value; updating repr and document_done will be done once, on ungrab
239     }
241     _updateHandles();
244 void Inkscape::SelTrans::grab(Geom::Point const &p, gdouble x, gdouble y, bool show_handles)
246     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
247     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
249     g_return_if_fail(!_grabbed);
251     _grabbed = true;
252     _show_handles = show_handles;
253     _updateVolatileState();
254     _current_relative_affine.setIdentity();
256     _changed = false;
258     if (_empty) {
259         return;
260     }
262     for (GSList const *l = selection->itemList(); l; l = l->next) {
263         SPItem *it = (SPItem *)sp_object_ref(SP_OBJECT(l->data), NULL);
264         _items.push_back(it);
265         _items_const.push_back(it);
266         _items_affines.push_back(sp_item_i2d_affine(it));
267         _items_centers.push_back(it->getCenter()); // for content-dragging, we need to remember original centers
268     }
270     _handle_x = x;
271     _handle_y = y;
273     // The selector tool should snap the bbox, special snappoints, and path nodes
274     // (The special points are the handles, center, rotation axis, font baseline, ends of spiral, etc.)
276     // First, determine the bounding box for snapping ...
277     _bbox = selection->bounds(_snap_bbox_type);
278     _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX); // Used for correctly scaling the strokewidth
279     _geometric_bbox = selection->bounds(SPItem::GEOMETRIC_BBOX);
280     _point = p;
281     if (_geometric_bbox) {
282         _point_geom = _geometric_bbox->min() + _geometric_bbox->dimensions() * Geom::Scale(x, y);
283     } else {
284         _point_geom = p;
285     }
287     // Next, get all points to consider for snapping
288     SnapManager const &m = _desktop->namedview->snap_manager;
289         Inkscape::SnapPreferences local_snapprefs = m.snapprefs;
290         local_snapprefs.setSnapToItemNode(true); // We should get at least the cusp nodes here. This might
291         // have been turned off because (for example) the user only want paths as a snap target, not nodes
292         // but as a snap source we still need some nodes though!
293     _snap_points.clear();
294         _snap_points = selection->getSnapPoints(&local_snapprefs);
295         std::vector<std::pair<Geom::Point, int> > snap_points_hull = selection->getSnapPointsConvexHull(&local_snapprefs);
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                 if (prefs->getBool("/options/snapclosestonly/value", false)) {
301                         _keepClosestPointOnly(_snap_points, p);
302                 } else {
303                         _snap_points = snap_points_hull;
304                 }
305                 // Unfortunately, by now we will have lost the font-baseline snappoints :-(
306         }
308     // Find bbox hulling all special points, which excludes stroke width. Here we need to include the
309     // path nodes, for example because a rectangle which has been converted to a path doesn't have
310     // any other special points
311     Geom::Rect snap_points_bbox;
312     if ( snap_points_hull.empty() == false ) {
313         std::vector<std::pair<Geom::Point, int> >::iterator i = snap_points_hull.begin();
314         snap_points_bbox = Geom::Rect((*i).first, (*i).first);
315         i++;
316         while (i != snap_points_hull.end()) {
317             snap_points_bbox.expandTo((*i).first);
318             i++;
319         }
320     }
322     _bbox_points.clear();
323     if (_bbox) {
324         if (m.snapprefs.getSnapModeBBox()) {
325                 getBBoxPoints(_bbox, &_bbox_points, false, true, m.snapprefs.getSnapBBoxEdgeMidpoints(), m.snapprefs.getSnapBBoxMidpoints());
326         }
327         // There are two separate "opposites" (i.e. opposite w.r.t. the handle being dragged):
328         //  - one for snapping the boundingbox, which can be either visual or geometric
329         //  - one for snapping the special points
330         // The "opposite" in case of a geometric boundingbox always coincides with the "opposite" for the special points
331         // These distinct "opposites" are needed in the snapmanager to avoid bugs such as #sf1540195 (in which
332         // a box is caught between two guides)
333         _opposite_for_bboxpoints = _bbox->min() + _bbox->dimensions() * Geom::Scale(1-x, 1-y);
334         _opposite_for_specpoints = snap_points_bbox.min() + snap_points_bbox.dimensions() * Geom::Scale(1-x, 1-y);
335         _opposite = _opposite_for_bboxpoints;
336     }
338     // When snapping the node closest to the mouse pointer is absolutely preferred over the closest snap
339     // (i.e. when weight == 1), then we will not even try to snap to other points and discard those other
340     // points immediately.
342         if (prefs->getBool("/options/snapclosestonly/value", false)) {
343         if (m.snapprefs.getSnapModeNode()) {
344                         _keepClosestPointOnly(_snap_points, p);
345         } else {
346                 _snap_points.clear(); // don't keep any point
347         }
349         if (m.snapprefs.getSnapModeBBox()) {
350                         _keepClosestPointOnly(_bbox_points, p);
351                 } else {
352                         _bbox_points.clear(); // don't keep any point
353                 }
355         g_assert(_bbox_points.size() < 2 && _snap_points.size() < 2);
356         if (_snap_points.size() == 1 && _bbox_points.size() == 1) { //both vectors can only have either one or zero elements
357                 // So we have exactly one bbox corner and one node left; now find out which is closest and delete the other one
358                 if (Geom::L2((_snap_points.at(0)).first - p) < Geom::L2((_bbox_points.at(0)).first - p)) {
359                         _bbox_points.clear();
360                 } else {
361                         _snap_points.clear();
362                 }
363                 }
365         // Optionally, show the snap source
366         if (!(_state == STATE_ROTATE && x != 0.5 && y != 0.5)) { // but not when we're draging a rotation handle, because that won't snap
367                         // Now either _bbox_points or _snap_points has a single element, the other one has zero..... or both have zero elements
368                         g_assert((_bbox_points.size() + _snap_points.size()) < 2);
369                         if (m.snapprefs.getSnapEnabledGlobally()) {
370                                 if (_bbox_points.size() == 1) {
371                                         _desktop->snapindicator->set_new_snapsource(_bbox_points.at(0));
372                                 } else if (_snap_points.size() == 1){
373                                         _desktop->snapindicator->set_new_snapsource(_snap_points.at(0));
374                                 }
375                         }
376         }
377     }
379         //sp_event_context_snap_window_open(_desktop->event_context);
381     if ((x != -1) && (y != -1)) {
382         sp_canvas_item_show(_norm);
383         sp_canvas_item_show(_grip);
384     }
386     if (_show == SHOW_OUTLINE) {
387         for (int i = 0; i < 4; i++)
388             sp_canvas_item_show(_l[i]);
389     }
391     _updateHandles();
392     g_return_if_fail(_stamp_cache == NULL);
395 void Inkscape::SelTrans::transform(Geom::Matrix const &rel_affine, Geom::Point const &norm)
397     g_return_if_fail(_grabbed);
398     g_return_if_fail(!_empty);
400     Geom::Matrix const affine( Geom::Translate(-norm) * rel_affine * Geom::Translate(norm) );
402     if (_show == SHOW_CONTENT) {
403         // update the content
404         for (unsigned i = 0; i < _items.size(); i++) {
405             SPItem &item = *_items[i];
406             Geom::Matrix const &prev_transform = _items_affines[i];
407             sp_item_set_i2d_affine(&item, prev_transform * affine);
408         }
409     } else {
410         if (_bbox) {
411             Geom::Point p[4];
412             /* update the outline */
413             for (unsigned i = 0 ; i < 4 ; i++) {
414                 p[i] = _bbox->corner(i) * affine;
415             }
416             for (unsigned i = 0 ; i < 4 ; i++) {
417                 sp_ctrlline_set_coords(SP_CTRLLINE(_l[i]), p[i], p[(i+1)%4]);
418             }
419         }
420     }
422     _current_relative_affine = affine;
423     _changed = true;
424     _updateHandles();
427 void Inkscape::SelTrans::ungrab()
429     g_return_if_fail(_grabbed);
430     _grabbed = false;
431     _show_handles = true;
433     //sp_event_context_snap_window_closed(_desktop->event_context);
435     _desktop->snapindicator->remove_snapsource();
437     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
438     _updateVolatileState();
440     for (unsigned i = 0; i < _items.size(); i++) {
441         sp_object_unref(SP_OBJECT(_items[i]), NULL);
442     }
444     sp_canvas_item_hide(_norm);
445     sp_canvas_item_hide(_grip);
447     if (_show == SHOW_OUTLINE) {
448         for (int i = 0; i < 4; i++)
449             sp_canvas_item_hide(_l[i]);
450     }
452     if (_stamp_cache) {
453         g_slist_free(_stamp_cache);
454         _stamp_cache = NULL;
455     }
457     _message_context.clear();
459     if (!_empty && _changed) {
460         sp_selection_apply_affine(selection, _current_relative_affine, (_show == SHOW_OUTLINE)? true : false);
461         if (_center) {
462             *_center *= _current_relative_affine;
463             _center_is_set = true;
464         }
466 // If dragging showed content live, sp_selection_apply_affine cannot change the centers
467 // appropriately - it does not know the original positions of the centers (all objects already have
468 // the new bboxes). So we need to reset the centers from our saved array.
469         if (_show != SHOW_OUTLINE && !_current_relative_affine.isTranslation()) {
470             for (unsigned i = 0; i < _items_centers.size(); i++) {
471                 SPItem *currentItem = _items[i];
472                 if (currentItem->isCenterSet()) { // only if it's already set
473                     currentItem->setCenter (_items_centers[i] * _current_relative_affine);
474                     SP_OBJECT(currentItem)->updateRepr();
475                 }
476             }
477         }
479         _items.clear();
480         _items_const.clear();
481         _items_affines.clear();
482         _items_centers.clear();
484         if (_current_relative_affine.isTranslation()) {
485             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
486                              _("Move"));
487         } else if (_current_relative_affine.isScale()) {
488             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
489                              _("Scale"));
490         } else if (_current_relative_affine.isRotation()) {
491             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
492                              _("Rotate"));
493         } else {
494             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
495                              _("Skew"));
496         }
498     } else {
500         if (_center_is_set) {
501             // we were dragging center; update reprs and commit undoable action
502             for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
503                 SPItem *it = (SPItem*)SP_OBJECT(l->data);
504                 SP_OBJECT(it)->updateRepr();
505             }
506             sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
507                             _("Set center"));
508         }
510         _items.clear();
511         _items_const.clear();
512         _items_affines.clear();
513         _items_centers.clear();
514         _updateHandles();
515     }
518 /* fixme: This is really bad, as we compare positions for each stamp (Lauris) */
519 /* fixme: IMHO the best way to keep sort cache would be to implement timestamping at last */
521 void Inkscape::SelTrans::stamp()
523     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
525     bool fixup = !_grabbed;
526     if ( fixup && _stamp_cache ) {
527         // TODO - give a proper fix. Simple temproary work-around for the grab() issue
528         g_slist_free(_stamp_cache);
529         _stamp_cache = NULL;
530     }
532     /* stamping mode */
533     if (!_empty) {
534         GSList *l;
535         if (_stamp_cache) {
536             l = _stamp_cache;
537         } else {
538             /* Build cache */
539             l  = g_slist_copy((GSList *) selection->itemList());
540             l  = g_slist_sort(l, (GCompareFunc) sp_object_compare_position);
541             _stamp_cache = l;
542         }
544         while (l) {
545             SPItem *original_item = SP_ITEM(l->data);
546             Inkscape::XML::Node *original_repr = SP_OBJECT_REPR(original_item);
548             // remember the position of the item
549             gint pos = original_repr->position();
550             // remember parent
551             Inkscape::XML::Node *parent = sp_repr_parent(original_repr);
553             Inkscape::XML::Node *copy_repr = original_repr->duplicate(parent->document());
555             // add the new repr to the parent
556             parent->appendChild(copy_repr);
557             // move to the saved position
558             copy_repr->setPosition(pos > 0 ? pos : 0);
560             SPItem *copy_item = (SPItem *) sp_desktop_document(_desktop)->getObjectByRepr(copy_repr);
562             Geom::Matrix const *new_affine;
563             if (_show == SHOW_OUTLINE) {
564                 Geom::Matrix const i2d(sp_item_i2d_affine(original_item));
565                 Geom::Matrix const i2dnew( i2d * _current_relative_affine );
566                 sp_item_set_i2d_affine(copy_item, i2dnew);
567                 new_affine = &copy_item->transform;
568             } else {
569                 new_affine = &original_item->transform;
570             }
572             sp_item_write_transform(copy_item, copy_repr, *new_affine);
574             if ( copy_item->isCenterSet() && _center ) {
575                 copy_item->setCenter(*_center * _current_relative_affine);
576             }
578             Inkscape::GC::release(copy_repr);
579             l = l->next;
580         }
581         sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
582                          _("Stamp"));
583     }
585     if ( fixup && _stamp_cache ) {
586         // TODO - give a proper fix. Simple temproary work-around for the grab() issue
587         g_slist_free(_stamp_cache);
588         _stamp_cache = NULL;
589     }
592 void Inkscape::SelTrans::_updateHandles()
594     if ( !_show_handles || _empty )
595     {
596         sp_remove_handles(_shandle, 8);
597         sp_remove_handles(_rhandle, 8);
598         sp_remove_handles(&_chandle, 1);
599         return;
600     }
602     // center handle
603     if ( _chandle == NULL ) {
604         _chandle = sp_knot_new(_desktop, _("<b>Center</b> of rotation and skewing: drag to reposition; scaling with Shift also uses this center"));
606         _chandle->setShape (SP_CTRL_SHAPE_BITMAP);
607         _chandle->setSize (13);
608         _chandle->setAnchor (handle_center.anchor);
609         _chandle->setMode (SP_CTRL_MODE_XOR);
610         _chandle->setFill(0x00000000, 0x00000000, 0x00000000);
611         _chandle->setStroke(0x000000ff, 0xff0000b0, 0xff0000b0);
612         _chandle->setPixbuf(handles[handle_center.control]);
613         sp_knot_update_ctrl(_chandle);
615         g_signal_connect(G_OBJECT(_chandle), "request",
616                          G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle_center);
617         g_signal_connect(G_OBJECT(_chandle), "moved",
618                          G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle_center);
619         g_signal_connect(G_OBJECT(_chandle), "grabbed",
620                          G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle_center);
621         g_signal_connect(G_OBJECT(_chandle), "ungrabbed",
622                          G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle_center);
623         g_signal_connect(G_OBJECT(_chandle), "clicked",
624                          G_CALLBACK(sp_sel_trans_handle_click), (gpointer) &handle_center);
625     }
627     sp_remove_handles(&_chandle, 1);
628     if ( _state == STATE_SCALE ) {
629         sp_remove_handles(_rhandle, 8);
630         _showHandles(_shandle, handles_scale, 8,
631                     _("<b>Squeeze or stretch</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"),
632                     _("<b>Scale</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"));
633     } else {
634         sp_remove_handles(_shandle, 8);
635         _showHandles(_rhandle, handles_rotate, 8,
636                     _("<b>Skew</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to skew around the opposite side"),
637                     _("<b>Rotate</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to rotate around the opposite corner"));
638     }
640     if (!_center_is_set) {
641         _center = _desktop->selection->center();
642         _center_is_set = true;
643     }
645     if ( _state == STATE_SCALE || !_center ) {
646         sp_knot_hide(_chandle);
647     } else {
648         sp_knot_show(_chandle);
649         sp_knot_moveto(_chandle, *_center);
650     }
653 void Inkscape::SelTrans::_updateVolatileState()
655     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
656     _empty = selection->isEmpty();
658     if (_empty) {
659         return;
660     }
662     //Update the bboxes
663     _bbox = selection->bounds(_snap_bbox_type);
664     _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX);
666     if (!_bbox) {
667         _empty = true;
668         return;
669     }
671     _strokewidth = stroke_average_width (selection->itemList());
674 static void sp_remove_handles(SPKnot *knot[], gint num)
676     for (int i = 0; i < num; i++) {
677         if (knot[i] != NULL) {
678             sp_knot_hide(knot[i]);
679         }
680     }
683 void Inkscape::SelTrans::_showHandles(SPKnot *knot[], SPSelTransHandle const handle[], gint num,
684                              gchar const *even_tip, gchar const *odd_tip)
686     g_return_if_fail( !_empty );
688     for (int i = 0; i < num; i++) {
689         if (knot[i] == NULL) {
690             knot[i] = sp_knot_new(_desktop, i % 2 ? even_tip : odd_tip);
692             knot[i]->setShape (SP_CTRL_SHAPE_BITMAP);
693             knot[i]->setSize (13);
694             knot[i]->setAnchor (handle[i].anchor);
695             knot[i]->setMode (SP_CTRL_MODE_XOR);
696             knot[i]->setFill(0x000000ff, 0x00ff6600, 0x00ff6600); // inversion, green, green
697             knot[i]->setStroke(0x000000ff, 0x000000ff, 0x000000ff); // inversion
698             knot[i]->setPixbuf(handles[handle[i].control]);
699             sp_knot_update_ctrl(knot[i]);
701             g_signal_connect(G_OBJECT(knot[i]), "request",
702                              G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle[i]);
703             g_signal_connect(G_OBJECT(knot[i]), "moved",
704                              G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle[i]);
705             g_signal_connect(G_OBJECT(knot[i]), "grabbed",
706                              G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle[i]);
707             g_signal_connect(G_OBJECT(knot[i]), "ungrabbed",
708                              G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle[i]);
709             g_signal_connect(G_OBJECT(knot[i]), "event", G_CALLBACK(sp_seltrans_handle_event), (gpointer) &handle[i]);
710         }
711         sp_knot_show(knot[i]);
713         Geom::Point const handle_pt(handle[i].x, handle[i].y);
714         // shouldn't have nullary bbox, but knots
715         g_assert(_bbox);
716         Geom::Point p( _bbox->min()
717                      + ( _bbox->dimensions()
718                          * Geom::Scale(handle_pt) ) );
720         sp_knot_moveto(knot[i], p);
721     }
724 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data)
726     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleGrab(
727         knot, state, *(SPSelTransHandle const *) data
728         );
731 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint /*state*/, gpointer /*data*/)
733     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->ungrab();
736 static void sp_sel_trans_handle_new_event(SPKnot *knot, Geom::Point *position, guint state, gpointer data)
738     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleNewEvent(
739         knot, position, state, *(SPSelTransHandle const *) data
740         );
743 static gboolean sp_sel_trans_handle_request(SPKnot *knot, Geom::Point *position, guint state, gboolean *data)
745     return SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleRequest(
746         knot, position, state, *(SPSelTransHandle const *) data
747         );
750 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data)
752     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleClick(
753         knot, state, *(SPSelTransHandle const *) data
754         );
757 void Inkscape::SelTrans::handleClick(SPKnot */*knot*/, guint state, SPSelTransHandle const &handle)
759     switch (handle.anchor) {
760         case GTK_ANCHOR_CENTER:
761             if (state & GDK_SHIFT_MASK) {
762                 // Unset the  center position for all selected items
763                 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
764                     SPItem *it = (SPItem*)(SP_OBJECT(l->data));
765                     it->unsetCenter();
766                     SP_OBJECT(it)->updateRepr();
767                     _center_is_set = false;  // center has changed
768                     _updateHandles();
769                 }
770                 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
771                                         _("Reset center"));
772             }
773             break;
774         default:
775             break;
776     }
779 void Inkscape::SelTrans::handleGrab(SPKnot *knot, guint /*state*/, SPSelTransHandle const &handle)
781     switch (handle.anchor) {
782         case GTK_ANCHOR_CENTER:
783             g_object_set(G_OBJECT(_grip),
784                          "shape", SP_CTRL_SHAPE_BITMAP,
785                          "size", 13.0,
786                          NULL);
787             sp_canvas_item_show(_grip);
788             break;
789         default:
790             g_object_set(G_OBJECT(_grip),
791                          "shape", SP_CTRL_SHAPE_CROSS,
792                          "size", 7.0,
793                          NULL);
794             sp_canvas_item_show(_norm);
795             sp_canvas_item_show(_grip);
797             break;
798     }
800     grab(sp_knot_position(knot), handle.x, handle.y, FALSE);
804 void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const &handle)
806     if (!SP_KNOT_IS_GRABBED(knot)) {
807         return;
808     }
810     // in case items have been unhooked from the document, don't
811     // try to continue processing events for them.
812     for (unsigned int i = 0; i < _items.size(); i++) {
813         if (!SP_OBJECT_DOCUMENT(SP_OBJECT(_items[i])) ) {
814             return;
815         }
816     }
818     handle.action(this, handle, *position, state);
822 gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const &handle)
824     if (!SP_KNOT_IS_GRABBED(knot)) {
825         return TRUE;
826     }
828     knot->desktop->setPosition(*position);
830     // When holding shift while rotating or skewing, the transformation will be
831     // relative to the point opposite of the handle; otherwise it will be relative
832     // to the center as set for the selection
833     if ((!(state & GDK_SHIFT_MASK) == !(_state == STATE_ROTATE)) && (&handle != &handle_center)) {
834         _origin = _opposite;
835         _origin_for_bboxpoints = _opposite_for_bboxpoints;
836         _origin_for_specpoints = _opposite_for_specpoints;
837     } else if (_center) {
838         _origin = *_center;
839         _origin_for_bboxpoints = *_center;
840         _origin_for_specpoints = *_center;
841     } else {
842         // FIXME
843         return TRUE;
844     }
845     if (handle.request(this, handle, *position, state)) {
846         sp_knot_set_position(knot, *position, state);
847         SP_CTRL(_grip)->moveto(*position);
848         SP_CTRL(_norm)->moveto(_origin);
849     }
851     return TRUE;
855 void Inkscape::SelTrans::_selChanged(Inkscape::Selection */*selection*/)
857     if (!_grabbed) {
858         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
859         // reread in case it changed on the fly:
860         int prefs_bbox = prefs->getBool("/tools/bounding_box");
861          _snap_bbox_type = !prefs_bbox ?
862             SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
863         //SPItem::APPROXIMATE_BBOX will be replaced by SPItem::VISUAL_BBOX, as soon as the latter is implemented properly
865         _updateVolatileState();
866         _current_relative_affine.setIdentity();
867         _center_is_set = false; // center(s) may have changed
868         _updateHandles();
869     }
872 void Inkscape::SelTrans::_selModified(Inkscape::Selection */*selection*/, guint /*flags*/)
874     if (!_grabbed) {
875         _updateVolatileState();
876         _current_relative_affine.setIdentity();
878         // reset internal flag
879         _changed = false;
881         _center_is_set = false;  // center(s) may have changed
883         _updateHandles();
884     }
887 /*
888  * handlers for handle move-request
889  */
891 /** Returns -1 or 1 according to the sign of x.  Returns 1 for 0 and NaN. */
892 static double sign(double const x)
894     return ( x < 0
895              ? -1
896              : 1 );
899 gboolean sp_sel_trans_scale_request(Inkscape::SelTrans *seltrans,
900                                     SPSelTransHandle const &, Geom::Point &pt, guint state)
902     return seltrans->scaleRequest(pt, state);
905 gboolean sp_sel_trans_stretch_request(Inkscape::SelTrans *seltrans,
906                                       SPSelTransHandle const &handle, Geom::Point &pt, guint state)
908     return seltrans->stretchRequest(handle, pt, state);
911 gboolean sp_sel_trans_skew_request(Inkscape::SelTrans *seltrans,
912                                    SPSelTransHandle const &handle, Geom::Point &pt, guint state)
914     return seltrans->skewRequest(handle, pt, state);
917 gboolean sp_sel_trans_rotate_request(Inkscape::SelTrans *seltrans,
918                                      SPSelTransHandle const &, Geom::Point &pt, guint state)
920     return seltrans->rotateRequest(pt, state);
923 gboolean sp_sel_trans_center_request(Inkscape::SelTrans *seltrans,
924                                      SPSelTransHandle const &, Geom::Point &pt, guint state)
926     return seltrans->centerRequest(pt, state);
929 gboolean Inkscape::SelTrans::scaleRequest(Geom::Point &pt, guint state)
932     // Calculate the scale factors, which can be either visual or geometric
933     // depending on which type of bbox is currently being used (see preferences -> selector tool)
934     Geom::Scale default_scale = calcScaleFactors(_point, pt, _origin);
936     // Find the scale factors for the geometric bbox
937     Geom::Point pt_geom = _getGeomHandlePos(pt);
938     Geom::Scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
940     _absolute_affine = Geom::identity(); //Initialize the scaler
942     if (state & GDK_MOD1_MASK) { // scale by an integer multiplier/divider
943         // We're scaling either the visual or the geometric bbox here (see the comment above)
944         for ( unsigned int i = 0 ; i < 2 ; i++ ) {
945             if (fabs(default_scale[i]) > 1) {
946                 default_scale[i] = round(default_scale[i]);
947             } else if (default_scale[i] != 0) {
948                 default_scale[i] = 1/round(1/(MIN(default_scale[i], 10)));
949             }
950         }
951         // Update the knot position
952         pt = _calcAbsAffineDefault(default_scale);
953         // When scaling by an integer, snapping is not needed
954     } else {
955         // In all other cases we should try to snap now
956         SnapManager &m = _desktop->namedview->snap_manager;
957         m.setup(_desktop, false, _items_const);
959         Inkscape::SnappedPoint bb, sn;
960         Geom::Coord bd(NR_HUGE);
961         Geom::Coord sd(NR_HUGE);
963         if ((state & GDK_CONTROL_MASK) || _desktop->isToolboxButtonActive ("lock")) {
964             // Scale is locked to a 1:1 aspect ratio, so that s[X] must be made to equal s[Y].
965             //
966             // The aspect-ratio must be locked before snapping
967             if (fabs(default_scale[Geom::X]) > fabs(default_scale[Geom::Y])) {
968                 default_scale[Geom::X] = fabs(default_scale[Geom::Y]) * sign(default_scale[Geom::X]);
969                 geom_scale[Geom::X] = fabs(geom_scale[Geom::Y]) * sign(geom_scale[Geom::X]);
970             } else {
971                 default_scale[Geom::Y] = fabs(default_scale[Geom::X]) * sign(default_scale[Geom::Y]);
972                 geom_scale[Geom::Y] = fabs(geom_scale[Geom::X]) * sign(geom_scale[Geom::Y]);
973             }
975             // Snap along a suitable constraint vector from the origin.
976             bb = m.constrainedSnapScale(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, default_scale, _origin_for_bboxpoints);
977             sn = m.constrainedSnapScale(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, geom_scale, _origin_for_specpoints);
979             /* Choose the smaller difference in scale.  Since s[X] == s[Y] we can
980             ** just compare difference in s[X].
981             */
982             bd = bb.getSnapped() ? fabs(bb.getTransformation()[Geom::X] - default_scale[Geom::X]) : NR_HUGE;
983             sd = sn.getSnapped() ? fabs(sn.getTransformation()[Geom::X] - geom_scale[Geom::X]) : NR_HUGE;
984         } else {
985             /* Scale aspect ratio is unlocked */
986             bb = m.freeSnapScale(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, default_scale, _origin_for_bboxpoints);
987             sn = m.freeSnapScale(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, geom_scale, _origin_for_specpoints);
989             /* Pick the snap that puts us closest to the original scale */
990             bd = bb.getSnapped() ? fabs(Geom::L2(bb.getTransformation()) - Geom::L2(Geom::Point(default_scale[Geom::X], default_scale[Geom::Y]))) : NR_HUGE;
991             sd = sn.getSnapped() ? fabs(Geom::L2(sn.getTransformation()) - Geom::L2(Geom::Point(geom_scale[Geom::X], geom_scale[Geom::Y]))) : NR_HUGE;
992         }
994         if (!(bb.getSnapped() || sn.getSnapped())) {
995             // We didn't snap at all! Don't update the handle position, just calculate the new transformation
996             _calcAbsAffineDefault(default_scale);
997             _desktop->snapindicator->remove_snaptarget();
998         } else if (bd < sd) {
999             // We snapped the bbox (which is either visual or geometric)
1000             _desktop->snapindicator->set_new_snaptarget(bb);
1001             default_scale = Geom::Scale(bb.getTransformation());
1002             // Calculate the new transformation and update the handle position
1003             pt = _calcAbsAffineDefault(default_scale);
1004         } else {
1005             _desktop->snapindicator->set_new_snaptarget(sn);
1006             // We snapped the special points (e.g. nodes), which are not at the visual bbox
1007             // The handle location however (pt) might however be at the visual bbox, so we
1008             // will have to calculate pt taking the stroke width into account
1009             geom_scale = Geom::Scale(sn.getTransformation());
1010             pt = _calcAbsAffineGeom(geom_scale);
1011         }
1012     }
1014     /* Status text */
1015     _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1016                           _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1017                           100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1019     return TRUE;
1022 gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1024     Geom::Dim2 axis, perp;
1025     switch (handle.cursor) {
1026         case GDK_TOP_SIDE:
1027         case GDK_BOTTOM_SIDE:
1028             axis = Geom::Y;
1029             perp = Geom::X;
1030             break;
1031         case GDK_LEFT_SIDE:
1032         case GDK_RIGHT_SIDE:
1033             axis = Geom::X;
1034             perp = Geom::Y;
1035             break;
1036         default:
1037             g_assert_not_reached();
1038             return TRUE;
1039     };
1041     // Calculate the scale factors, which can be either visual or geometric
1042     // depending on which type of bbox is currently being used (see preferences -> selector tool)
1043     Geom::Scale default_scale = calcScaleFactors(_point, pt, _origin);
1044     default_scale[perp] = 1;
1046     // Find the scale factors for the geometric bbox
1047     Geom::Point pt_geom = _getGeomHandlePos(pt);
1048     Geom::Scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
1049     geom_scale[perp] = 1;
1051     _absolute_affine = Geom::identity(); //Initialize the scaler
1053     if (state & GDK_MOD1_MASK) { // stretch by an integer multiplier/divider
1054         if (fabs(default_scale[axis]) > 1) {
1055             default_scale[axis] = round(default_scale[axis]);
1056         } else if (default_scale[axis] != 0) {
1057             default_scale[axis] = 1/round(1/(MIN(default_scale[axis], 10)));
1058         }
1059         // Calculate the new transformation and update the handle position
1060         pt = _calcAbsAffineDefault(default_scale);
1061         // When stretching by an integer, snapping is not needed
1062     } else {
1063         // In all other cases we should try to snap now
1065         SnapManager &m = _desktop->namedview->snap_manager;
1066         m.setup(_desktop, false, _items_const);
1068         Inkscape::SnappedPoint bb, sn;
1069         g_assert(bb.getSnapped() == false); // Check initialization to catch any regression
1070         Geom::Coord bd(NR_HUGE);
1071         Geom::Coord sd(NR_HUGE);
1073         bool symmetrical = state & GDK_CONTROL_MASK;
1075         bb = m.constrainedSnapStretch(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, Geom::Coord(default_scale[axis]), _origin_for_bboxpoints, Geom::Dim2(axis), symmetrical);
1076         sn = m.constrainedSnapStretch(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, Geom::Coord(geom_scale[axis]), _origin_for_specpoints, Geom::Dim2(axis), symmetrical);
1078         if (bb.getSnapped()) {
1079             // We snapped the bbox (which is either visual or geometric)
1080             bd = fabs(bb.getTransformation()[axis] - default_scale[axis]);
1081             default_scale[axis] = bb.getTransformation()[axis];
1082         }
1084         if (sn.getSnapped()) {
1085             sd = fabs(sn.getTransformation()[axis] - geom_scale[axis]);
1086             geom_scale[axis] = sn.getTransformation()[axis];
1087         }
1089         if (symmetrical) {
1090             // on ctrl, apply symmetrical scaling instead of stretching
1091             // Preserve aspect ratio, but never flip in the dimension not being edited (by using fabs())
1092             default_scale[perp] = fabs(default_scale[axis]);
1093             geom_scale[perp] = fabs(geom_scale[axis]);
1094         }
1096         if (!(bb.getSnapped() || sn.getSnapped())) {
1097             // We didn't snap at all! Don't update the handle position, just calculate the new transformation
1098             _calcAbsAffineDefault(default_scale);
1099             _desktop->snapindicator->remove_snaptarget();
1100         } else if (bd < sd) {
1101             _desktop->snapindicator->set_new_snaptarget(bb);
1102             // Calculate the new transformation and update the handle position
1103             pt = _calcAbsAffineDefault(default_scale);
1104         } else {
1105             _desktop->snapindicator->set_new_snaptarget(sn);
1106             // We snapped the special points (e.g. nodes), which are not at the visual bbox
1107             // The handle location however (pt) might however be at the visual bbox, so we
1108             // will have to calculate pt taking the stroke width into account
1109             pt = _calcAbsAffineGeom(geom_scale);
1110         }
1111     }
1113     // status text
1114     _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1115                           _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1116                           100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1118     return TRUE;
1121 gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1123     /* When skewing (or rotating):
1124      * 1) the stroke width will not change. This makes life much easier because we don't have to
1125      *    account for that (like for scaling or stretching). As a consequence, all points will
1126      *    have the same origin for the transformation and for the snapping.
1127      * 2) When holding shift, the transformation will be relative to the point opposite of
1128      *    the handle; otherwise it will be relative to the center as set for the selection
1129      */
1131     Geom::Dim2 dim_a;
1132     Geom::Dim2 dim_b;
1134     switch (handle.cursor) {
1135         case GDK_SB_H_DOUBLE_ARROW:
1136             dim_a = Geom::Y;
1137             dim_b = Geom::X;
1138             break;
1139         case GDK_SB_V_DOUBLE_ARROW:
1140             dim_a = Geom::X;
1141             dim_b = Geom::Y;
1142             break;
1143         default:
1144             g_assert_not_reached();
1145             abort();
1146             break;
1147     }
1149     Geom::Point const initial_delta = _point - _origin;
1151     if (fabs(initial_delta[dim_a]) < 1e-15) {
1152         return false;
1153     }
1155     // Calculate the scale factors, which can be either visual or geometric
1156     // depending on which type of bbox is currently being used (see preferences -> selector tool)
1157     Geom::Scale scale = calcScaleFactors(_point, pt, _origin, false);
1158     Geom::Scale skew = calcScaleFactors(_point, pt, _origin, true);
1159     scale[dim_b] = 1;
1160     skew[dim_b] = 1;
1162     if (fabs(scale[dim_a]) < 1) {
1163         // Prevent shrinking of the selected object, while allowing mirroring
1164         scale[dim_a] = sign(scale[dim_a]);
1165     } else {
1166         // Allow expanding of the selected object by integer multiples
1167         scale[dim_a] = floor(scale[dim_a] + 0.5);
1168     }
1170     double radians = atan(skew[dim_a] / scale[dim_a]);
1172     if (state & GDK_CONTROL_MASK) {
1173         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1174         // Snap to defined angle increments
1175         int snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12);
1176         if (snaps) {
1177             double sections = floor(radians * snaps / M_PI + .5);
1178             if (fabs(sections) >= snaps / 2) {
1179                 sections = sign(sections) * (snaps / 2 - 1);
1180             }
1181             radians = (M_PI / snaps) * sections;
1182         }
1183         skew[dim_a] = tan(radians) * scale[dim_a];
1184     } else {
1185         // Snap to objects, grids, guides
1187         SnapManager &m = _desktop->namedview->snap_manager;
1188         m.setup(_desktop, false, _items_const);
1190         Inkscape::Snapper::ConstraintLine const constraint(component_vectors[dim_b]);
1191         // When skewing, we cannot snap the corners of the bounding box, see the comment in "constrainedSnapSkew" for details
1192         Geom::Point const s(skew[dim_a], scale[dim_a]);
1193         Inkscape::SnappedPoint sn = m.constrainedSnapSkew(Inkscape::SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, constraint, s, _origin, Geom::Dim2(dim_b));
1195         if (sn.getSnapped()) {
1196             // We snapped something, so change the skew to reflect it
1197             Geom::Coord const sd = sn.getSnapped() ? sn.getTransformation()[0] : NR_HUGE;
1198              _desktop->snapindicator->set_new_snaptarget(sn);
1199             skew[dim_a] = sd;
1200         } else {
1201             _desktop->snapindicator->remove_snaptarget();
1202         }
1203     }
1205     // Update the handle position
1206     pt[dim_b] = initial_delta[dim_a] * skew[dim_a] + _point[dim_b];
1207     pt[dim_a] = initial_delta[dim_a] * scale[dim_a] + _origin[dim_a];
1209     // Calculate the relative affine
1210     _relative_affine = Geom::identity();
1211     _relative_affine[2*dim_a + dim_a] = (pt[dim_a] - _origin[dim_a]) / initial_delta[dim_a];
1212     _relative_affine[2*dim_a + (dim_b)] = (pt[dim_b] - _point[dim_b]) / initial_delta[dim_a];
1213     _relative_affine[2*(dim_b) + (dim_a)] = 0;
1214     _relative_affine[2*(dim_b) + (dim_b)] = 1;
1216     for (int i = 0; i < 2; i++) {
1217         if (fabs(_relative_affine[3*i]) < 1e-15) {
1218             _relative_affine[3*i] = 1e-15;
1219         }
1220     }
1222     // Update the status text
1223     double degrees = mod360symm(Geom::rad_to_deg(radians));
1224     _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1225                           // TRANSLATORS: don't modify the first ";"
1226                           // (it will NOT be displayed as ";" - only the second one will be)
1227                           _("<b>Skew</b>: %0.2f&#176;; with <b>Ctrl</b> to snap angle"),
1228                           degrees);
1230     return TRUE;
1233 gboolean Inkscape::SelTrans::rotateRequest(Geom::Point &pt, guint state)
1235     /* When rotating (or skewing):
1236      * 1) the stroke width will not change. This makes life much easier because we don't have to
1237      *    account for that (like for scaling or stretching). As a consequence, all points will
1238      *    have the same origin for the transformation and for the snapping.
1239      * 2) When holding shift, the transformation will be relative to the point opposite of
1240      *    the handle; otherwise it will be relative to the center as set for the selection
1241      */
1243     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1244     int snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12);
1246     // rotate affine in rotate
1247     Geom::Point const d1 = _point - _origin;
1248     Geom::Point const d2 = pt     - _origin;
1250     Geom::Coord const h1 = Geom::L2(d1); // initial radius
1251     if (h1 < 1e-15) return FALSE;
1252     Geom::Point q1 = d1 / h1; // normalized initial vector to handle
1253     Geom::Coord const h2 = Geom::L2(d2); // new radius
1254     if (fabs(h2) < 1e-15) return FALSE;
1255     Geom::Point q2 = d2 / h2; // normalized new vector to handle
1257     double radians;
1258     if (state & GDK_CONTROL_MASK) {
1259         // Snap to defined angle increments
1260         double cos_t = Geom::dot(q1, q2);
1261         double sin_t = Geom::dot(Geom::rot90(q1), q2);
1262         radians = atan2(sin_t, cos_t);
1263         if (snaps) {
1264             radians = ( M_PI / snaps ) * floor( radians * snaps / M_PI + .5 );
1265         }
1266         q1 = Geom::Point(1, 0);
1267         q2 = Geom::Point(cos(radians), sin(radians));
1268     } else {
1269         radians = atan2(Geom::dot(Geom::rot90(d1), d2),
1270                         Geom::dot(d1, d2));
1271     }
1273     Geom::Rotate const r1(q1);
1274     Geom::Rotate const r2(q2);
1276     // Calculate the relative affine
1277     _relative_affine = r2 * r1.inverse();
1279     // Update the handle position
1280     pt = _point * Geom::Translate(-_origin) * _relative_affine * Geom::Translate(_origin);
1282     // Update the status text
1283     double degrees = mod360symm(Geom::rad_to_deg(radians));
1284     _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1285                           // TRANSLATORS: don't modify the first ";"
1286                           // (it will NOT be displayed as ";" - only the second one will be)
1287                           _("<b>Rotate</b>: %0.2f&#176;; with <b>Ctrl</b> to snap angle"), degrees);
1289     return TRUE;
1292 // Move the item's transformation center
1293 gboolean Inkscape::SelTrans::centerRequest(Geom::Point &pt, guint state)
1295     SnapManager &m = _desktop->namedview->snap_manager;
1296     m.setup(_desktop);
1297     m.freeSnapReturnByRef(SnapPreferences::SNAPPOINT_NODE, pt, Inkscape::SNAPSOURCE_HANDLE);
1299     if (state & GDK_CONTROL_MASK) {
1300         if ( fabs(_point[Geom::X] - pt[Geom::X]) > fabs(_point[Geom::Y] - pt[Geom::Y]) ) {
1301             pt[Geom::Y] = _point[Geom::Y];
1302         } else {
1303             pt[Geom::X] = _point[Geom::X];
1304         }
1305     }
1307     if ( !(state & GDK_SHIFT_MASK) && _bbox ) {
1308         // screen pixels to snap center to bbox
1309 #define SNAP_DIST 5
1310         // FIXME: take from prefs
1311         double snap_dist = SNAP_DIST / _desktop->current_zoom();
1313         for (int i = 0; i < 2; i++) {
1314             if (fabs(pt[i] - _bbox->min()[i]) < snap_dist) {
1315                 pt[i] = _bbox->min()[i];
1316             }
1317             if (fabs(pt[i] - _bbox->midpoint()[i]) < snap_dist) {
1318                 pt[i] = _bbox->midpoint()[i];
1319             }
1320             if (fabs(pt[i] - _bbox->max()[i]) < snap_dist) {
1321                 pt[i] = _bbox->max()[i];
1322             }
1323         }
1324     }
1326     // status text
1327     GString *xs = SP_PX_TO_METRIC_STRING(pt[Geom::X], _desktop->namedview->getDefaultMetric());
1328     GString *ys = SP_PX_TO_METRIC_STRING(pt[Geom::Y], _desktop->namedview->getDefaultMetric());
1329     _message_context.setF(Inkscape::NORMAL_MESSAGE, _("Move <b>center</b> to %s, %s"), xs->str, ys->str);
1330     g_string_free(xs, FALSE);
1331     g_string_free(ys, FALSE);
1333     return TRUE;
1336 /*
1337  * handlers for handle movement
1338  *
1339  */
1341 void sp_sel_trans_stretch(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1343     seltrans->stretch(handle, pt, state);
1346 void sp_sel_trans_scale(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint state)
1348     seltrans->scale(pt, state);
1351 void sp_sel_trans_skew(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1353     seltrans->skew(handle, pt, state);
1356 void sp_sel_trans_rotate(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint state)
1358     seltrans->rotate(pt, state);
1361 void Inkscape::SelTrans::stretch(SPSelTransHandle const &/*handle*/, Geom::Point &/*pt*/, guint /*state*/)
1363     transform(_absolute_affine, Geom::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1366 void Inkscape::SelTrans::scale(Geom::Point &/*pt*/, guint /*state*/)
1368     transform(_absolute_affine, Geom::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1371 void Inkscape::SelTrans::skew(SPSelTransHandle const &/*handle*/, Geom::Point &/*pt*/, guint /*state*/)
1373     transform(_relative_affine, _origin);
1376 void Inkscape::SelTrans::rotate(Geom::Point &/*pt*/, guint /*state*/)
1378     transform(_relative_affine, _origin);
1381 void sp_sel_trans_center(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint /*state*/)
1383     seltrans->setCenter(pt);
1387 void Inkscape::SelTrans::moveTo(Geom::Point const &xy, guint state)
1389     SnapManager &m = _desktop->namedview->snap_manager;
1391     /* The amount that we've moved by during this drag */
1392     Geom::Point dxy = xy - _point;
1394     bool const alt = (state & GDK_MOD1_MASK);
1395     bool const control = (state & GDK_CONTROL_MASK);
1396     bool const shift = (state & GDK_SHIFT_MASK);
1398     if (alt) {
1400         /* Alt pressed means keep offset: snap the moved distance to the grid.
1401         ** FIXME: this will snap to more than just the grid, nowadays.
1402         */
1404         m.setup(_desktop, true, _items_const);
1405         m.freeSnapReturnByRef(SnapPreferences::SNAPPOINT_NODE, dxy, Inkscape::SNAPSOURCE_UNDEFINED);
1407     } else if (shift) {
1408         if (control) { // shift & control: constrained movement without snapping
1409                 if (fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y])) {
1410                                 dxy[Geom::Y] = 0;
1411                         } else {
1412                                 dxy[Geom::X] = 0;
1413                         }
1414         }
1415     } else { //!shift: with snapping
1417         /* We're snapping to things, possibly with a constraint to horizontal or
1418         ** vertical movement.  Obtain a list of possible translations and then
1419         ** pick the smallest.
1420         */
1422         m.setup(_desktop, false, _items_const);
1424         /* This will be our list of possible translations */
1425         std::list<Inkscape::SnappedPoint> s;
1427         if (control) { // constrained movement with snapping
1429             /* Snap to things, and also constrain to horizontal or vertical movement */
1431             unsigned int dim = fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y]) ? Geom::X : Geom::Y;
1432                         // When doing a constrained translation, all points will move in the same direction, i.e.
1433                         // either horizontally or vertically. Therefore we only have to specify the direction of
1434                         // the constraint-line once. The constraint lines are parallel, but might not be colinear.
1435                         // Therefore we will have to set the point through which the constraint-line runs
1436                         // individually for each point to be snapped; this will be handled however by _snapTransformed()
1437                         s.push_back(m.constrainedSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_BBOX,
1438                                                                                                          _bbox_points,
1439                                                                                                          _point,
1440                                                                                                          Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1441                                                                                                          dxy));
1443                         s.push_back(m.constrainedSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_NODE,
1444                                                                                                          _snap_points,
1445                                                                                                          _point,
1446                                                                                                          Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1447                                                                                                          dxy));
1448         } else { // !control
1450             // Let's leave this timer code here for a while. I'll probably need it in the near future (Diederik van Lierop)
1451             /* GTimeVal starttime;
1452             GTimeVal endtime;
1453                 g_get_current_time(&starttime); */
1455             /* Snap to things with no constraint */
1456                 s.push_back(m.freeSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, dxy));
1457                 s.push_back(m.freeSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, dxy));
1459                 /*g_get_current_time(&endtime);
1460                 double elapsed = ((((double)endtime.tv_sec - starttime.tv_sec) * G_USEC_PER_SEC + (endtime.tv_usec - starttime.tv_usec))) / 1000.0;
1461                 std::cout << "Time spent snapping: " << elapsed << std::endl; */
1462         }
1464         /* Pick one */
1465         Inkscape::SnappedPoint best_snapped_point;
1466         for (std::list<Inkscape::SnappedPoint>::const_iterator i = s.begin(); i != s.end(); i++) {
1467             if (i->getSnapped()) {
1468                 if (best_snapped_point.isOtherSnapBetter(*i, true)) {
1469                     best_snapped_point = *i;
1470                     dxy = i->getTransformation();
1471                 }
1472             }
1473         }
1474         if (best_snapped_point.getSnapped()) {
1475             _desktop->snapindicator->set_new_snaptarget(best_snapped_point);
1476         } else {
1477             // We didn't snap, so remove any previous snap indicator
1478             _desktop->snapindicator->remove_snaptarget();
1479             if (control) {
1480                 // If we didn't snap, then we should still constrain horizontally or vertically
1481                 // (When we did snap, then this constraint has already been enforced by
1482                 // calling constrainedSnapTranslation() above)
1483                 if (fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y])) {
1484                     dxy[Geom::Y] = 0;
1485                 } else {
1486                     dxy[Geom::X] = 0;
1487                 }
1488             }
1489         }
1490     }
1492     Geom::Matrix const move((Geom::Translate(dxy)));
1493     Geom::Point const norm(0, 0);
1494     transform(move, norm);
1496     // status text
1497     GString *xs = SP_PX_TO_METRIC_STRING(dxy[Geom::X], _desktop->namedview->getDefaultMetric());
1498     GString *ys = SP_PX_TO_METRIC_STRING(dxy[Geom::Y], _desktop->namedview->getDefaultMetric());
1499     _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);
1500     g_string_free(xs, TRUE);
1501     g_string_free(ys, TRUE);
1504 // Given a location of a handle at the visual bounding box, find the corresponding location at the
1505 // geometrical bounding box
1506 Geom::Point Inkscape::SelTrans::_getGeomHandlePos(Geom::Point const &visual_handle_pos)
1508     if ( _snap_bbox_type == SPItem::GEOMETRIC_BBOX) {
1509         // When the selector tool is using geometric bboxes, then the handle is already
1510         // located at one of the geometric bbox corners
1511         return visual_handle_pos;
1512     }
1514     if (!_geometric_bbox) {
1515         //_getGeomHandlePos() can only be used after _geometric_bbox has been defined!
1516         return visual_handle_pos;
1517     }
1519     // Using the Geom::Rect constructor below ensures that "min() < max()", which is important
1520     // because this will also hold for _bbox, and which is required for get_scale_transform_with_stroke()
1521     Geom::Rect new_bbox = Geom::Rect(_origin_for_bboxpoints, visual_handle_pos); // new visual bounding box
1522     // Please note that the new_bbox might in fact be just a single line, for example when stretching (in
1523     // which case the handle and origin will be aligned vertically or horizontally)
1524     Geom::Point normalized_handle_pos = (visual_handle_pos - new_bbox.min()) * Geom::Scale(new_bbox.dimensions()).inverse();
1526     // Calculate the absolute affine while taking into account the scaling of the stroke width
1527     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1528     bool transform_stroke = prefs->getBool("/options/transform/stroke", true);
1529     Geom::Matrix abs_affine = get_scale_transform_with_stroke (*_bbox, _strokewidth, transform_stroke,
1530                     new_bbox.min()[Geom::X], new_bbox.min()[Geom::Y], new_bbox.max()[Geom::X], new_bbox.max()[Geom::Y]);
1532     // Calculate the scaled geometrical bbox
1533     Geom::Rect new_geom_bbox = Geom::Rect(_geometric_bbox->min() * abs_affine, _geometric_bbox->max() * abs_affine);
1534     // Find the location of the handle on this new geometrical bbox
1535     return normalized_handle_pos * Geom::Scale(new_geom_bbox.dimensions()) + new_geom_bbox.min(); //new position of the geometric handle
1538 Geom::Scale Inkscape::calcScaleFactors(Geom::Point const &initial_point, Geom::Point const &new_point, Geom::Point const &origin, bool const skew)
1540     // Work out the new scale factors for the bbox
1542     Geom::Point const initial_delta = initial_point - origin;
1543     Geom::Point const new_delta = new_point - origin;
1544     Geom::Point const offset = new_point - initial_point;
1545     Geom::Scale scale(1, 1);
1547     for ( unsigned int i = 0 ; i < 2 ; i++ ) {
1548         if ( fabs(initial_delta[i]) > 1e-6 ) {
1549             if (skew) {
1550                 scale[i] = offset[1-i] / initial_delta[i];
1551             } else {
1552                 scale[i] = new_delta[i] / initial_delta[i];
1553             }
1554         }
1555     }
1557     return scale;
1560 // Only for scaling/stretching
1561 Geom::Point Inkscape::SelTrans::_calcAbsAffineDefault(Geom::Scale const default_scale)
1563     Geom::Matrix abs_affine = Geom::Translate(-_origin) * Geom::Matrix(default_scale) * Geom::Translate(_origin);
1564     Geom::Point new_bbox_min = _approximate_bbox->min() * abs_affine;
1565     Geom::Point new_bbox_max = _approximate_bbox->max() * abs_affine;
1567     bool transform_stroke = false;
1568     gdouble strokewidth = 0;
1570     if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
1571         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1572         transform_stroke = prefs->getBool("/options/transform/stroke", true);
1573         strokewidth = _strokewidth;
1574     }
1576     _absolute_affine = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
1577                     new_bbox_min[Geom::X], new_bbox_min[Geom::Y], new_bbox_max[Geom::X], new_bbox_max[Geom::Y]);
1579     // return the new handle position
1580     return ( _point - _origin ) * default_scale + _origin;
1583 // Only for scaling/stretching
1584 Geom::Point Inkscape::SelTrans::_calcAbsAffineGeom(Geom::Scale const geom_scale)
1586     _relative_affine = Geom::Matrix(geom_scale);
1587     _absolute_affine = Geom::Translate(-_origin_for_specpoints) * _relative_affine * Geom::Translate(_origin_for_specpoints);
1589     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1590     bool const transform_stroke = prefs->getBool("/options/transform/stroke", true);
1591     Geom::Rect visual_bbox = get_visual_bbox(_geometric_bbox, _absolute_affine, _strokewidth, transform_stroke);
1593     // return the new handle position
1594     return visual_bbox.min() + visual_bbox.dimensions() * Geom::Scale(_handle_x, _handle_y);
1597 void Inkscape::SelTrans::_keepClosestPointOnly(std::vector<std::pair<Geom::Point, int> > &points, const Geom::Point &reference)
1599         if (points.size() < 2) return;
1601         std::pair<Geom::Point, int> closest_point = std::make_pair(Geom::Point(NR_HUGE, NR_HUGE), SNAPSOURCE_UNDEFINED);
1602         Geom::Coord closest_dist = NR_HUGE;
1604         for(std::vector<std::pair<Geom::Point, int> >::const_iterator i = points.begin(); i != points.end(); i++) {
1605                 Geom::Coord dist = Geom::L2((*i).first - reference);
1606                 if (i == points.begin() || dist < closest_dist) {
1607                         closest_point = *i;
1608                         closest_dist = dist;
1609                 }
1610     }
1612         points.clear();
1613         points.push_back(closest_point);
1616 /*
1617   Local Variables:
1618   mode:c++
1619   c-file-style:"stroustrup"
1620   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1621   indent-tabs-mode:nil
1622   fill-column:99
1623   End:
1624 */
1625 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :