Code

1) Fix moving by an integer multiple of the grid spacing (<alt>-dragging in the selec...
[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, bool translating)
246     // While dragging a handle, we will either scale, skew, or rotate and the "translating" parameter will be false
247     // When dragging the selected item itself however, we will translate the selection and that parameter will be true
248     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
249     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
251     g_return_if_fail(!_grabbed);
253     _grabbed = true;
254     _show_handles = show_handles;
255     _updateVolatileState();
256     _current_relative_affine.setIdentity();
258     _changed = false;
260     if (_empty) {
261         return;
262     }
264     for (GSList const *l = selection->itemList(); l; l = l->next) {
265         SPItem *it = (SPItem *)sp_object_ref(SP_OBJECT(l->data), NULL);
266         _items.push_back(it);
267         _items_const.push_back(it);
268         _items_affines.push_back(sp_item_i2d_affine(it));
269         _items_centers.push_back(it->getCenter()); // for content-dragging, we need to remember original centers
270     }
272     _handle_x = x;
273     _handle_y = y;
275     // The selector tool should snap the bbox, special snappoints, and path nodes
276     // (The special points are the handles, center, rotation axis, font baseline, ends of spiral, etc.)
278     // First, determine the bounding box
279     _bbox = selection->bounds(_snap_bbox_type);
280     _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX); // Used for correctly scaling the strokewidth
281     _geometric_bbox = selection->bounds(SPItem::GEOMETRIC_BBOX);
283     _point = p;
284     if (_geometric_bbox) {
285         _point_geom = _geometric_bbox->min() + _geometric_bbox->dimensions() * Geom::Scale(x, y);
286     } else {
287         _point_geom = p;
288     }
290     // Next, get all points to consider for snapping
291     SnapManager const &m = _desktop->namedview->snap_manager;
292     Inkscape::SnapPreferences local_snapprefs = m.snapprefs;
293     local_snapprefs.setSnapToItemNode(true); // We should get at least the cusp nodes here. This might
294     // have been turned off because (for example) the user only want paths as a snap target, not nodes
295     // but as a snap source we still need some nodes though!
296     _snap_points.clear();
297     _snap_points = selection->getSnapPoints(&local_snapprefs);
298     std::vector<Inkscape::SnapCandidatePoint> snap_points_hull = selection->getSnapPointsConvexHull(&local_snapprefs);
299     if (_snap_points.size() > 200) {
300         /* Snapping a huge number of nodes will take way too long, so limit the number of snappable nodes
301         An average user would rarely ever try to snap such a large number of nodes anyway, because
302         (s)he could hardly discern which node would be snapping */
303         if (prefs->getBool("/options/snapclosestonly/value", false)) {
304             _keepClosestPointOnly(_snap_points, p);
305         } else {
306             _snap_points = snap_points_hull;
307         }
308         // Unfortunately, by now we will have lost the font-baseline snappoints :-(
309     }
311     // Find bbox hulling all special points, which excludes stroke width. Here we need to include the
312     // path nodes, for example because a rectangle which has been converted to a path doesn't have
313     // any other special points
314     Geom::Rect snap_points_bbox;
315     if ( snap_points_hull.empty() == false ) {
316         std::vector<Inkscape::SnapCandidatePoint>::iterator i = snap_points_hull.begin();
317         snap_points_bbox = Geom::Rect((*i).getPoint(), (*i).getPoint());
318         i++;
319         while (i != snap_points_hull.end()) {
320             snap_points_bbox.expandTo((*i).getPoint());
321             i++;
322         }
323     }
325     _bbox_points.clear();
326     _bbox_points_for_translating.clear();
327     // Collect the bounding box's corners and midpoints for each selected item
328     if (m.snapprefs.getSnapModeBBox()) {
329         bool mp = m.snapprefs.getSnapBBoxMidpoints();
330         bool emp = m.snapprefs.getSnapBBoxEdgeMidpoints();
331         // Preferably we'd use the bbox of each selected item, instead of the bbox of the selection as a whole; for translations
332         // this is easy to do, but when snapping the visual bbox while scaling we will have to compensate for the scaling of the
333         // stroke width. (see get_scale_transform_with_stroke()). This however is currently only implemented for a single bbox.
334         // That's why we have both _bbox_points_for_translating and _bbox_points.
335         getBBoxPoints(selection->bounds(_snap_bbox_type), &_bbox_points, false, true, emp, mp);
336         if (((_items.size() > 0) && (_items.size() < 50)) || prefs->getBool("/options/snapclosestonly/value", false)) {
337             // More than 50 items will produce at least 200 bbox points, which might make Inkscape crawl
338             // (see the comment a few lines above). In that case we will use the bbox of the selection as a whole
339             for (unsigned i = 0; i < _items.size(); i++) {
340                 getBBoxPoints(sp_item_bbox_desktop(_items[i], _snap_bbox_type), &_bbox_points_for_translating, false, true, emp, mp);
341             }
342         } else {
343             _bbox_points_for_translating = _bbox_points; // use the bbox points of the selection as a whole
344         }
345     }
347     if (_bbox) {
348         // There are two separate "opposites" (i.e. opposite w.r.t. the handle being dragged):
349         //  - one for snapping the boundingbox, which can be either visual or geometric
350         //  - one for snapping the special points
351         // The "opposite" in case of a geometric boundingbox always coincides with the "opposite" for the special points
352         // These distinct "opposites" are needed in the snapmanager to avoid bugs such as #sf1540195 (in which
353         // a box is caught between two guides)
354         _opposite_for_bboxpoints = _bbox->min() + _bbox->dimensions() * Geom::Scale(1-x, 1-y);
355         _opposite_for_specpoints = snap_points_bbox.min() + snap_points_bbox.dimensions() * Geom::Scale(1-x, 1-y);
356         _opposite = _opposite_for_bboxpoints;
357     }
359     // When snapping the node closest to the mouse pointer is absolutely preferred over the closest snap
360     // (i.e. when weight == 1), then we will not even try to snap to other points and discard those other
361     // points immediately.
363     if (prefs->getBool("/options/snapclosestonly/value", false)) {
364         if (m.snapprefs.getSnapModeNode()) {
365             _keepClosestPointOnly(_snap_points, p);
366         } else {
367             _snap_points.clear(); // don't keep any point
368         }
370         if (m.snapprefs.getSnapModeBBox()) {
371             _keepClosestPointOnly(_bbox_points, p);
372             _keepClosestPointOnly(_bbox_points_for_translating, p);
373         } else {
374             _bbox_points.clear(); // don't keep any point
375             _bbox_points_for_translating.clear();
376         }
378         // Each of the three vectors of snappoints now contains either one snappoint or none at all.
379         if (_snap_points.size() > 1 || _bbox_points.size() > 1 || _bbox_points_for_translating.size() > 1) {
380             g_warning("Incorrect assumption encountered while finding the snap source; nothing serious, but please report to Diederik");
381         }
383         // Now let's reduce this to a single closest snappoint
384         Geom::Coord dsp    = _snap_points.size()                 == 1 ? Geom::L2((_snap_points.at(0)).getPoint() - p) : NR_HUGE;
385         Geom::Coord dbbp   = _bbox_points.size()                 == 1 ? Geom::L2((_bbox_points.at(0)).getPoint() - p) : NR_HUGE;
386         Geom::Coord dbbpft = _bbox_points_for_translating.size() == 1 ? Geom::L2((_bbox_points_for_translating.at(0)).getPoint() - p) : NR_HUGE;
388         if (translating) {
389             _bbox_points.clear();
390             if (dsp > dbbpft) {
391                 _snap_points.clear();
392             } else {
393                 _bbox_points_for_translating.clear();
394             }
395         } else {
396             _bbox_points_for_translating.clear();
397             if (dsp > dbbp) {
398                 _snap_points.clear();
399             } else {
400                 _bbox_points.clear();
401             }
402         }
404         if ((_snap_points.size() + _bbox_points.size() + _bbox_points_for_translating.size()) > 1) {
405             g_warning("Checking number of snap sources failed; nothing serious, but please report to Diederik");
406         }
408         // Optionally, show the snap source
409         if (!(_state == STATE_ROTATE && x != 0.5 && y != 0.5)) { // but not when we're dragging a rotation handle, because that won't snap
410             // Now either _bbox_points or _snap_points has a single element, the other one has zero..... or both have zero elements
411             if ((_snap_points.size() + _bbox_points.size() + _bbox_points_for_translating.size()) > 1) {
412                 g_warning("too many snap sources to display, please fix this");
413             } else if (m.snapprefs.getSnapEnabledGlobally()) {
414                 if (_bbox_points.size() == 1) {
415                     _desktop->snapindicator->set_new_snapsource(_bbox_points.at(0));
416                 } else if (_bbox_points_for_translating.size() == 1) {
417                     _desktop->snapindicator->set_new_snapsource(_bbox_points_for_translating.at(0));
418                 } else if (_snap_points.size() == 1){
419                     _desktop->snapindicator->set_new_snapsource(_snap_points.at(0));
420                 }
421             }
422         }
423     }
425     if ((x != -1) && (y != -1)) {
426         sp_canvas_item_show(_norm);
427         sp_canvas_item_show(_grip);
428     }
430     if (_show == SHOW_OUTLINE) {
431         for (int i = 0; i < 4; i++)
432             sp_canvas_item_show(_l[i]);
433     }
435     _updateHandles();
436     g_return_if_fail(_stamp_cache == NULL);
439 void Inkscape::SelTrans::transform(Geom::Matrix const &rel_affine, Geom::Point const &norm)
441     g_return_if_fail(_grabbed);
442     g_return_if_fail(!_empty);
444     Geom::Matrix const affine( Geom::Translate(-norm) * rel_affine * Geom::Translate(norm) );
446     if (_show == SHOW_CONTENT) {
447         // update the content
448         for (unsigned i = 0; i < _items.size(); i++) {
449             SPItem &item = *_items[i];
450             Geom::Matrix const &prev_transform = _items_affines[i];
451             sp_item_set_i2d_affine(&item, prev_transform * affine);
452         }
453     } else {
454         if (_bbox) {
455             Geom::Point p[4];
456             /* update the outline */
457             for (unsigned i = 0 ; i < 4 ; i++) {
458                 p[i] = _bbox->corner(i) * affine;
459             }
460             for (unsigned i = 0 ; i < 4 ; i++) {
461                 sp_ctrlline_set_coords(SP_CTRLLINE(_l[i]), p[i], p[(i+1)%4]);
462             }
463         }
464     }
466     _current_relative_affine = affine;
467     _changed = true;
468     _updateHandles();
471 void Inkscape::SelTrans::ungrab()
473     g_return_if_fail(_grabbed);
474     _grabbed = false;
475     _show_handles = true;
477     _desktop->snapindicator->remove_snapsource();
479     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
480     _updateVolatileState();
482     for (unsigned i = 0; i < _items.size(); i++) {
483         sp_object_unref(SP_OBJECT(_items[i]), NULL);
484     }
486     sp_canvas_item_hide(_norm);
487     sp_canvas_item_hide(_grip);
489     if (_show == SHOW_OUTLINE) {
490         for (int i = 0; i < 4; i++)
491             sp_canvas_item_hide(_l[i]);
492     }
494     if (_stamp_cache) {
495         g_slist_free(_stamp_cache);
496         _stamp_cache = NULL;
497     }
499     _message_context.clear();
501     if (!_empty && _changed) {
502         sp_selection_apply_affine(selection, _current_relative_affine, (_show == SHOW_OUTLINE)? true : false);
503         if (_center) {
504             *_center *= _current_relative_affine;
505             _center_is_set = true;
506         }
508 // If dragging showed content live, sp_selection_apply_affine cannot change the centers
509 // appropriately - it does not know the original positions of the centers (all objects already have
510 // the new bboxes). So we need to reset the centers from our saved array.
511         if (_show != SHOW_OUTLINE && !_current_relative_affine.isTranslation()) {
512             for (unsigned i = 0; i < _items_centers.size(); i++) {
513                 SPItem *currentItem = _items[i];
514                 if (currentItem->isCenterSet()) { // only if it's already set
515                     currentItem->setCenter (_items_centers[i] * _current_relative_affine);
516                     SP_OBJECT(currentItem)->updateRepr();
517                 }
518             }
519         }
521         _items.clear();
522         _items_const.clear();
523         _items_affines.clear();
524         _items_centers.clear();
526         if (_current_relative_affine.isTranslation()) {
527             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
528                              _("Move"));
529         } else if (_current_relative_affine.without_translation().isScale()) {
530             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
531                              _("Scale"));
532         } else if (_current_relative_affine.without_translation().isRotation()) {
533             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
534                              _("Rotate"));
535         } else {
536             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
537                              _("Skew"));
538         }
540     } else {
542         if (_center_is_set) {
543             // we were dragging center; update reprs and commit undoable action
544             for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
545                 SPItem *it = (SPItem*)SP_OBJECT(l->data);
546                 SP_OBJECT(it)->updateRepr();
547             }
548             sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
549                             _("Set center"));
550         }
552         _items.clear();
553         _items_const.clear();
554         _items_affines.clear();
555         _items_centers.clear();
556         _updateHandles();
557     }
560 /* fixme: This is really bad, as we compare positions for each stamp (Lauris) */
561 /* fixme: IMHO the best way to keep sort cache would be to implement timestamping at last */
563 void Inkscape::SelTrans::stamp()
565     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
567     bool fixup = !_grabbed;
568     if ( fixup && _stamp_cache ) {
569         // TODO - give a proper fix. Simple temproary work-around for the grab() issue
570         g_slist_free(_stamp_cache);
571         _stamp_cache = NULL;
572     }
574     /* stamping mode */
575     if (!_empty) {
576         GSList *l;
577         if (_stamp_cache) {
578             l = _stamp_cache;
579         } else {
580             /* Build cache */
581             l  = g_slist_copy((GSList *) selection->itemList());
582             l  = g_slist_sort(l, (GCompareFunc) sp_object_compare_position);
583             _stamp_cache = l;
584         }
586         while (l) {
587             SPItem *original_item = SP_ITEM(l->data);
588             Inkscape::XML::Node *original_repr = SP_OBJECT_REPR(original_item);
590             // remember the position of the item
591             gint pos = original_repr->position();
592             // remember parent
593             Inkscape::XML::Node *parent = sp_repr_parent(original_repr);
595             Inkscape::XML::Node *copy_repr = original_repr->duplicate(parent->document());
597             // add the new repr to the parent
598             parent->appendChild(copy_repr);
599             // move to the saved position
600             copy_repr->setPosition(pos > 0 ? pos : 0);
602             SPItem *copy_item = (SPItem *) sp_desktop_document(_desktop)->getObjectByRepr(copy_repr);
604             Geom::Matrix const *new_affine;
605             if (_show == SHOW_OUTLINE) {
606                 Geom::Matrix const i2d(sp_item_i2d_affine(original_item));
607                 Geom::Matrix const i2dnew( i2d * _current_relative_affine );
608                 sp_item_set_i2d_affine(copy_item, i2dnew);
609                 new_affine = &copy_item->transform;
610             } else {
611                 new_affine = &original_item->transform;
612             }
614             sp_item_write_transform(copy_item, copy_repr, *new_affine);
616             if ( copy_item->isCenterSet() && _center ) {
617                 copy_item->setCenter(*_center * _current_relative_affine);
618             }
620             Inkscape::GC::release(copy_repr);
621             l = l->next;
622         }
623         sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
624                          _("Stamp"));
625     }
627     if ( fixup && _stamp_cache ) {
628         // TODO - give a proper fix. Simple temproary work-around for the grab() issue
629         g_slist_free(_stamp_cache);
630         _stamp_cache = NULL;
631     }
634 void Inkscape::SelTrans::_updateHandles()
636     if ( !_show_handles || _empty )
637     {
638         sp_remove_handles(_shandle, 8);
639         sp_remove_handles(_rhandle, 8);
640         sp_remove_handles(&_chandle, 1);
641         return;
642     }
644     // center handle
645     if ( _chandle == NULL ) {
646         _chandle = sp_knot_new(_desktop, _("<b>Center</b> of rotation and skewing: drag to reposition; scaling with Shift also uses this center"));
648         _chandle->setShape (SP_CTRL_SHAPE_BITMAP);
649         _chandle->setSize (13);
650         _chandle->setAnchor (handle_center.anchor);
651         _chandle->setMode (SP_CTRL_MODE_XOR);
652         _chandle->setFill(0x00000000, 0x00000000, 0x00000000);
653         _chandle->setStroke(0x000000ff, 0xff0000b0, 0xff0000b0);
654         _chandle->setPixbuf(handles[handle_center.control]);
655         sp_knot_update_ctrl(_chandle);
657         g_signal_connect(G_OBJECT(_chandle), "request",
658                          G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle_center);
659         g_signal_connect(G_OBJECT(_chandle), "moved",
660                          G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle_center);
661         g_signal_connect(G_OBJECT(_chandle), "grabbed",
662                          G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle_center);
663         g_signal_connect(G_OBJECT(_chandle), "ungrabbed",
664                          G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle_center);
665         g_signal_connect(G_OBJECT(_chandle), "clicked",
666                          G_CALLBACK(sp_sel_trans_handle_click), (gpointer) &handle_center);
667     }
669     sp_remove_handles(&_chandle, 1);
670     if ( _state == STATE_SCALE ) {
671         sp_remove_handles(_rhandle, 8);
672         _showHandles(_shandle, handles_scale, 8,
673                     _("<b>Squeeze or stretch</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"),
674                     _("<b>Scale</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"));
675     } else {
676         sp_remove_handles(_shandle, 8);
677         _showHandles(_rhandle, handles_rotate, 8,
678                     _("<b>Skew</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to skew around the opposite side"),
679                     _("<b>Rotate</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to rotate around the opposite corner"));
680     }
682     if (!_center_is_set) {
683         _center = _desktop->selection->center();
684         _center_is_set = true;
685     }
687     if ( _state == STATE_SCALE || !_center ) {
688         sp_knot_hide(_chandle);
689     } else {
690         sp_knot_show(_chandle);
691         sp_knot_moveto(_chandle, *_center);
692     }
695 void Inkscape::SelTrans::_updateVolatileState()
697     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
698     _empty = selection->isEmpty();
700     if (_empty) {
701         return;
702     }
704     //Update the bboxes
705     _bbox = selection->bounds(_snap_bbox_type);
706     _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX);
708     if (!_bbox) {
709         _empty = true;
710         return;
711     }
713     _strokewidth = stroke_average_width (selection->itemList());
716 static void sp_remove_handles(SPKnot *knot[], gint num)
718     for (int i = 0; i < num; i++) {
719         if (knot[i] != NULL) {
720             sp_knot_hide(knot[i]);
721         }
722     }
725 void Inkscape::SelTrans::_showHandles(SPKnot *knot[], SPSelTransHandle const handle[], gint num,
726                              gchar const *even_tip, gchar const *odd_tip)
728     g_return_if_fail( !_empty );
730     for (int i = 0; i < num; i++) {
731         if (knot[i] == NULL) {
732             knot[i] = sp_knot_new(_desktop, i % 2 ? even_tip : odd_tip);
734             knot[i]->setShape (SP_CTRL_SHAPE_BITMAP);
735             knot[i]->setSize (13);
736             knot[i]->setAnchor (handle[i].anchor);
737             knot[i]->setMode (SP_CTRL_MODE_XOR);
738             knot[i]->setFill(0x000000ff, 0x00ff6600, 0x00ff6600); // inversion, green, green
739             knot[i]->setStroke(0x000000ff, 0x000000ff, 0x000000ff); // inversion
740             knot[i]->setPixbuf(handles[handle[i].control]);
741             sp_knot_update_ctrl(knot[i]);
743             g_signal_connect(G_OBJECT(knot[i]), "request",
744                              G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle[i]);
745             g_signal_connect(G_OBJECT(knot[i]), "moved",
746                              G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle[i]);
747             g_signal_connect(G_OBJECT(knot[i]), "grabbed",
748                              G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle[i]);
749             g_signal_connect(G_OBJECT(knot[i]), "ungrabbed",
750                              G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle[i]);
751             g_signal_connect(G_OBJECT(knot[i]), "event", G_CALLBACK(sp_seltrans_handle_event), (gpointer) &handle[i]);
752         }
753         sp_knot_show(knot[i]);
755         Geom::Point const handle_pt(handle[i].x, handle[i].y);
756         // shouldn't have nullary bbox, but knots
757         g_assert(_bbox);
758         Geom::Point p( _bbox->min()
759                      + ( _bbox->dimensions()
760                          * Geom::Scale(handle_pt) ) );
762         sp_knot_moveto(knot[i], p);
763     }
766 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data)
768     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleGrab(
769         knot, state, *(SPSelTransHandle const *) data
770         );
773 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint /*state*/, gpointer /*data*/)
775     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->ungrab();
778 static void sp_sel_trans_handle_new_event(SPKnot *knot, Geom::Point *position, guint state, gpointer data)
780     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleNewEvent(
781         knot, position, state, *(SPSelTransHandle const *) data
782         );
785 static gboolean sp_sel_trans_handle_request(SPKnot *knot, Geom::Point *position, guint state, gboolean *data)
787     return SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleRequest(
788         knot, position, state, *(SPSelTransHandle const *) data
789         );
792 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data)
794     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleClick(
795         knot, state, *(SPSelTransHandle const *) data
796         );
799 void Inkscape::SelTrans::handleClick(SPKnot */*knot*/, guint state, SPSelTransHandle const &handle)
801     switch (handle.anchor) {
802         case GTK_ANCHOR_CENTER:
803             if (state & GDK_SHIFT_MASK) {
804                 // Unset the  center position for all selected items
805                 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
806                     SPItem *it = (SPItem*)(SP_OBJECT(l->data));
807                     it->unsetCenter();
808                     SP_OBJECT(it)->updateRepr();
809                     _center_is_set = false;  // center has changed
810                     _updateHandles();
811                 }
812                 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
813                                         _("Reset center"));
814             }
815             break;
816         default:
817             break;
818     }
821 void Inkscape::SelTrans::handleGrab(SPKnot *knot, guint /*state*/, SPSelTransHandle const &handle)
823     switch (handle.anchor) {
824         case GTK_ANCHOR_CENTER:
825             g_object_set(G_OBJECT(_grip),
826                          "shape", SP_CTRL_SHAPE_BITMAP,
827                          "size", 13.0,
828                          NULL);
829             sp_canvas_item_show(_grip);
830             break;
831         default:
832             g_object_set(G_OBJECT(_grip),
833                          "shape", SP_CTRL_SHAPE_CROSS,
834                          "size", 7.0,
835                          NULL);
836             sp_canvas_item_show(_norm);
837             sp_canvas_item_show(_grip);
839             break;
840     }
842     grab(sp_knot_position(knot), handle.x, handle.y, FALSE, FALSE);
846 void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const &handle)
848     if (!SP_KNOT_IS_GRABBED(knot)) {
849         return;
850     }
852     // in case items have been unhooked from the document, don't
853     // try to continue processing events for them.
854     for (unsigned int i = 0; i < _items.size(); i++) {
855         if (!SP_OBJECT_DOCUMENT(SP_OBJECT(_items[i])) ) {
856             return;
857         }
858     }
860     handle.action(this, handle, *position, state);
864 gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const &handle)
866     if (!SP_KNOT_IS_GRABBED(knot)) {
867         return TRUE;
868     }
870     knot->desktop->setPosition(*position);
872     // When holding shift while rotating or skewing, the transformation will be
873     // relative to the point opposite of the handle; otherwise it will be relative
874     // to the center as set for the selection
875     if ((!(state & GDK_SHIFT_MASK) == !(_state == STATE_ROTATE)) && (&handle != &handle_center)) {
876         _origin = _opposite;
877         _origin_for_bboxpoints = _opposite_for_bboxpoints;
878         _origin_for_specpoints = _opposite_for_specpoints;
879     } else if (_center) {
880         _origin = *_center;
881         _origin_for_bboxpoints = *_center;
882         _origin_for_specpoints = *_center;
883     } else {
884         // FIXME
885         return TRUE;
886     }
887     if (handle.request(this, handle, *position, state)) {
888         sp_knot_set_position(knot, *position, state);
889         SP_CTRL(_grip)->moveto(*position);
890         SP_CTRL(_norm)->moveto(_origin);
891     }
893     return TRUE;
897 void Inkscape::SelTrans::_selChanged(Inkscape::Selection */*selection*/)
899     if (!_grabbed) {
900         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
901         // reread in case it changed on the fly:
902         int prefs_bbox = prefs->getBool("/tools/bounding_box");
903          _snap_bbox_type = !prefs_bbox ?
904             SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
905         //SPItem::APPROXIMATE_BBOX will be replaced by SPItem::VISUAL_BBOX, as soon as the latter is implemented properly
907         _updateVolatileState();
908         _current_relative_affine.setIdentity();
909         _center_is_set = false; // center(s) may have changed
910         _updateHandles();
911     }
914 void Inkscape::SelTrans::_selModified(Inkscape::Selection */*selection*/, guint /*flags*/)
916     if (!_grabbed) {
917         _updateVolatileState();
918         _current_relative_affine.setIdentity();
920         // reset internal flag
921         _changed = false;
923         _center_is_set = false;  // center(s) may have changed
925         _updateHandles();
926     }
929 /*
930  * handlers for handle move-request
931  */
933 /** Returns -1 or 1 according to the sign of x.  Returns 1 for 0 and NaN. */
934 static double sign(double const x)
936     return ( x < 0
937              ? -1
938              : 1 );
941 gboolean sp_sel_trans_scale_request(Inkscape::SelTrans *seltrans,
942                                     SPSelTransHandle const &, Geom::Point &pt, guint state)
944     return seltrans->scaleRequest(pt, state);
947 gboolean sp_sel_trans_stretch_request(Inkscape::SelTrans *seltrans,
948                                       SPSelTransHandle const &handle, Geom::Point &pt, guint state)
950     return seltrans->stretchRequest(handle, pt, state);
953 gboolean sp_sel_trans_skew_request(Inkscape::SelTrans *seltrans,
954                                    SPSelTransHandle const &handle, Geom::Point &pt, guint state)
956     return seltrans->skewRequest(handle, pt, state);
959 gboolean sp_sel_trans_rotate_request(Inkscape::SelTrans *seltrans,
960                                      SPSelTransHandle const &, Geom::Point &pt, guint state)
962     return seltrans->rotateRequest(pt, state);
965 gboolean sp_sel_trans_center_request(Inkscape::SelTrans *seltrans,
966                                      SPSelTransHandle const &, Geom::Point &pt, guint state)
968     return seltrans->centerRequest(pt, state);
971 gboolean Inkscape::SelTrans::scaleRequest(Geom::Point &pt, guint state)
974     // Calculate the scale factors, which can be either visual or geometric
975     // depending on which type of bbox is currently being used (see preferences -> selector tool)
976     Geom::Scale default_scale = calcScaleFactors(_point, pt, _origin);
978     // Find the scale factors for the geometric bbox
979     Geom::Point pt_geom = _getGeomHandlePos(pt);
980     Geom::Scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
982     _absolute_affine = Geom::identity(); //Initialize the scaler
984     if (state & GDK_MOD1_MASK) { // scale by an integer multiplier/divider
985         // We're scaling either the visual or the geometric bbox here (see the comment above)
986         for ( unsigned int i = 0 ; i < 2 ; i++ ) {
987             if (fabs(default_scale[i]) > 1) {
988                 default_scale[i] = round(default_scale[i]);
989             } else if (default_scale[i] != 0) {
990                 default_scale[i] = 1/round(1/(MIN(default_scale[i], 10)));
991             }
992         }
993         // Update the knot position
994         pt = _calcAbsAffineDefault(default_scale);
995         // When scaling by an integer, snapping is not needed
996     } else {
997         // In all other cases we should try to snap now
998         SnapManager &m = _desktop->namedview->snap_manager;
999         m.setup(_desktop, false, _items_const);
1001         Inkscape::SnappedPoint bb, sn;
1002         Geom::Coord bd(NR_HUGE);
1003         Geom::Coord sd(NR_HUGE);
1005         if ((state & GDK_CONTROL_MASK) || _desktop->isToolboxButtonActive ("lock")) {
1006             // Scale is locked to a 1:1 aspect ratio, so that s[X] must be made to equal s[Y].
1007             //
1008             // The aspect-ratio must be locked before snapping
1009             if (fabs(default_scale[Geom::X]) > fabs(default_scale[Geom::Y])) {
1010                 default_scale[Geom::X] = fabs(default_scale[Geom::Y]) * sign(default_scale[Geom::X]);
1011                 geom_scale[Geom::X] = fabs(geom_scale[Geom::Y]) * sign(geom_scale[Geom::X]);
1012             } else {
1013                 default_scale[Geom::Y] = fabs(default_scale[Geom::X]) * sign(default_scale[Geom::Y]);
1014                 geom_scale[Geom::Y] = fabs(geom_scale[Geom::X]) * sign(geom_scale[Geom::Y]);
1015             }
1017             // Snap along a suitable constraint vector from the origin.
1018             bb = m.constrainedSnapScale(_bbox_points, _point, default_scale, _origin_for_bboxpoints);
1019             sn = m.constrainedSnapScale(_snap_points, _point, geom_scale, _origin_for_specpoints);
1021             /* Choose the smaller difference in scale.  Since s[X] == s[Y] we can
1022             ** just compare difference in s[X].
1023             */
1024             bd = bb.getSnapped() ? fabs(bb.getTransformation()[Geom::X] - default_scale[Geom::X]) : NR_HUGE;
1025             sd = sn.getSnapped() ? fabs(sn.getTransformation()[Geom::X] - geom_scale[Geom::X]) : NR_HUGE;
1026         } else {
1027             /* Scale aspect ratio is unlocked */
1028             bb = m.freeSnapScale(_bbox_points, _point, default_scale, _origin_for_bboxpoints);
1029             sn = m.freeSnapScale(_snap_points, _point, geom_scale, _origin_for_specpoints);
1031             /* Pick the snap that puts us closest to the original scale */
1032             bd = bb.getSnapped() ? fabs(Geom::L2(bb.getTransformation()) - Geom::L2(Geom::Point(default_scale[Geom::X], default_scale[Geom::Y]))) : NR_HUGE;
1033             sd = sn.getSnapped() ? fabs(Geom::L2(sn.getTransformation()) - Geom::L2(Geom::Point(geom_scale[Geom::X], geom_scale[Geom::Y]))) : NR_HUGE;
1034         }
1036         if (!(bb.getSnapped() || sn.getSnapped())) {
1037             // We didn't snap at all! Don't update the handle position, just calculate the new transformation
1038             _calcAbsAffineDefault(default_scale);
1039             _desktop->snapindicator->remove_snaptarget();
1040         } else if (bd < sd) {
1041             // We snapped the bbox (which is either visual or geometric)
1042             _desktop->snapindicator->set_new_snaptarget(bb);
1043             default_scale = Geom::Scale(bb.getTransformation());
1044             // Calculate the new transformation and update the handle position
1045             pt = _calcAbsAffineDefault(default_scale);
1046         } else {
1047             _desktop->snapindicator->set_new_snaptarget(sn);
1048             // We snapped the special points (e.g. nodes), which are not at the visual bbox
1049             // The handle location however (pt) might however be at the visual bbox, so we
1050             // will have to calculate pt taking the stroke width into account
1051             geom_scale = Geom::Scale(sn.getTransformation());
1052             pt = _calcAbsAffineGeom(geom_scale);
1053         }
1054     }
1056     /* Status text */
1057     _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1058                           _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1059                           100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1061     return TRUE;
1064 gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1066     Geom::Dim2 axis, perp;
1067     switch (handle.cursor) {
1068         case GDK_TOP_SIDE:
1069         case GDK_BOTTOM_SIDE:
1070             axis = Geom::Y;
1071             perp = Geom::X;
1072             break;
1073         case GDK_LEFT_SIDE:
1074         case GDK_RIGHT_SIDE:
1075             axis = Geom::X;
1076             perp = Geom::Y;
1077             break;
1078         default:
1079             g_assert_not_reached();
1080             return TRUE;
1081     };
1083     // Calculate the scale factors, which can be either visual or geometric
1084     // depending on which type of bbox is currently being used (see preferences -> selector tool)
1085     Geom::Scale default_scale = calcScaleFactors(_point, pt, _origin);
1086     default_scale[perp] = 1;
1088     // Find the scale factors for the geometric bbox
1089     Geom::Point pt_geom = _getGeomHandlePos(pt);
1090     Geom::Scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
1091     geom_scale[perp] = 1;
1093     _absolute_affine = Geom::identity(); //Initialize the scaler
1095     if (state & GDK_MOD1_MASK) { // stretch by an integer multiplier/divider
1096         if (fabs(default_scale[axis]) > 1) {
1097             default_scale[axis] = round(default_scale[axis]);
1098         } else if (default_scale[axis] != 0) {
1099             default_scale[axis] = 1/round(1/(MIN(default_scale[axis], 10)));
1100         }
1101         // Calculate the new transformation and update the handle position
1102         pt = _calcAbsAffineDefault(default_scale);
1103         // When stretching by an integer, snapping is not needed
1104     } else {
1105         // In all other cases we should try to snap now
1107         SnapManager &m = _desktop->namedview->snap_manager;
1108         m.setup(_desktop, false, _items_const);
1110         Inkscape::SnappedPoint bb, sn;
1111         g_assert(bb.getSnapped() == false); // Check initialization to catch any regression
1112         Geom::Coord bd(NR_HUGE);
1113         Geom::Coord sd(NR_HUGE);
1115         bool symmetrical = state & GDK_CONTROL_MASK;
1117         bb = m.constrainedSnapStretch(_bbox_points, _point, Geom::Coord(default_scale[axis]), _origin_for_bboxpoints, Geom::Dim2(axis), symmetrical);
1118         sn = m.constrainedSnapStretch(_snap_points, _point, Geom::Coord(geom_scale[axis]), _origin_for_specpoints, Geom::Dim2(axis), symmetrical);
1120         if (bb.getSnapped()) {
1121             // We snapped the bbox (which is either visual or geometric)
1122             bd = fabs(bb.getTransformation()[axis] - default_scale[axis]);
1123             default_scale[axis] = bb.getTransformation()[axis];
1124         }
1126         if (sn.getSnapped()) {
1127             sd = fabs(sn.getTransformation()[axis] - geom_scale[axis]);
1128             geom_scale[axis] = sn.getTransformation()[axis];
1129         }
1131         if (symmetrical) {
1132             // on ctrl, apply symmetrical scaling instead of stretching
1133             // Preserve aspect ratio, but never flip in the dimension not being edited (by using fabs())
1134             default_scale[perp] = fabs(default_scale[axis]);
1135             geom_scale[perp] = fabs(geom_scale[axis]);
1136         }
1138         if (!(bb.getSnapped() || sn.getSnapped())) {
1139             // We didn't snap at all! Don't update the handle position, just calculate the new transformation
1140             _calcAbsAffineDefault(default_scale);
1141             _desktop->snapindicator->remove_snaptarget();
1142         } else if (bd < sd) {
1143             _desktop->snapindicator->set_new_snaptarget(bb);
1144             // Calculate the new transformation and update the handle position
1145             pt = _calcAbsAffineDefault(default_scale);
1146         } else {
1147             _desktop->snapindicator->set_new_snaptarget(sn);
1148             // We snapped the special points (e.g. nodes), which are not at the visual bbox
1149             // The handle location however (pt) might however be at the visual bbox, so we
1150             // will have to calculate pt taking the stroke width into account
1151             pt = _calcAbsAffineGeom(geom_scale);
1152         }
1153     }
1155     // status text
1156     _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1157                           _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1158                           100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1160     return TRUE;
1163 gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1165     /* When skewing (or rotating):
1166      * 1) the stroke width will not change. This makes life much easier because we don't have to
1167      *    account for that (like for scaling or stretching). As a consequence, all points will
1168      *    have the same origin for the transformation and for the snapping.
1169      * 2) When holding shift, the transformation will be relative to the point opposite of
1170      *    the handle; otherwise it will be relative to the center as set for the selection
1171      */
1173     Geom::Dim2 dim_a;
1174     Geom::Dim2 dim_b;
1176     switch (handle.cursor) {
1177         case GDK_SB_H_DOUBLE_ARROW:
1178             dim_a = Geom::Y;
1179             dim_b = Geom::X;
1180             break;
1181         case GDK_SB_V_DOUBLE_ARROW:
1182             dim_a = Geom::X;
1183             dim_b = Geom::Y;
1184             break;
1185         default:
1186             g_assert_not_reached();
1187             abort();
1188             break;
1189     }
1191     Geom::Point const initial_delta = _point - _origin;
1193     if (fabs(initial_delta[dim_a]) < 1e-15) {
1194         return false;
1195     }
1197     // Calculate the scale factors, which can be either visual or geometric
1198     // depending on which type of bbox is currently being used (see preferences -> selector tool)
1199     Geom::Scale scale = calcScaleFactors(_point, pt, _origin, false);
1200     Geom::Scale skew = calcScaleFactors(_point, pt, _origin, true);
1201     scale[dim_b] = 1;
1202     skew[dim_b] = 1;
1204     if (fabs(scale[dim_a]) < 1) {
1205         // Prevent shrinking of the selected object, while allowing mirroring
1206         scale[dim_a] = sign(scale[dim_a]);
1207     } else {
1208         // Allow expanding of the selected object by integer multiples
1209         scale[dim_a] = floor(scale[dim_a] + 0.5);
1210     }
1212     double radians = atan(skew[dim_a] / scale[dim_a]);
1214     if (state & GDK_CONTROL_MASK) {
1215         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1216         // Snap to defined angle increments
1217         int snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12);
1218         if (snaps) {
1219             double sections = floor(radians * snaps / M_PI + .5);
1220             if (fabs(sections) >= snaps / 2) {
1221                 sections = sign(sections) * (snaps / 2 - 1);
1222             }
1223             radians = (M_PI / snaps) * sections;
1224         }
1225         skew[dim_a] = tan(radians) * scale[dim_a];
1226     } else {
1227         // Snap to objects, grids, guides
1229         SnapManager &m = _desktop->namedview->snap_manager;
1230         m.setup(_desktop, false, _items_const);
1232         Inkscape::Snapper::ConstraintLine const constraint(component_vectors[dim_b]);
1233         // When skewing, we cannot snap the corners of the bounding box, see the comment in "constrainedSnapSkew" for details
1234         Geom::Point const s(skew[dim_a], scale[dim_a]);
1235         Inkscape::SnappedPoint sn = m.constrainedSnapSkew(_snap_points, _point, constraint, s, _origin, Geom::Dim2(dim_b));
1237         if (sn.getSnapped()) {
1238             // We snapped something, so change the skew to reflect it
1239             Geom::Coord const sd = sn.getSnapped() ? sn.getTransformation()[0] : NR_HUGE;
1240              _desktop->snapindicator->set_new_snaptarget(sn);
1241             skew[dim_a] = sd;
1242         } else {
1243             _desktop->snapindicator->remove_snaptarget();
1244         }
1245     }
1247     // Update the handle position
1248     pt[dim_b] = initial_delta[dim_a] * skew[dim_a] + _point[dim_b];
1249     pt[dim_a] = initial_delta[dim_a] * scale[dim_a] + _origin[dim_a];
1251     // Calculate the relative affine
1252     _relative_affine = Geom::identity();
1253     _relative_affine[2*dim_a + dim_a] = (pt[dim_a] - _origin[dim_a]) / initial_delta[dim_a];
1254     _relative_affine[2*dim_a + (dim_b)] = (pt[dim_b] - _point[dim_b]) / initial_delta[dim_a];
1255     _relative_affine[2*(dim_b) + (dim_a)] = 0;
1256     _relative_affine[2*(dim_b) + (dim_b)] = 1;
1258     for (int i = 0; i < 2; i++) {
1259         if (fabs(_relative_affine[3*i]) < 1e-15) {
1260             _relative_affine[3*i] = 1e-15;
1261         }
1262     }
1264     // Update the status text
1265     double degrees = mod360symm(Geom::rad_to_deg(radians));
1266     _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1267                           // TRANSLATORS: don't modify the first ";"
1268                           // (it will NOT be displayed as ";" - only the second one will be)
1269                           _("<b>Skew</b>: %0.2f&#176;; with <b>Ctrl</b> to snap angle"),
1270                           degrees);
1272     return TRUE;
1275 gboolean Inkscape::SelTrans::rotateRequest(Geom::Point &pt, guint state)
1277     /* When rotating (or skewing):
1278      * 1) the stroke width will not change. This makes life much easier because we don't have to
1279      *    account for that (like for scaling or stretching). As a consequence, all points will
1280      *    have the same origin for the transformation and for the snapping.
1281      * 2) When holding shift, the transformation will be relative to the point opposite of
1282      *    the handle; otherwise it will be relative to the center as set for the selection
1283      */
1285     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1286     int snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12);
1288     // rotate affine in rotate
1289     Geom::Point const d1 = _point - _origin;
1290     Geom::Point const d2 = pt     - _origin;
1292     Geom::Coord const h1 = Geom::L2(d1); // initial radius
1293     if (h1 < 1e-15) return FALSE;
1294     Geom::Point q1 = d1 / h1; // normalized initial vector to handle
1295     Geom::Coord const h2 = Geom::L2(d2); // new radius
1296     if (fabs(h2) < 1e-15) return FALSE;
1297     Geom::Point q2 = d2 / h2; // normalized new vector to handle
1299     double radians;
1300     if (state & GDK_CONTROL_MASK) {
1301         // Snap to defined angle increments
1302         double cos_t = Geom::dot(q1, q2);
1303         double sin_t = Geom::dot(Geom::rot90(q1), q2);
1304         radians = atan2(sin_t, cos_t);
1305         if (snaps) {
1306             radians = ( M_PI / snaps ) * floor( radians * snaps / M_PI + .5 );
1307         }
1308         q1 = Geom::Point(1, 0);
1309         q2 = Geom::Point(cos(radians), sin(radians));
1310     } else {
1311         radians = atan2(Geom::dot(Geom::rot90(d1), d2),
1312                         Geom::dot(d1, d2));
1313     }
1315     Geom::Rotate const r1(q1);
1316     Geom::Rotate const r2(q2);
1318     // Calculate the relative affine
1319     _relative_affine = r2 * r1.inverse();
1321     // Update the handle position
1322     pt = _point * Geom::Translate(-_origin) * _relative_affine * Geom::Translate(_origin);
1324     // Update the status text
1325     double degrees = mod360symm(Geom::rad_to_deg(radians));
1326     _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1327                           // TRANSLATORS: don't modify the first ";"
1328                           // (it will NOT be displayed as ";" - only the second one will be)
1329                           _("<b>Rotate</b>: %0.2f&#176;; with <b>Ctrl</b> to snap angle"), degrees);
1331     return TRUE;
1334 // Move the item's transformation center
1335 gboolean Inkscape::SelTrans::centerRequest(Geom::Point &pt, guint state)
1337     SnapManager &m = _desktop->namedview->snap_manager;
1338     m.setup(_desktop);
1339     m.freeSnapReturnByRef(pt, Inkscape::SNAPSOURCE_OTHER_HANDLE);
1341     if (state & GDK_CONTROL_MASK) {
1342         if ( fabs(_point[Geom::X] - pt[Geom::X]) > fabs(_point[Geom::Y] - pt[Geom::Y]) ) {
1343             pt[Geom::Y] = _point[Geom::Y];
1344         } else {
1345             pt[Geom::X] = _point[Geom::X];
1346         }
1347     }
1349     if ( !(state & GDK_SHIFT_MASK) && _bbox ) {
1350         // screen pixels to snap center to bbox
1351 #define SNAP_DIST 5
1352         // FIXME: take from prefs
1353         double snap_dist = SNAP_DIST / _desktop->current_zoom();
1355         for (int i = 0; i < 2; i++) {
1356             if (fabs(pt[i] - _bbox->min()[i]) < snap_dist) {
1357                 pt[i] = _bbox->min()[i];
1358             }
1359             if (fabs(pt[i] - _bbox->midpoint()[i]) < snap_dist) {
1360                 pt[i] = _bbox->midpoint()[i];
1361             }
1362             if (fabs(pt[i] - _bbox->max()[i]) < snap_dist) {
1363                 pt[i] = _bbox->max()[i];
1364             }
1365         }
1366     }
1368     // status text
1369     GString *xs = SP_PX_TO_METRIC_STRING(pt[Geom::X], _desktop->namedview->getDefaultMetric());
1370     GString *ys = SP_PX_TO_METRIC_STRING(pt[Geom::Y], _desktop->namedview->getDefaultMetric());
1371     _message_context.setF(Inkscape::NORMAL_MESSAGE, _("Move <b>center</b> to %s, %s"), xs->str, ys->str);
1372     g_string_free(xs, FALSE);
1373     g_string_free(ys, FALSE);
1375     return TRUE;
1378 /*
1379  * handlers for handle movement
1380  *
1381  */
1383 void sp_sel_trans_stretch(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1385     seltrans->stretch(handle, pt, state);
1388 void sp_sel_trans_scale(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint state)
1390     seltrans->scale(pt, state);
1393 void sp_sel_trans_skew(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1395     seltrans->skew(handle, pt, state);
1398 void sp_sel_trans_rotate(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint state)
1400     seltrans->rotate(pt, state);
1403 void Inkscape::SelTrans::stretch(SPSelTransHandle const &/*handle*/, Geom::Point &/*pt*/, guint /*state*/)
1405     transform(_absolute_affine, Geom::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1408 void Inkscape::SelTrans::scale(Geom::Point &/*pt*/, guint /*state*/)
1410     transform(_absolute_affine, Geom::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1413 void Inkscape::SelTrans::skew(SPSelTransHandle const &/*handle*/, Geom::Point &/*pt*/, guint /*state*/)
1415     transform(_relative_affine, _origin);
1418 void Inkscape::SelTrans::rotate(Geom::Point &/*pt*/, guint /*state*/)
1420     transform(_relative_affine, _origin);
1423 void sp_sel_trans_center(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint /*state*/)
1425     seltrans->setCenter(pt);
1429 void Inkscape::SelTrans::moveTo(Geom::Point const &xy, guint state)
1431     SnapManager &m = _desktop->namedview->snap_manager;
1433     /* The amount that we've moved by during this drag */
1434     Geom::Point dxy = xy - _point;
1436     bool const alt = (state & GDK_MOD1_MASK);
1437     bool const control = (state & GDK_CONTROL_MASK);
1438     bool const shift = (state & GDK_SHIFT_MASK);
1440     if (alt) {
1442         // Alt pressed means: move only by integer multiples of the grid spacing
1444         if (control) { // ... if also constrained to the orthogonal axes
1445             if (fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y])) {
1446                 dxy[Geom::Y] = 0;
1447             } else {
1448                 dxy[Geom::X] = 0;
1449             }
1450         }
1451         m.setup(_desktop, true, _items_const);
1452         dxy = m.multipleOfGridPitch(dxy, _point);
1453     } else if (shift) {
1454         if (control) { // shift & control: constrained movement without snapping
1455             if (fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y])) {
1456                 dxy[Geom::Y] = 0;
1457             } else {
1458                 dxy[Geom::X] = 0;
1459             }
1460         }
1461     } else { //!shift: with snapping
1463         /* We're snapping to things, possibly with a constraint to horizontal or
1464         ** vertical movement.  Obtain a list of possible translations and then
1465         ** pick the smallest.
1466         */
1468         m.setup(_desktop, false, _items_const);
1470         /* This will be our list of possible translations */
1471         std::list<Inkscape::SnappedPoint> s;
1473         if (control) { // constrained movement with snapping
1475             /* Snap to things, and also constrain to horizontal or vertical movement */
1477             unsigned int dim = fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y]) ? Geom::X : Geom::Y;
1478             // When doing a constrained translation, all points will move in the same direction, i.e.
1479             // either horizontally or vertically. Therefore we only have to specify the direction of
1480             // the constraint-line once. The constraint lines are parallel, but might not be colinear.
1481             // Therefore we will have to set the point through which the constraint-line runs
1482             // individually for each point to be snapped; this will be handled however by _snapTransformed()
1483             s.push_back(m.constrainedSnapTranslation(_bbox_points_for_translating,
1484                                                      _point,
1485                                                      Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1486                                                      dxy));
1488             s.push_back(m.constrainedSnapTranslation(_snap_points,
1489                                                      _point,
1490                                                      Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1491                                                      dxy));
1492         } else { // !control
1494             // Let's leave this timer code here for a while. I'll probably need it in the near future (Diederik van Lierop)
1495             /* GTimeVal starttime;
1496             GTimeVal endtime;
1497             g_get_current_time(&starttime); */
1499             /* Snap to things with no constraint */
1500             s.push_back(m.freeSnapTranslation(_bbox_points_for_translating, _point, dxy));
1501             s.push_back(m.freeSnapTranslation(_snap_points, _point, dxy));
1503               /*g_get_current_time(&endtime);
1504               double elapsed = ((((double)endtime.tv_sec - starttime.tv_sec) * G_USEC_PER_SEC + (endtime.tv_usec - starttime.tv_usec))) / 1000.0;
1505               std::cout << "Time spent snapping: " << elapsed << std::endl; */
1506         }
1508         /* Pick one */
1509         Inkscape::SnappedPoint best_snapped_point;
1510         for (std::list<Inkscape::SnappedPoint>::const_iterator i = s.begin(); i != s.end(); i++) {
1511             if (i->getSnapped()) {
1512                 if (best_snapped_point.isOtherSnapBetter(*i, true)) {
1513                     best_snapped_point = *i;
1514                     dxy = i->getTransformation();
1515                 }
1516             }
1517         }
1519         if (best_snapped_point.getSnapped()) {
1520             _desktop->snapindicator->set_new_snaptarget(best_snapped_point);
1521         } else {
1522             // We didn't snap, so remove any previous snap indicator
1523             _desktop->snapindicator->remove_snaptarget();
1524             if (control) {
1525                 // If we didn't snap, then we should still constrain horizontally or vertically
1526                 // (When we did snap, then this constraint has already been enforced by
1527                 // calling constrainedSnapTranslation() above)
1528                 if (fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y])) {
1529                     dxy[Geom::Y] = 0;
1530                 } else {
1531                     dxy[Geom::X] = 0;
1532                 }
1533             }
1534         }
1535     }
1537     Geom::Matrix const move((Geom::Translate(dxy)));
1538     Geom::Point const norm(0, 0);
1539     transform(move, norm);
1541     // status text
1542     GString *xs = SP_PX_TO_METRIC_STRING(dxy[Geom::X], _desktop->namedview->getDefaultMetric());
1543     GString *ys = SP_PX_TO_METRIC_STRING(dxy[Geom::Y], _desktop->namedview->getDefaultMetric());
1544     _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);
1545     g_string_free(xs, TRUE);
1546     g_string_free(ys, TRUE);
1549 // Given a location of a handle at the visual bounding box, find the corresponding location at the
1550 // geometrical bounding box
1551 Geom::Point Inkscape::SelTrans::_getGeomHandlePos(Geom::Point const &visual_handle_pos)
1553     if ( _snap_bbox_type == SPItem::GEOMETRIC_BBOX) {
1554         // When the selector tool is using geometric bboxes, then the handle is already
1555         // located at one of the geometric bbox corners
1556         return visual_handle_pos;
1557     }
1559     if (!_geometric_bbox) {
1560         //_getGeomHandlePos() can only be used after _geometric_bbox has been defined!
1561         return visual_handle_pos;
1562     }
1564     // Using the Geom::Rect constructor below ensures that "min() < max()", which is important
1565     // because this will also hold for _bbox, and which is required for get_scale_transform_with_stroke()
1566     Geom::Rect new_bbox = Geom::Rect(_origin_for_bboxpoints, visual_handle_pos); // new visual bounding box
1567     // Please note that the new_bbox might in fact be just a single line, for example when stretching (in
1568     // which case the handle and origin will be aligned vertically or horizontally)
1569     Geom::Point normalized_handle_pos = (visual_handle_pos - new_bbox.min()) * Geom::Scale(new_bbox.dimensions()).inverse();
1571     // Calculate the absolute affine while taking into account the scaling of the stroke width
1572     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1573     bool transform_stroke = prefs->getBool("/options/transform/stroke", true);
1574     Geom::Matrix abs_affine = get_scale_transform_with_stroke (*_bbox, _strokewidth, transform_stroke,
1575                     new_bbox.min()[Geom::X], new_bbox.min()[Geom::Y], new_bbox.max()[Geom::X], new_bbox.max()[Geom::Y]);
1577     // Calculate the scaled geometrical bbox
1578     Geom::Rect new_geom_bbox = Geom::Rect(_geometric_bbox->min() * abs_affine, _geometric_bbox->max() * abs_affine);
1579     // Find the location of the handle on this new geometrical bbox
1580     return normalized_handle_pos * Geom::Scale(new_geom_bbox.dimensions()) + new_geom_bbox.min(); //new position of the geometric handle
1583 Geom::Scale Inkscape::calcScaleFactors(Geom::Point const &initial_point, Geom::Point const &new_point, Geom::Point const &origin, bool const skew)
1585     // Work out the new scale factors for the bbox
1587     Geom::Point const initial_delta = initial_point - origin;
1588     Geom::Point const new_delta = new_point - origin;
1589     Geom::Point const offset = new_point - initial_point;
1590     Geom::Scale scale(1, 1);
1592     for ( unsigned int i = 0 ; i < 2 ; i++ ) {
1593         if ( fabs(initial_delta[i]) > 1e-6 ) {
1594             if (skew) {
1595                 scale[i] = offset[1-i] / initial_delta[i];
1596             } else {
1597                 scale[i] = new_delta[i] / initial_delta[i];
1598             }
1599         }
1600     }
1602     return scale;
1605 // Only for scaling/stretching
1606 Geom::Point Inkscape::SelTrans::_calcAbsAffineDefault(Geom::Scale const default_scale)
1608     Geom::Matrix abs_affine = Geom::Translate(-_origin) * Geom::Matrix(default_scale) * Geom::Translate(_origin);
1609     Geom::Point new_bbox_min = _approximate_bbox->min() * abs_affine;
1610     Geom::Point new_bbox_max = _approximate_bbox->max() * abs_affine;
1612     bool transform_stroke = false;
1613     gdouble strokewidth = 0;
1615     if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
1616         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1617         transform_stroke = prefs->getBool("/options/transform/stroke", true);
1618         strokewidth = _strokewidth;
1619     }
1621     _absolute_affine = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
1622                     new_bbox_min[Geom::X], new_bbox_min[Geom::Y], new_bbox_max[Geom::X], new_bbox_max[Geom::Y]);
1624     // return the new handle position
1625     return ( _point - _origin ) * default_scale + _origin;
1628 // Only for scaling/stretching
1629 Geom::Point Inkscape::SelTrans::_calcAbsAffineGeom(Geom::Scale const geom_scale)
1631     _relative_affine = Geom::Matrix(geom_scale);
1632     _absolute_affine = Geom::Translate(-_origin_for_specpoints) * _relative_affine * Geom::Translate(_origin_for_specpoints);
1634     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1635     bool const transform_stroke = prefs->getBool("/options/transform/stroke", true);
1636     if (_geometric_bbox) {
1637         Geom::Rect visual_bbox = get_visual_bbox(_geometric_bbox, _absolute_affine, _strokewidth, transform_stroke);
1638         // return the new handle position
1639         return visual_bbox.min() + visual_bbox.dimensions() * Geom::Scale(_handle_x, _handle_y);
1640     }
1642     // Fall back scenario, in case we don't have a geometric bounding box at hand;
1643     // (Due to some bugs related to bounding boxes having at least one zero dimension; For more details
1644     // see https://bugs.launchpad.net/inkscape/+bug/318726)
1645     g_warning("No geometric bounding box has been calculated; this is a bug that needs fixing!");
1646     return _calcAbsAffineDefault(geom_scale); // this is bogus, but we must return _something_
1649 void Inkscape::SelTrans::_keepClosestPointOnly(std::vector<Inkscape::SnapCandidatePoint> &points, const Geom::Point &reference)
1651     if (points.size() < 2) return;
1653     Inkscape::SnapCandidatePoint closest_point = Inkscape::SnapCandidatePoint(Geom::Point(NR_HUGE, NR_HUGE), SNAPSOURCE_UNDEFINED, SNAPTARGET_UNDEFINED);
1654     Geom::Coord closest_dist = NR_HUGE;
1656     for(std::vector<Inkscape::SnapCandidatePoint>::const_iterator i = points.begin(); i != points.end(); i++) {
1657         Geom::Coord dist = Geom::L2((*i).getPoint() - reference);
1658         if (i == points.begin() || dist < closest_dist) {
1659             closest_point = *i;
1660             closest_dist = dist;
1661         }
1662     }
1664     points.clear();
1665     points.push_back(closest_point);
1668 /*
1669   Local Variables:
1670   mode:c++
1671   c-file-style:"stroustrup"
1672   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1673   indent-tabs-mode:nil
1674   fill-column:99
1675   End:
1676 */
1677 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :