Code

Removed duplication of menu items.
[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);
248     g_return_if_fail(!_grabbed);
250     _grabbed = true;
251     _show_handles = show_handles;
252     _updateVolatileState();
253     _current_relative_affine.setIdentity();
255     _changed = false;
257     if (_empty) {
258         return;
259     }
261     for (GSList const *l = selection->itemList(); l; l = l->next) {
262         SPItem *it = (SPItem *)sp_object_ref(SP_OBJECT(l->data), NULL);
263         _items.push_back(it);
264         _items_const.push_back(it);
265         _items_affines.push_back(sp_item_i2d_affine(it));
266         _items_centers.push_back(it->getCenter()); // for content-dragging, we need to remember original centers
267     }
269     _handle_x = x;
270     _handle_y = y;
272     // The selector tool should snap the bbox, special snappoints, and path nodes
273     // (The special points are the handles, center, rotation axis, font baseline, ends of spiral, etc.)
275     // First, determine the bounding box for snapping ...
276     _bbox = selection->bounds(_snap_bbox_type);
277     _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX); // Used for correctly scaling the strokewidth
278     _geometric_bbox = selection->bounds(SPItem::GEOMETRIC_BBOX);
279     _point = p;
280     if (_geometric_bbox) {
281         _point_geom = _geometric_bbox->min() + _geometric_bbox->dimensions() * Geom::Scale(x, y);
282     } else {
283         _point_geom = p;
284     }
286     // Next, get all points to consider for snapping
287     SnapManager const &m = _desktop->namedview->snap_manager;
288     _snap_points.clear();
289     _snap_points = selection->getSnapPoints(&m.snapprefs);
290     std::vector<Geom::Point> snap_points_hull = selection->getSnapPointsConvexHull(&m.snapprefs);
291     if (_snap_points.size() > 100) {
292         /* Snapping a huge number of nodes will take way too long, so limit the number of snappable nodes
293         An average user would rarely ever try to snap such a large number of nodes anyway, because
294         (s)he could hardly discern which node would be snapping */
295         _snap_points = snap_points_hull;
296         // Unfortunately, by now we will have lost the font-baseline snappoints :-(
297     }
298     
299     // Find bbox hulling all special points, which excludes stroke width. Here we need to include the
300     // path nodes, for example because a rectangle which has been converted to a path doesn't have
301     // any other special points
302     Geom::Rect snap_points_bbox;
303     if ( snap_points_hull.empty() == false ) {
304         std::vector<Geom::Point>::iterator i = snap_points_hull.begin();
305         snap_points_bbox = Geom::Rect(*i, *i);
306         i++;
307         while (i != snap_points_hull.end()) {
308             snap_points_bbox.expandTo(*i);
309             i++;
310         }
311     }
313     _bbox_points.clear();
314     if (_bbox) {
315         // ... and add the bbox corners to _bbox_points
316         for ( unsigned i = 0 ; i < 4 ; i++ ) {
317             _bbox_points.push_back(_bbox->corner(i));
318         }
319         // There are two separate "opposites" (i.e. opposite w.r.t. the handle being dragged):
320         //  - one for snapping the boundingbox, which can be either visual or geometric
321         //  - one for snapping the special points
322         // The "opposite" in case of a geometric boundingbox always coincides with the "opposite" for the special points
323         // These distinct "opposites" are needed in the snapmanager to avoid bugs such as #sf1540195 (in which
324         // a box is caught between two guides)
325         _opposite_for_bboxpoints = _bbox->min() + _bbox->dimensions() * Geom::Scale(1-x, 1-y);
326         _opposite_for_specpoints = snap_points_bbox.min() + snap_points_bbox.dimensions() * Geom::Scale(1-x, 1-y);
327         _opposite = _opposite_for_bboxpoints;
328     }
329     
330     // When snapping the node closest to the mouse pointer is absolutely preferred over the closest snap 
331     // (i.e. when weight == 1), then we will not even try to snap to other points and discard those other
332     // points immediately. 
333     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
334         if (prefs->getBool("/options/snapclosestonly/value", false)) {
335         if (m.snapprefs.getSnapModeNode()) {
336                         _keepClosestPointOnly(_snap_points, p);
337         } else {
338                 _snap_points.clear(); // don't keep any point
339         }
340                 
341         if (m.snapprefs.getSnapModeBBox()) {
342                         _keepClosestPointOnly(_bbox_points, p);
343                 } else {
344                         _bbox_points.clear(); // don't keep any point
345                 }                       
346         
347         g_assert(_bbox_points.size() < 2 && _snap_points.size() < 2);
348         if (_snap_points.size() == 1 && _bbox_points.size() == 1) { //both vectors can only have either one or zero elements
349                 // So we have exactly one bbox corner and one node left; now find out which is closest and delete the other one
350                 if (Geom::L2(_snap_points.at(0) - p) < Geom::L2(_bbox_points.at(0) - p)) {
351                         _bbox_points.clear();
352                 } else {
353                         _snap_points.clear();
354                 }
355                 }
356         
357         // Now either _bbox_points or _snap_points has a single element, the other one has zero..... or both have zero elements
358         g_assert((_bbox_points.size() + _snap_points.size()) < 2);
359         if (_bbox_points.size() == 1) {
360                 _desktop->snapindicator->set_new_snapsource(_bbox_points.at(0));
361         } else if (_snap_points.size() == 1){
362                 _desktop->snapindicator->set_new_snapsource(_snap_points.at(0));
363         }
364     }
366     // The lines below are useful for debugging any snapping issues, as they'll spit out all points that are considered for snapping
368     /*std::cout << "Number of snap points:  " << _snap_points.size() << std::endl;
369     for (std::vector<Geom::Point>::const_iterator i = _snap_points.begin(); i != _snap_points.end(); i++)
370     {
371         std::cout << "    " << *i << std::endl;
372     }
374     std::cout << "Number of bbox points:  " << _bbox_points.size() << std::endl;
375     for (std::vector<Geom::Point>::const_iterator i = _bbox_points.begin(); i != _bbox_points.end(); i++)
376     {
377         std::cout << "    " << *i << std::endl;
378     }*/
380     if ((x != -1) && (y != -1)) {
381         sp_canvas_item_show(_norm);
382         sp_canvas_item_show(_grip);
383     }
385     if (_show == SHOW_OUTLINE) {
386         for (int i = 0; i < 4; i++)
387             sp_canvas_item_show(_l[i]);
388     }
390     _updateHandles();
391     g_return_if_fail(_stamp_cache == NULL);
394 void Inkscape::SelTrans::transform(Geom::Matrix const &rel_affine, Geom::Point const &norm)
396     g_return_if_fail(_grabbed);
397     g_return_if_fail(!_empty);
399     Geom::Matrix const affine( Geom::Translate(-norm) * rel_affine * Geom::Translate(norm) );
401     if (_show == SHOW_CONTENT) {
402         // update the content
403         for (unsigned i = 0; i < _items.size(); i++) {
404             SPItem &item = *_items[i];
405             Geom::Matrix const &prev_transform = _items_affines[i];
406             sp_item_set_i2d_affine(&item, prev_transform * affine);
407         }
408     } else {
409         if (_bbox) {
410             Geom::Point p[4];
411             /* update the outline */
412             for (unsigned i = 0 ; i < 4 ; i++) {
413                 p[i] = _bbox->corner(i) * affine;
414             }
415             for (unsigned i = 0 ; i < 4 ; i++) {
416                 sp_ctrlline_set_coords(SP_CTRLLINE(_l[i]), p[i], p[(i+1)%4]);
417             }
418         }
419     }
421     _current_relative_affine = affine;
422     _changed = true;
423     _updateHandles();
426 void Inkscape::SelTrans::ungrab()
428     g_return_if_fail(_grabbed);
429     _grabbed = false;
430     _show_handles = true;
432     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
433     _updateVolatileState();
435     for (unsigned i = 0; i < _items.size(); i++) {
436         sp_object_unref(SP_OBJECT(_items[i]), NULL);
437     }
439     sp_canvas_item_hide(_norm);
440     sp_canvas_item_hide(_grip);
442     if (_show == SHOW_OUTLINE) {
443         for (int i = 0; i < 4; i++)
444             sp_canvas_item_hide(_l[i]);
445     }
447     if (_stamp_cache) {
448         g_slist_free(_stamp_cache);
449         _stamp_cache = NULL;
450     }
452     _message_context.clear();
454     if (!_empty && _changed) {
455         sp_selection_apply_affine(selection, _current_relative_affine, (_show == SHOW_OUTLINE)? true : false);
456         if (_center) {
457             *_center *= _current_relative_affine;
458             _center_is_set = true;
459         }
461 // If dragging showed content live, sp_selection_apply_affine cannot change the centers
462 // appropriately - it does not know the original positions of the centers (all objects already have
463 // the new bboxes). So we need to reset the centers from our saved array.
464         if (_show != SHOW_OUTLINE && !_current_relative_affine.isTranslation()) {
465             for (unsigned i = 0; i < _items_centers.size(); i++) {
466                 SPItem *currentItem = _items[i];
467                 if (currentItem->isCenterSet()) { // only if it's already set
468                     currentItem->setCenter (_items_centers[i] * _current_relative_affine);
469                     SP_OBJECT(currentItem)->updateRepr();
470                 }
471             }
472         }
474         _items.clear();
475         _items_const.clear();
476         _items_affines.clear();
477         _items_centers.clear();
479         if (_current_relative_affine.isTranslation()) {
480             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
481                              _("Move"));
482         } else if (_current_relative_affine.isScale()) {
483             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
484                              _("Scale"));
485         } else if (_current_relative_affine.isRotation()) {
486             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
487                              _("Rotate"));
488         } else {
489             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
490                              _("Skew"));
491         }
493     } else {
495         if (_center_is_set) {
496             // we were dragging center; update reprs and commit undoable action
497             for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
498                 SPItem *it = (SPItem*)SP_OBJECT(l->data);
499                 SP_OBJECT(it)->updateRepr();
500             }
501             sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
502                             _("Set center"));
503         }
505         _items.clear();
506         _items_const.clear();
507         _items_affines.clear();
508         _items_centers.clear();
509         _updateHandles();
510     }
513 /* fixme: This is really bad, as we compare positions for each stamp (Lauris) */
514 /* fixme: IMHO the best way to keep sort cache would be to implement timestamping at last */
516 void Inkscape::SelTrans::stamp()
518     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
520     bool fixup = !_grabbed;
521     if ( fixup && _stamp_cache ) {
522         // TODO - give a proper fix. Simple temproary work-around for the grab() issue
523         g_slist_free(_stamp_cache);
524         _stamp_cache = NULL;
525     }
527     /* stamping mode */
528     if (!_empty) {
529         GSList *l;
530         if (_stamp_cache) {
531             l = _stamp_cache;
532         } else {
533             /* Build cache */
534             l  = g_slist_copy((GSList *) selection->itemList());
535             l  = g_slist_sort(l, (GCompareFunc) sp_object_compare_position);
536             _stamp_cache = l;
537         }
539         while (l) {
540             SPItem *original_item = SP_ITEM(l->data);
541             Inkscape::XML::Node *original_repr = SP_OBJECT_REPR(original_item);
543             // remember the position of the item
544             gint pos = original_repr->position();
545             // remember parent
546             Inkscape::XML::Node *parent = sp_repr_parent(original_repr);
548             Inkscape::XML::Node *copy_repr = original_repr->duplicate(parent->document());
550             // add the new repr to the parent
551             parent->appendChild(copy_repr);
552             // move to the saved position
553             copy_repr->setPosition(pos > 0 ? pos : 0);
555             SPItem *copy_item = (SPItem *) sp_desktop_document(_desktop)->getObjectByRepr(copy_repr);
557             Geom::Matrix const *new_affine;
558             if (_show == SHOW_OUTLINE) {
559                 Geom::Matrix const i2d(sp_item_i2d_affine(original_item));
560                 Geom::Matrix const i2dnew( i2d * _current_relative_affine );
561                 sp_item_set_i2d_affine(copy_item, i2dnew);
562                 new_affine = &copy_item->transform;
563             } else {
564                 new_affine = &original_item->transform;
565             }
567             sp_item_write_transform(copy_item, copy_repr, *new_affine);
569             if ( copy_item->isCenterSet() && _center ) {
570                 copy_item->setCenter(*_center * _current_relative_affine);
571             }
573             Inkscape::GC::release(copy_repr);
574             l = l->next;
575         }
576         sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
577                          _("Stamp"));
578     }
580     if ( fixup && _stamp_cache ) {
581         // TODO - give a proper fix. Simple temproary work-around for the grab() issue
582         g_slist_free(_stamp_cache);
583         _stamp_cache = NULL;
584     }
587 void Inkscape::SelTrans::_updateHandles()
589     if ( !_show_handles || _empty )
590     {
591         sp_remove_handles(_shandle, 8);
592         sp_remove_handles(_rhandle, 8);
593         sp_remove_handles(&_chandle, 1);
594         return;
595     }
597     // center handle
598     if ( _chandle == NULL ) {
599         _chandle = sp_knot_new(_desktop, _("<b>Center</b> of rotation and skewing: drag to reposition; scaling with Shift also uses this center"));
601         _chandle->setShape (SP_CTRL_SHAPE_BITMAP);
602         _chandle->setSize (13);
603         _chandle->setAnchor (handle_center.anchor);
604         _chandle->setMode (SP_CTRL_MODE_XOR);
605         _chandle->setFill(0x00000000, 0x00000000, 0x00000000);
606         _chandle->setStroke(0x000000ff, 0xff0000b0, 0xff0000b0);
607         _chandle->setPixbuf(handles[handle_center.control]);
608         sp_knot_update_ctrl(_chandle);
610         g_signal_connect(G_OBJECT(_chandle), "request",
611                          G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle_center);
612         g_signal_connect(G_OBJECT(_chandle), "moved",
613                          G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle_center);
614         g_signal_connect(G_OBJECT(_chandle), "grabbed",
615                          G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle_center);
616         g_signal_connect(G_OBJECT(_chandle), "ungrabbed",
617                          G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle_center);
618         g_signal_connect(G_OBJECT(_chandle), "clicked",
619                          G_CALLBACK(sp_sel_trans_handle_click), (gpointer) &handle_center);
620     }
622     sp_remove_handles(&_chandle, 1);
623     if ( _state == STATE_SCALE ) {
624         sp_remove_handles(_rhandle, 8);
625         _showHandles(_shandle, handles_scale, 8,
626                     _("<b>Squeeze or stretch</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"),
627                     _("<b>Scale</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"));
628     } else {
629         sp_remove_handles(_shandle, 8);
630         _showHandles(_rhandle, handles_rotate, 8,
631                     _("<b>Skew</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to skew around the opposite side"),
632                     _("<b>Rotate</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to rotate around the opposite corner"));
633     }
635     if (!_center_is_set) {
636         _center = _desktop->selection->center();
637         _center_is_set = true;
638     }
640     if ( _state == STATE_SCALE || !_center ) {
641         sp_knot_hide(_chandle);
642     } else {
643         sp_knot_show(_chandle);
644         sp_knot_moveto(_chandle, *_center);
645     }
648 void Inkscape::SelTrans::_updateVolatileState()
650     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
651     _empty = selection->isEmpty();
653     if (_empty) {
654         return;
655     }
657     //Update the bboxes
658     _bbox = selection->bounds(_snap_bbox_type);
659     _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX);
661     if (!_bbox) {
662         _empty = true;
663         return;
664     }
666     _strokewidth = stroke_average_width (selection->itemList());
669 static void sp_remove_handles(SPKnot *knot[], gint num)
671     for (int i = 0; i < num; i++) {
672         if (knot[i] != NULL) {
673             sp_knot_hide(knot[i]);
674         }
675     }
678 void Inkscape::SelTrans::_showHandles(SPKnot *knot[], SPSelTransHandle const handle[], gint num,
679                              gchar const *even_tip, gchar const *odd_tip)
681     g_return_if_fail( !_empty );
683     for (int i = 0; i < num; i++) {
684         if (knot[i] == NULL) {
685             knot[i] = sp_knot_new(_desktop, i % 2 ? even_tip : odd_tip);
687             knot[i]->setShape (SP_CTRL_SHAPE_BITMAP);
688             knot[i]->setSize (13);
689             knot[i]->setAnchor (handle[i].anchor);
690             knot[i]->setMode (SP_CTRL_MODE_XOR);
691             knot[i]->setFill(0x000000ff, 0x00ff6600, 0x00ff6600); // inversion, green, green
692             knot[i]->setStroke(0x000000ff, 0x000000ff, 0x000000ff); // inversion
693             knot[i]->setPixbuf(handles[handle[i].control]);
694             sp_knot_update_ctrl(knot[i]);
696             g_signal_connect(G_OBJECT(knot[i]), "request",
697                              G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle[i]);
698             g_signal_connect(G_OBJECT(knot[i]), "moved",
699                              G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle[i]);
700             g_signal_connect(G_OBJECT(knot[i]), "grabbed",
701                              G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle[i]);
702             g_signal_connect(G_OBJECT(knot[i]), "ungrabbed",
703                              G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle[i]);
704             g_signal_connect(G_OBJECT(knot[i]), "event", G_CALLBACK(sp_seltrans_handle_event), (gpointer) &handle[i]);
705         }
706         sp_knot_show(knot[i]);
708         Geom::Point const handle_pt(handle[i].x, handle[i].y);
709         // shouldn't have nullary bbox, but knots
710         g_assert(_bbox);
711         Geom::Point p( _bbox->min()
712                      + ( _bbox->dimensions()
713                          * Geom::Scale(handle_pt) ) );
715         sp_knot_moveto(knot[i], p);
716     }
719 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data)
721     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleGrab(
722         knot, state, *(SPSelTransHandle const *) data
723         );
726 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint /*state*/, gpointer /*data*/)
728     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->ungrab();
731 static void sp_sel_trans_handle_new_event(SPKnot *knot, Geom::Point *position, guint state, gpointer data)
733     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleNewEvent(
734         knot, position, state, *(SPSelTransHandle const *) data
735         );
738 static gboolean sp_sel_trans_handle_request(SPKnot *knot, Geom::Point *position, guint state, gboolean *data)
740     return SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleRequest(
741         knot, position, state, *(SPSelTransHandle const *) data
742         );
745 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data)
747     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleClick(
748         knot, state, *(SPSelTransHandle const *) data
749         );
752 void Inkscape::SelTrans::handleClick(SPKnot */*knot*/, guint state, SPSelTransHandle const &handle)
754     switch (handle.anchor) {
755         case GTK_ANCHOR_CENTER:
756             if (state & GDK_SHIFT_MASK) {
757                 // Unset the  center position for all selected items
758                 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
759                     SPItem *it = (SPItem*)(SP_OBJECT(l->data));
760                     it->unsetCenter();
761                     SP_OBJECT(it)->updateRepr();
762                     _center_is_set = false;  // center has changed
763                     _updateHandles();
764                 }
765                 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
766                                         _("Reset center"));
767             }
768             break;
769         default:
770             break;
771     }
774 void Inkscape::SelTrans::handleGrab(SPKnot *knot, guint /*state*/, SPSelTransHandle const &handle)
776     switch (handle.anchor) {
777         case GTK_ANCHOR_CENTER:
778             g_object_set(G_OBJECT(_grip),
779                          "shape", SP_CTRL_SHAPE_BITMAP,
780                          "size", 13.0,
781                          NULL);
782             sp_canvas_item_show(_grip);
783             break;
784         default:
785             g_object_set(G_OBJECT(_grip),
786                          "shape", SP_CTRL_SHAPE_CROSS,
787                          "size", 7.0,
788                          NULL);
789             sp_canvas_item_show(_norm);
790             sp_canvas_item_show(_grip);
792             break;
793     }
795     grab(sp_knot_position(knot), handle.x, handle.y, FALSE);
799 void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const &handle)
801     if (!SP_KNOT_IS_GRABBED(knot)) {
802         return;
803     }
805     // in case items have been unhooked from the document, don't
806     // try to continue processing events for them.
807     for (unsigned int i = 0; i < _items.size(); i++) {
808         if (!SP_OBJECT_DOCUMENT(SP_OBJECT(_items[i])) ) {
809             return;
810         }
811     }
813     handle.action(this, handle, *position, state);
817 gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const &handle)
819     if (!SP_KNOT_IS_GRABBED(knot)) {
820         return TRUE;
821     }
823     knot->desktop->setPosition(*position);
825     // When holding shift while rotating or skewing, the transformation will be
826     // relative to the point opposite of the handle; otherwise it will be relative
827     // to the center as set for the selection
828     if ((!(state & GDK_SHIFT_MASK) == !(_state == STATE_ROTATE)) && (&handle != &handle_center)) {
829         _origin = _opposite;
830         _origin_for_bboxpoints = _opposite_for_bboxpoints;
831         _origin_for_specpoints = _opposite_for_specpoints;
832     } else if (_center) {
833         _origin = *_center;
834         _origin_for_bboxpoints = *_center;
835         _origin_for_specpoints = *_center;
836     } else {
837         // FIXME
838         return TRUE;
839     }
840     if (handle.request(this, handle, *position, state)) {
841         sp_knot_set_position(knot, *position, state);
842         SP_CTRL(_grip)->moveto(*position);
843         SP_CTRL(_norm)->moveto(_origin);
844     }
846     return TRUE;
850 void Inkscape::SelTrans::_selChanged(Inkscape::Selection */*selection*/)
852     if (!_grabbed) {
853         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
854         // reread in case it changed on the fly:
855         int prefs_bbox = prefs->getBool("/tools/bounding_box");
856          _snap_bbox_type = !prefs_bbox ?
857             SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
858         //SPItem::APPROXIMATE_BBOX will be replaced by SPItem::VISUAL_BBOX, as soon as the latter is implemented properly
860         _updateVolatileState();
861         _current_relative_affine.setIdentity();
862         _center_is_set = false; // center(s) may have changed
863         _updateHandles();
864     }
867 void Inkscape::SelTrans::_selModified(Inkscape::Selection */*selection*/, guint /*flags*/)
869     if (!_grabbed) {
870         _updateVolatileState();
871         _current_relative_affine.setIdentity();
873         // reset internal flag
874         _changed = false;
876         _center_is_set = false;  // center(s) may have changed
878         _updateHandles();
879     }
882 /*
883  * handlers for handle move-request
884  */
886 /** Returns -1 or 1 according to the sign of x.  Returns 1 for 0 and NaN. */
887 static double sign(double const x)
889     return ( x < 0
890              ? -1
891              : 1 );
894 gboolean sp_sel_trans_scale_request(Inkscape::SelTrans *seltrans,
895                                     SPSelTransHandle const &, Geom::Point &pt, guint state)
897     return seltrans->scaleRequest(pt, state);
900 gboolean sp_sel_trans_stretch_request(Inkscape::SelTrans *seltrans,
901                                       SPSelTransHandle const &handle, Geom::Point &pt, guint state)
903     return seltrans->stretchRequest(handle, pt, state);
906 gboolean sp_sel_trans_skew_request(Inkscape::SelTrans *seltrans,
907                                    SPSelTransHandle const &handle, Geom::Point &pt, guint state)
909     return seltrans->skewRequest(handle, pt, state);
912 gboolean sp_sel_trans_rotate_request(Inkscape::SelTrans *seltrans,
913                                      SPSelTransHandle const &, Geom::Point &pt, guint state)
915     return seltrans->rotateRequest(pt, state);
918 gboolean sp_sel_trans_center_request(Inkscape::SelTrans *seltrans,
919                                      SPSelTransHandle const &, Geom::Point &pt, guint state)
921     return seltrans->centerRequest(pt, state);
924 gboolean Inkscape::SelTrans::scaleRequest(Geom::Point &pt, guint state)
927     // Calculate the scale factors, which can be either visual or geometric
928     // depending on which type of bbox is currently being used (see preferences -> selector tool)
929     Geom::Scale default_scale = calcScaleFactors(_point, pt, _origin);
931     // Find the scale factors for the geometric bbox
932     Geom::Point pt_geom = _getGeomHandlePos(pt);
933     Geom::Scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
935     _absolute_affine = Geom::identity(); //Initialize the scaler
937     if (state & GDK_MOD1_MASK) { // scale by an integer multiplier/divider
938         // We're scaling either the visual or the geometric bbox here (see the comment above)
939         for ( unsigned int i = 0 ; i < 2 ; i++ ) {
940             if (fabs(default_scale[i]) > 1) {
941                 default_scale[i] = round(default_scale[i]);
942             } else if (default_scale[i] != 0) {
943                 default_scale[i] = 1/round(1/(MIN(default_scale[i], 10)));
944             }
945         }
946         // Update the knot position
947         pt = _calcAbsAffineDefault(default_scale);
948         // When scaling by an integer, snapping is not needed
949     } else {
950         // In all other cases we should try to snap now
951         SnapManager &m = _desktop->namedview->snap_manager;
952         m.setup(_desktop, false, _items_const);
954         Inkscape::SnappedPoint bb, sn;
955         Geom::Coord bd(NR_HUGE);
956         Geom::Coord sd(NR_HUGE);
958         if ((state & GDK_CONTROL_MASK) || _desktop->isToolboxButtonActive ("lock")) {
959             // Scale is locked to a 1:1 aspect ratio, so that s[X] must be made to equal s[Y].
960             //
961             // The aspect-ratio must be locked before snapping
962             if (fabs(default_scale[Geom::X]) > fabs(default_scale[Geom::Y])) {
963                 default_scale[Geom::X] = fabs(default_scale[Geom::Y]) * sign(default_scale[Geom::X]);
964                 geom_scale[Geom::X] = fabs(geom_scale[Geom::Y]) * sign(geom_scale[Geom::X]);
965             } else {
966                 default_scale[Geom::Y] = fabs(default_scale[Geom::X]) * sign(default_scale[Geom::Y]);
967                 geom_scale[Geom::Y] = fabs(geom_scale[Geom::X]) * sign(geom_scale[Geom::Y]);
968             }
970             // Snap along a suitable constraint vector from the origin.
971             bb = m.constrainedSnapScale(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, default_scale, _origin_for_bboxpoints);
972             sn = m.constrainedSnapScale(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, geom_scale, _origin_for_specpoints);
974             /* Choose the smaller difference in scale.  Since s[X] == s[Y] we can
975             ** just compare difference in s[X].
976             */
977             bd = bb.getSnapped() ? fabs(bb.getTransformation()[Geom::X] - default_scale[Geom::X]) : NR_HUGE;
978             sd = sn.getSnapped() ? fabs(sn.getTransformation()[Geom::X] - geom_scale[Geom::X]) : NR_HUGE;
979         } else {
980             /* Scale aspect ratio is unlocked */
981             bb = m.freeSnapScale(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, default_scale, _origin_for_bboxpoints);
982             sn = m.freeSnapScale(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, geom_scale, _origin_for_specpoints);
984             /* Pick the snap that puts us closest to the original scale */
985             bd = bb.getSnapped() ? fabs(Geom::L2(bb.getTransformation()) - Geom::L2(Geom::Point(default_scale[Geom::X], default_scale[Geom::Y]))) : NR_HUGE;
986             sd = sn.getSnapped() ? fabs(Geom::L2(sn.getTransformation()) - Geom::L2(Geom::Point(geom_scale[Geom::X], geom_scale[Geom::Y]))) : NR_HUGE;
987         }
989         if (!(bb.getSnapped() || sn.getSnapped())) {
990             // We didn't snap at all! Don't update the handle position, just calculate the new transformation
991             _calcAbsAffineDefault(default_scale);
992             _desktop->snapindicator->remove_snaptarget();
993         } else if (bd < sd) {
994             // We snapped the bbox (which is either visual or geometric)
995             _desktop->snapindicator->set_new_snaptarget(bb);
996             default_scale = Geom::Scale(bb.getTransformation());
997             // Calculate the new transformation and update the handle position
998             pt = _calcAbsAffineDefault(default_scale);
999         } else {
1000             _desktop->snapindicator->set_new_snaptarget(sn);
1001             // We snapped the special points (e.g. nodes), which are not at the visual bbox
1002             // The handle location however (pt) might however be at the visual bbox, so we
1003             // will have to calculate pt taking the stroke width into account
1004             geom_scale = Geom::Scale(sn.getTransformation());
1005             pt = _calcAbsAffineGeom(geom_scale);
1006         }
1007     }
1009     /* Status text */
1010     _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1011                           _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1012                           100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1014     return TRUE;
1017 gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1019     Geom::Dim2 axis, perp;
1020     switch (handle.cursor) {
1021         case GDK_TOP_SIDE:
1022         case GDK_BOTTOM_SIDE:
1023             axis = Geom::Y;
1024             perp = Geom::X;
1025             break;
1026         case GDK_LEFT_SIDE:
1027         case GDK_RIGHT_SIDE:
1028             axis = Geom::X;
1029             perp = Geom::Y;
1030             break;
1031         default:
1032             g_assert_not_reached();
1033             return TRUE;
1034     };
1036     // Calculate the scale factors, which can be either visual or geometric
1037     // depending on which type of bbox is currently being used (see preferences -> selector tool)
1038     Geom::Scale default_scale = calcScaleFactors(_point, pt, _origin);
1039     default_scale[perp] = 1;
1041     // Find the scale factors for the geometric bbox
1042     Geom::Point pt_geom = _getGeomHandlePos(pt);
1043     Geom::Scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
1044     geom_scale[perp] = 1;
1046     _absolute_affine = Geom::identity(); //Initialize the scaler
1048     if (state & GDK_MOD1_MASK) { // stretch by an integer multiplier/divider
1049         if (fabs(default_scale[axis]) > 1) {
1050             default_scale[axis] = round(default_scale[axis]);
1051         } else if (default_scale[axis] != 0) {
1052             default_scale[axis] = 1/round(1/(MIN(default_scale[axis], 10)));
1053         }
1054         // Calculate the new transformation and update the handle position
1055         pt = _calcAbsAffineDefault(default_scale);
1056         // When stretching by an integer, snapping is not needed
1057     } else {
1058         // In all other cases we should try to snap now
1060         SnapManager &m = _desktop->namedview->snap_manager;
1061         m.setup(_desktop, false, _items_const);
1063         Inkscape::SnappedPoint bb, sn;
1064         g_assert(bb.getSnapped() == false); // Check initialization to catch any regression
1065         Geom::Coord bd(NR_HUGE);
1066         Geom::Coord sd(NR_HUGE);
1068         bool symmetrical = state & GDK_CONTROL_MASK;
1070         bb = m.constrainedSnapStretch(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, Geom::Coord(default_scale[axis]), _origin_for_bboxpoints, Geom::Dim2(axis), symmetrical);
1071         sn = m.constrainedSnapStretch(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, Geom::Coord(geom_scale[axis]), _origin_for_specpoints, Geom::Dim2(axis), symmetrical);
1073         if (bb.getSnapped()) {
1074             // We snapped the bbox (which is either visual or geometric)
1075             bd = fabs(bb.getTransformation()[axis] - default_scale[axis]);
1076             default_scale[axis] = bb.getTransformation()[axis];
1077         }
1079         if (sn.getSnapped()) {
1080             sd = fabs(sn.getTransformation()[axis] - geom_scale[axis]);
1081             geom_scale[axis] = sn.getTransformation()[axis];
1082         }
1084         if (symmetrical) {
1085             // on ctrl, apply symmetrical scaling instead of stretching
1086             // Preserve aspect ratio, but never flip in the dimension not being edited (by using fabs())
1087             default_scale[perp] = fabs(default_scale[axis]);
1088             geom_scale[perp] = fabs(geom_scale[axis]);
1089         }
1091         if (!(bb.getSnapped() || sn.getSnapped())) {
1092             // We didn't snap at all! Don't update the handle position, just calculate the new transformation
1093             _calcAbsAffineDefault(default_scale);
1094             _desktop->snapindicator->remove_snaptarget();
1095         } else if (bd < sd) {
1096             _desktop->snapindicator->set_new_snaptarget(bb);
1097             // Calculate the new transformation and update the handle position
1098             pt = _calcAbsAffineDefault(default_scale);
1099         } else {
1100             _desktop->snapindicator->set_new_snaptarget(sn);
1101             // We snapped the special points (e.g. nodes), which are not at the visual bbox
1102             // The handle location however (pt) might however be at the visual bbox, so we
1103             // will have to calculate pt taking the stroke width into account
1104             pt = _calcAbsAffineGeom(geom_scale);
1105         }
1106     }
1108     // status text
1109     _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1110                           _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1111                           100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1113     return TRUE;
1116 gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1118     /* When skewing (or rotating):
1119      * 1) the stroke width will not change. This makes life much easier because we don't have to
1120      *    account for that (like for scaling or stretching). As a consequence, all points will
1121      *    have the same origin for the transformation and for the snapping.
1122      * 2) When holding shift, the transformation will be relative to the point opposite of
1123      *    the handle; otherwise it will be relative to the center as set for the selection
1124      */
1126     Geom::Dim2 dim_a;
1127     Geom::Dim2 dim_b;
1129     switch (handle.cursor) {
1130         case GDK_SB_H_DOUBLE_ARROW:
1131             dim_a = Geom::Y;
1132             dim_b = Geom::X;
1133             break;
1134         case GDK_SB_V_DOUBLE_ARROW:
1135             dim_a = Geom::X;
1136             dim_b = Geom::Y;
1137             break;
1138         default:
1139             g_assert_not_reached();
1140             abort();
1141             break;
1142     }
1144     Geom::Point const initial_delta = _point - _origin;
1146     if (fabs(initial_delta[dim_a]) < 1e-15) {
1147         return false;
1148     }
1150     // Calculate the scale factors, which can be either visual or geometric
1151     // depending on which type of bbox is currently being used (see preferences -> selector tool)
1152     Geom::Scale scale = calcScaleFactors(_point, pt, _origin, false);
1153     Geom::Scale skew = calcScaleFactors(_point, pt, _origin, true);
1154     scale[dim_b] = 1;
1155     skew[dim_b] = 1;
1157     if (fabs(scale[dim_a]) < 1) {
1158         // Prevent shrinking of the selected object, while allowing mirroring
1159         scale[dim_a] = sign(scale[dim_a]);
1160     } else {
1161         // Allow expanding of the selected object by integer multiples
1162         scale[dim_a] = floor(scale[dim_a] + 0.5);
1163     }
1165     double radians = atan(skew[dim_a] / scale[dim_a]);
1167     if (state & GDK_CONTROL_MASK) {
1168         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1169         // Snap to defined angle increments
1170         int snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12);
1171         if (snaps) {
1172             double sections = floor(radians * snaps / M_PI + .5);
1173             if (fabs(sections) >= snaps / 2) {
1174                 sections = sign(sections) * (snaps / 2 - 1);
1175             }
1176             radians = (M_PI / snaps) * sections;
1177         }
1178         skew[dim_a] = tan(radians) * scale[dim_a];
1179     } else {
1180         // Snap to objects, grids, guides
1182         SnapManager &m = _desktop->namedview->snap_manager;
1183         m.setup(_desktop, false, _items_const);
1185         Inkscape::Snapper::ConstraintLine const constraint(component_vectors[dim_b]);
1186         // When skewing, we cannot snap the corners of the bounding box, see the comment in "constrainedSnapSkew" for details
1187         Geom::Point const s(skew[dim_a], scale[dim_a]);
1188         Inkscape::SnappedPoint sn = m.constrainedSnapSkew(Inkscape::SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, constraint, s, _origin, Geom::Dim2(dim_b));
1190         if (sn.getSnapped()) {
1191             // We snapped something, so change the skew to reflect it
1192             Geom::Coord const sd = sn.getSnapped() ? sn.getTransformation()[0] : NR_HUGE;
1193              _desktop->snapindicator->set_new_snaptarget(sn);
1194             skew[dim_a] = sd;
1195         } else {
1196             _desktop->snapindicator->remove_snaptarget();
1197         }
1198     }
1200     // Update the handle position
1201     pt[dim_b] = initial_delta[dim_a] * skew[dim_a] + _point[dim_b];
1202     pt[dim_a] = initial_delta[dim_a] * scale[dim_a] + _origin[dim_a];
1204     // Calculate the relative affine
1205     _relative_affine = Geom::identity();
1206     _relative_affine[2*dim_a + dim_a] = (pt[dim_a] - _origin[dim_a]) / initial_delta[dim_a];
1207     _relative_affine[2*dim_a + (dim_b)] = (pt[dim_b] - _point[dim_b]) / initial_delta[dim_a];
1208     _relative_affine[2*(dim_b) + (dim_a)] = 0;
1209     _relative_affine[2*(dim_b) + (dim_b)] = 1;
1211     for (int i = 0; i < 2; i++) {
1212         if (fabs(_relative_affine[3*i]) < 1e-15) {
1213             _relative_affine[3*i] = 1e-15;
1214         }
1215     }
1217     // Update the status text
1218     double degrees = mod360symm(Geom::rad_to_deg(radians));
1219     _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1220                           // TRANSLATORS: don't modify the first ";"
1221                           // (it will NOT be displayed as ";" - only the second one will be)
1222                           _("<b>Skew</b>: %0.2f&#176;; with <b>Ctrl</b> to snap angle"),
1223                           degrees);
1225     return TRUE;
1228 gboolean Inkscape::SelTrans::rotateRequest(Geom::Point &pt, guint state)
1230     /* When rotating (or skewing):
1231      * 1) the stroke width will not change. This makes life much easier because we don't have to
1232      *    account for that (like for scaling or stretching). As a consequence, all points will
1233      *    have the same origin for the transformation and for the snapping.
1234      * 2) When holding shift, the transformation will be relative to the point opposite of
1235      *    the handle; otherwise it will be relative to the center as set for the selection
1236      */
1238     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1239     int snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12);
1241     // rotate affine in rotate
1242     Geom::Point const d1 = _point - _origin;
1243     Geom::Point const d2 = pt     - _origin;
1245     Geom::Coord const h1 = Geom::L2(d1); // initial radius
1246     if (h1 < 1e-15) return FALSE;
1247     Geom::Point q1 = d1 / h1; // normalized initial vector to handle
1248     Geom::Coord const h2 = Geom::L2(d2); // new radius
1249     if (fabs(h2) < 1e-15) return FALSE;
1250     Geom::Point q2 = d2 / h2; // normalized new vector to handle
1252     double radians;
1253     if (state & GDK_CONTROL_MASK) {
1254         // Snap to defined angle increments
1255         double cos_t = Geom::dot(q1, q2);
1256         double sin_t = Geom::dot(Geom::rot90(q1), q2);
1257         radians = atan2(sin_t, cos_t);
1258         if (snaps) {
1259             radians = ( M_PI / snaps ) * floor( radians * snaps / M_PI + .5 );
1260         }
1261         q1 = Geom::Point(1, 0);
1262         q2 = Geom::Point(cos(radians), sin(radians));
1263     } else {
1264         radians = atan2(Geom::dot(Geom::rot90(d1), d2),
1265                         Geom::dot(d1, d2));
1266     }
1268     Geom::Rotate const r1(q1);
1269     Geom::Rotate const r2(q2);
1271     // Calculate the relative affine
1272     _relative_affine = r2 * r1.inverse();
1274     // Update the handle position
1275     pt = _point * Geom::Translate(-_origin) * _relative_affine * Geom::Translate(_origin);
1277     // Update the status text
1278     double degrees = mod360symm(Geom::rad_to_deg(radians));
1279     _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1280                           // TRANSLATORS: don't modify the first ";"
1281                           // (it will NOT be displayed as ";" - only the second one will be)
1282                           _("<b>Rotate</b>: %0.2f&#176;; with <b>Ctrl</b> to snap angle"), degrees);
1284     return TRUE;
1287 gboolean Inkscape::SelTrans::centerRequest(Geom::Point &pt, guint state)
1289     SnapManager &m = _desktop->namedview->snap_manager;
1290     m.setup(_desktop);
1291     m.freeSnapReturnByRef(SnapPreferences::SNAPPOINT_NODE, pt);
1293     if (state & GDK_CONTROL_MASK) {
1294         if ( fabs(_point[Geom::X] - pt[Geom::X]) > fabs(_point[Geom::Y] - pt[Geom::Y]) ) {
1295             pt[Geom::Y] = _point[Geom::Y];
1296         } else {
1297             pt[Geom::X] = _point[Geom::X];
1298         }
1299     }
1301     if ( !(state & GDK_SHIFT_MASK) && _bbox ) {
1302         // screen pixels to snap center to bbox
1303 #define SNAP_DIST 5
1304         // FIXME: take from prefs
1305         double snap_dist = SNAP_DIST / _desktop->current_zoom();
1307         for (int i = 0; i < 2; i++) {
1308             if (fabs(pt[i] - _bbox->min()[i]) < snap_dist) {
1309                 pt[i] = _bbox->min()[i];
1310             }
1311             if (fabs(pt[i] - _bbox->midpoint()[i]) < snap_dist) {
1312                 pt[i] = _bbox->midpoint()[i];
1313             }
1314             if (fabs(pt[i] - _bbox->max()[i]) < snap_dist) {
1315                 pt[i] = _bbox->max()[i];
1316             }
1317         }
1318     }
1320     // status text
1321     GString *xs = SP_PX_TO_METRIC_STRING(pt[Geom::X], _desktop->namedview->getDefaultMetric());
1322     GString *ys = SP_PX_TO_METRIC_STRING(pt[Geom::Y], _desktop->namedview->getDefaultMetric());
1323     _message_context.setF(Inkscape::NORMAL_MESSAGE, _("Move <b>center</b> to %s, %s"), xs->str, ys->str);
1324     g_string_free(xs, FALSE);
1325     g_string_free(ys, FALSE);
1327     return TRUE;
1330 /*
1331  * handlers for handle movement
1332  *
1333  */
1335 void sp_sel_trans_stretch(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1337     seltrans->stretch(handle, pt, state);
1340 void sp_sel_trans_scale(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint state)
1342     seltrans->scale(pt, state);
1345 void sp_sel_trans_skew(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, Geom::Point &pt, guint state)
1347     seltrans->skew(handle, pt, state);
1350 void sp_sel_trans_rotate(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint state)
1352     seltrans->rotate(pt, state);
1355 void Inkscape::SelTrans::stretch(SPSelTransHandle const &/*handle*/, Geom::Point &/*pt*/, guint /*state*/)
1357     transform(_absolute_affine, Geom::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1360 void Inkscape::SelTrans::scale(Geom::Point &/*pt*/, guint /*state*/)
1362     transform(_absolute_affine, Geom::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1365 void Inkscape::SelTrans::skew(SPSelTransHandle const &/*handle*/, Geom::Point &/*pt*/, guint /*state*/)
1367     transform(_relative_affine, _origin);
1370 void Inkscape::SelTrans::rotate(Geom::Point &/*pt*/, guint /*state*/)
1372     transform(_relative_affine, _origin);
1375 void sp_sel_trans_center(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint /*state*/)
1377     seltrans->setCenter(pt);
1381 void Inkscape::SelTrans::moveTo(Geom::Point const &xy, guint state)
1383     SnapManager &m = _desktop->namedview->snap_manager;
1384     m.setup(_desktop, true, _items_const);
1386     /* The amount that we've moved by during this drag */
1387     Geom::Point dxy = xy - _point;
1389     bool const alt = (state & GDK_MOD1_MASK);
1390     bool const control = (state & GDK_CONTROL_MASK);
1391     bool const shift = (state & GDK_SHIFT_MASK);
1393     if (alt) {
1395         /* Alt pressed means keep offset: snap the moved distance to the grid.
1396         ** FIXME: this will snap to more than just the grid, nowadays.
1397         */
1399         m.freeSnapReturnByRef(SnapPreferences::SNAPPOINT_NODE, dxy);
1401     } else if (!shift) {
1403         /* We're snapping to things, possibly with a constraint to horizontal or
1404         ** vertical movement.  Obtain a list of possible translations and then
1405         ** pick the smallest.
1406         */
1408         /* This will be our list of possible translations */
1409         std::list<Inkscape::SnappedPoint> s;
1411         if (control) {
1413             /* Snap to things, and also constrain to horizontal or vertical movement */
1415             for (unsigned int dim = 0; dim < 2; dim++) {
1416                 // When doing a constrained translation, all points will move in the same direction, i.e.
1417                 // either horizontally or vertically. Therefore we only have to specify the direction of
1418                 // the constraint-line once. The constraint lines are parallel, but might not be colinear.
1419                 // Therefore we will have to set the point through which the constraint-line runs
1420                 // individually for each point to be snapped; this will be handled however by _snapTransformed()
1421                 s.push_back(m.constrainedSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_BBOX,
1422                                                          _bbox_points,
1423                                                          _point, 
1424                                                          Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1425                                                          dxy));
1427                 s.push_back(m.constrainedSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_NODE,
1428                                                          _snap_points,
1429                                                          _point, 
1430                                                          Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1431                                                          dxy));
1432             }
1434         } else {
1436             // Let's leave this timer code here for a while. I'll probably need it in the near future (Diederik van Lierop)
1437             /* GTimeVal starttime;
1438             GTimeVal endtime;
1439                 g_get_current_time(&starttime); */
1441             /* Snap to things with no constraint */
1442                         s.push_back(m.freeSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, dxy));
1443                 s.push_back(m.freeSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, dxy));
1445                 /*g_get_current_time(&endtime);
1446                 double elapsed = ((((double)endtime.tv_sec - starttime.tv_sec) * G_USEC_PER_SEC + (endtime.tv_usec - starttime.tv_usec))) / 1000.0;
1447                 std::cout << "Time spent snapping: " << elapsed << std::endl; */
1448         }
1450         /* Pick one */
1451         Inkscape::SnappedPoint best_snapped_point;
1452         for (std::list<Inkscape::SnappedPoint>::const_iterator i = s.begin(); i != s.end(); i++) {
1453             if (i->getSnapped()) {
1454                 if (best_snapped_point.isOtherSnapBetter(*i, true)) {
1455                     best_snapped_point = *i;
1456                     dxy = i->getTransformation();
1457                 }
1458             }
1459         }
1460         if (best_snapped_point.getSnapped()) {
1461             _desktop->snapindicator->set_new_snaptarget(best_snapped_point);
1462         } else {
1463             // We didn't snap, so remove any previous snap indicator 
1464             _desktop->snapindicator->remove_snaptarget();            
1465             if (control) {
1466                 // If we didn't snap, then we should still constrain horizontally or vertically
1467                 // (When we did snap, then this constraint has already been enforced by
1468                 // calling constrainedSnapTranslation() above)
1469                 if (fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y])) {
1470                     dxy[Geom::Y] = 0;
1471                 } else {
1472                     dxy[Geom::X] = 0;
1473                 }
1474             }
1475         }
1476     }
1477     
1478     Geom::Matrix const move((Geom::Translate(dxy)));
1479     Geom::Point const norm(0, 0);
1480     transform(move, norm);
1482     // status text
1483     GString *xs = SP_PX_TO_METRIC_STRING(dxy[Geom::X], _desktop->namedview->getDefaultMetric());
1484     GString *ys = SP_PX_TO_METRIC_STRING(dxy[Geom::Y], _desktop->namedview->getDefaultMetric());
1485     _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);
1486     g_string_free(xs, TRUE);
1487     g_string_free(ys, TRUE);
1490 // Given a location of a handle at the visual bounding box, find the corresponding location at the
1491 // geometrical bounding box
1492 Geom::Point Inkscape::SelTrans::_getGeomHandlePos(Geom::Point const &visual_handle_pos)
1494     if ( _snap_bbox_type == SPItem::GEOMETRIC_BBOX) {
1495         // When the selector tool is using geometric bboxes, then the handle is already
1496         // located at one of the geometric bbox corners
1497         return visual_handle_pos;
1498     }
1500     if (!_geometric_bbox) {
1501         //_getGeomHandlePos() can only be used after _geometric_bbox has been defined!
1502         return visual_handle_pos;
1503     }
1505     // Using the Geom::Rect constructor below ensures that "min() < max()", which is important
1506     // because this will also hold for _bbox, and which is required for get_scale_transform_with_stroke()
1507     Geom::Rect new_bbox = Geom::Rect(_origin_for_bboxpoints, visual_handle_pos); // new visual bounding box
1508     // Please note that the new_bbox might in fact be just a single line, for example when stretching (in
1509     // which case the handle and origin will be aligned vertically or horizontally)
1510     Geom::Point normalized_handle_pos = (visual_handle_pos - new_bbox.min()) * Geom::Scale(new_bbox.dimensions()).inverse();
1512     // Calculate the absolute affine while taking into account the scaling of the stroke width
1513     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1514     bool transform_stroke = prefs->getBool("/options/transform/stroke", true);
1515     Geom::Matrix abs_affine = get_scale_transform_with_stroke (*_bbox, _strokewidth, transform_stroke,
1516                     new_bbox.min()[Geom::X], new_bbox.min()[Geom::Y], new_bbox.max()[Geom::X], new_bbox.max()[Geom::Y]);
1518     // Calculate the scaled geometrical bbox
1519     Geom::Rect new_geom_bbox = Geom::Rect(_geometric_bbox->min() * abs_affine, _geometric_bbox->max() * abs_affine);
1520     // Find the location of the handle on this new geometrical bbox
1521     return normalized_handle_pos * Geom::Scale(new_geom_bbox.dimensions()) + new_geom_bbox.min(); //new position of the geometric handle
1524 Geom::Scale Inkscape::calcScaleFactors(Geom::Point const &initial_point, Geom::Point const &new_point, Geom::Point const &origin, bool const skew)
1526     // Work out the new scale factors for the bbox
1528     Geom::Point const initial_delta = initial_point - origin;
1529     Geom::Point const new_delta = new_point - origin;
1530     Geom::Point const offset = new_point - initial_point;
1531     Geom::Scale scale(1, 1);
1533     for ( unsigned int i = 0 ; i < 2 ; i++ ) {
1534         if ( fabs(initial_delta[i]) > 1e-6 ) {
1535             if (skew) {
1536                 scale[i] = offset[1-i] / initial_delta[i];
1537             } else {
1538                 scale[i] = new_delta[i] / initial_delta[i];
1539             }
1540         }
1541     }
1543     return scale;
1546 // Only for scaling/stretching
1547 Geom::Point Inkscape::SelTrans::_calcAbsAffineDefault(Geom::Scale const default_scale)
1549     Geom::Matrix abs_affine = Geom::Translate(-_origin) * Geom::Matrix(default_scale) * Geom::Translate(_origin);
1550     Geom::Point new_bbox_min = _approximate_bbox->min() * abs_affine;
1551     Geom::Point new_bbox_max = _approximate_bbox->max() * abs_affine;
1553     bool transform_stroke = false;
1554     gdouble strokewidth = 0;
1556     if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
1557         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1558         transform_stroke = prefs->getBool("/options/transform/stroke", true);
1559         strokewidth = _strokewidth;
1560     }
1562     _absolute_affine = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
1563                     new_bbox_min[Geom::X], new_bbox_min[Geom::Y], new_bbox_max[Geom::X], new_bbox_max[Geom::Y]);
1565     // return the new handle position
1566     return ( _point - _origin ) * default_scale + _origin;
1569 // Only for scaling/stretching
1570 Geom::Point Inkscape::SelTrans::_calcAbsAffineGeom(Geom::Scale const geom_scale)
1572     _relative_affine = Geom::Matrix(geom_scale);
1573     _absolute_affine = Geom::Translate(-_origin_for_specpoints) * _relative_affine * Geom::Translate(_origin_for_specpoints);
1575     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1576     bool const transform_stroke = prefs->getBool("/options/transform/stroke", true);
1577     Geom::Rect visual_bbox = get_visual_bbox(_geometric_bbox, _absolute_affine, _strokewidth, transform_stroke);
1579     // return the new handle position
1580     return visual_bbox.min() + visual_bbox.dimensions() * Geom::Scale(_handle_x, _handle_y);
1583 void Inkscape::SelTrans::_keepClosestPointOnly(std::vector<Geom::Point> &points, const Geom::Point &reference)
1585         if (points.size() < 2) return;
1586         
1587         Geom::Point closest_point = Geom::Point(NR_HUGE, NR_HUGE);
1588         Geom::Coord closest_dist = NR_HUGE;
1589         
1590         for(std::vector<Geom::Point>::const_iterator i = points.begin(); i != points.end(); i++) {
1591                 Geom::Coord dist = Geom::L2(*i - reference);
1592                 if (i == points.begin() || dist < closest_dist) {
1593                         closest_point = *i;
1594                         closest_dist = dist;                    
1595                 }
1596     }
1597         
1598         points.clear();
1599         points.push_back(closest_point);        
1602 /*
1603   Local Variables:
1604   mode:c++
1605   c-file-style:"stroustrup"
1606   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1607   indent-tabs-mode:nil
1608   fill-column:99
1609   End:
1610 */
1611 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :