Code

82632d45693b65d416534dc79f7f545a6a8f2080
[inkscape.git] / src / seltrans.cpp
1 #define __SELTRANS_C__
3 /*
4  * Helper object for transforming selected items
5  *
6  * Author:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   bulia byak <buliabyak@users.sf.net>
9  *   Carl Hetherington <inkscape@carlh.net>
10  *
11  * Copyright (C) 1999-2002 Lauris Kaplinski
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
20 #include <libnr/nr-matrix-ops.h>
21 #include <libnr/nr-matrix-translate-ops.h>
22 #include <libnr/nr-rotate-ops.h>
23 #include <libnr/nr-scale-ops.h>
24 #include <libnr/nr-translate-matrix-ops.h>
25 #include <libnr/nr-translate-ops.h>
26 #include <gdk/gdkkeysyms.h>
27 #include "document.h"
28 #include "sp-namedview.h"
29 #include "desktop.h"
30 #include "desktop-handles.h"
31 #include "desktop-style.h"
32 #include "knot.h"
33 #include "snap.h"
34 #include "selection.h"
35 #include "select-context.h"
36 #include "sp-item.h"
37 #include "sp-item-transform.h"
38 #include "seltrans-handles.h"
39 #include "seltrans.h"
40 #include "selection-chemistry.h"
41 #include "sp-metrics.h"
42 #include "verbs.h"
43 #include <glibmm/i18n.h>
44 #include "display/sp-ctrlline.h"
45 #include "prefs-utils.h"
46 #include "xml/repr.h"
48 #include "isnan.h" //temp fix.  make sure included last
50 static void sp_remove_handles(SPKnot *knot[], gint num);
52 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data);
53 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint state, gpointer data);
54 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data);
55 static void sp_sel_trans_handle_new_event(SPKnot *knot, NR::Point *position, guint32 state, gpointer data);
56 static gboolean sp_sel_trans_handle_request(SPKnot *knot, NR::Point *p, guint state, gboolean *data);
58 extern GdkPixbuf *handles[];
60 static gboolean sp_seltrans_handle_event(SPKnot *knot, GdkEvent *event, gpointer)
61 {
62     switch (event->type) {
63         case GDK_MOTION_NOTIFY:
64             break;
65         case GDK_KEY_PRESS:
66             if (get_group0_keyval (&event->key) == GDK_space) {
67                 /* stamping mode: both mode(show content and outline) operation with knot */
68                 if (!SP_KNOT_IS_GRABBED(knot)) {
69                     return FALSE;
70                 }
71                 SPDesktop *desktop = knot->desktop;
72                 Inkscape::SelTrans *seltrans = SP_SELECT_CONTEXT(desktop->event_context)->_seltrans;
73                 seltrans->stamp();
74                 return TRUE;
75             }
76             break;
77         default:
78             break;
79     }
81     return FALSE;
82 }
84 Inkscape::SelTrans::SelTrans(SPDesktop *desktop) :
85     _desktop(desktop),
86     _selcue(desktop),
87     _state(STATE_SCALE),
88     _show(SHOW_CONTENT),
89     _grabbed(false),
90     _show_handles(true),
91     _bbox(NR::Nothing()),
92     _approximate_bbox(NR::Nothing()),
93     _chandle(NULL),
94     _stamp_cache(NULL),
95     _message_context(desktop->messageStack())
96 {
97     gchar const *prefs_bbox = prefs_get_string_attribute("tools.select", "bounding_box");
98     _snap_bbox_type = (prefs_bbox != NULL && strcmp(prefs_bbox, "geometric")==0)? SPItem::GEOMETRIC_BBOX : SPItem::APPROXIMATE_BBOX;
99     
100     g_return_if_fail(desktop != NULL);
102     for (int i = 0; i < 8; i++) {
103         _shandle[i] = NULL;
104         _rhandle[i] = NULL;
105     }
107     _updateVolatileState();
108     _current.set_identity();
110     _center_is_set = false; // reread _center from items, or set to bbox midpoint
112     _updateHandles();
114     _selection = sp_desktop_selection(desktop);
116     _norm = sp_canvas_item_new(sp_desktop_controls(desktop),
117                                SP_TYPE_CTRL,
118                                "anchor", GTK_ANCHOR_CENTER,
119                                "mode", SP_CTRL_MODE_COLOR,
120                                "shape", SP_CTRL_SHAPE_BITMAP,
121                                "size", 13.0,
122                                "filled", TRUE,
123                                "fill_color", 0x00000000,
124                                "stroked", TRUE,
125                                "stroke_color", 0x000000a0,
126                                "pixbuf", handles[12],
127                                NULL);
129     _grip = sp_canvas_item_new(sp_desktop_controls(desktop),
130                                SP_TYPE_CTRL,
131                                "anchor", GTK_ANCHOR_CENTER,
132                                "mode", SP_CTRL_MODE_XOR,
133                                "shape", SP_CTRL_SHAPE_CROSS,
134                                "size", 7.0,
135                                "filled", TRUE,
136                                "fill_color", 0xffffff7f,
137                                "stroked", TRUE,
138                                "stroke_color", 0xffffffff,
139                                "pixbuf", handles[12],
140                                NULL);
142     sp_canvas_item_hide(_grip);
143     sp_canvas_item_hide(_norm);
145     for (int i = 0; i < 4; i++) {
146         _l[i] = sp_canvas_item_new(sp_desktop_controls(desktop), SP_TYPE_CTRLLINE, NULL);
147         sp_canvas_item_hide(_l[i]);
148     }
150     _sel_changed_connection = _selection->connectChanged(
151         sigc::mem_fun(*this, &Inkscape::SelTrans::_selChanged)
152         );
154     _sel_modified_connection = _selection->connectModified(
155         sigc::mem_fun(*this, &Inkscape::SelTrans::_selModified)
156         );
159 Inkscape::SelTrans::~SelTrans()
161     _sel_changed_connection.disconnect();
162     _sel_modified_connection.disconnect();
164     for (unsigned int i = 0; i < 8; i++) {
165         if (_shandle[i]) {
166             g_object_unref(G_OBJECT(_shandle[i]));
167             _shandle[i] = NULL;
168         }
169         if (_rhandle[i]) {
170             g_object_unref(G_OBJECT(_rhandle[i]));
171             _rhandle[i] = NULL;
172         }
173     }
174     if (_chandle) {
175         g_object_unref(G_OBJECT(_chandle));
176         _chandle = NULL;
177     }
179     if (_norm) {
180         gtk_object_destroy(GTK_OBJECT(_norm));
181         _norm = NULL;
182     }
183     if (_grip) {
184         gtk_object_destroy(GTK_OBJECT(_grip));
185         _grip = NULL;
186     }
187     for (int i = 0; i < 4; i++) {
188         if (_l[i]) {
189             gtk_object_destroy(GTK_OBJECT(_l[i]));
190             _l[i] = NULL;
191         }
192     }
194     for (unsigned i = 0; i < _items.size(); i++) {
195         sp_object_unref(SP_OBJECT(_items[i].first), NULL);
196     }
198     _items.clear();
199     _items_centers.clear();
202 void Inkscape::SelTrans::resetState()
204     _state = STATE_SCALE;
207 void Inkscape::SelTrans::increaseState()
209     if (_state == STATE_SCALE) {
210         _state = STATE_ROTATE;
211     } else {
212         _state = STATE_SCALE;
213     }
215     _center_is_set = true; // no need to reread center
217     _updateHandles();
220 void Inkscape::SelTrans::setCenter(NR::Point const &p)
222     _center = p;
223     _center_is_set = true;
225     // Write the new center position into all selected items
226     for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
227         SPItem *it = (SPItem*)SP_OBJECT(l->data);
228         it->setCenter(p);
229         // only set the value; updating repr and document_done will be done once, on ungrab
230     }
232     _updateHandles();
235 void Inkscape::SelTrans::grab(NR::Point const &p, gdouble x, gdouble y, bool show_handles)
237     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
239     g_return_if_fail(!_grabbed);
241     _grabbed = true;
242     _show_handles = show_handles;
243     _updateVolatileState();
244     _current.set_identity();
246     _changed = false;
248     if (_empty) {
249         return;
250     }
252     for (GSList const *l = selection->itemList(); l; l = l->next) {
253         SPItem *it = (SPItem*)sp_object_ref(SP_OBJECT(l->data), NULL);
254         _items.push_back(std::pair<SPItem *, NR::Matrix>(it, sp_item_i2d_affine(it)));
255         _items_centers.push_back(std::pair<SPItem *, NR::Point>(it, it->getCenter())); // for content-dragging, we need to remember original centers
256     }
258     _current.set_identity();
260     _point = p;
261     
262     // The selector tool should snap the bbox and the special snappoints, but not path nodes
263     // (The special points are the handles, center, rotation axis, font baseline, ends of spiral, etc.)
265     // First, determine the bounding box for snapping ...
266     _bbox = selection->bounds(_snap_bbox_type);    
267     _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX); // Used for correctly scaling the strokewidth
270     // Next, get all special points for snapping
271     _snap_points = selection->getSnapPoints(); // Excludes path nodes
272     std::vector<NR::Point> snap_points_hull = selection->getSnapPointsConvexHull(); // Includes path nodes
273     if (_snap_points.size() > 100) {
274         /* Snapping a huge number of nodes will take way too long, so limit the number of snappable nodes
275         An average user would rarely ever try to snap such a large number of nodes anyway, because 
276         (s)he could hardly discern which node would be snapping */
277         _snap_points = snap_points_hull;
278         // Unfortunately, by now we will have lost the font-baseline snappoints :-(
279     }
280     
281     // Find bbox hulling all special points, which excludes stroke width. Here we need to include the
282     // path nodes, for example because a rectangle which has been converted to a path doesn't have 
283     // any other special points
284     NR::Rect snap_points_bbox;
285     if ( snap_points_hull.empty() == false ) {
286         std::vector<NR::Point>::iterator i = snap_points_hull.begin();
287         snap_points_bbox = NR::Rect(*i, *i);
288         i++;
289         while (i != snap_points_hull.end()) {
290             snap_points_bbox.expandTo(*i);
291             i++;
292         }
293     }
294     
295     _bbox_points.clear();
296     if (_bbox) {
297         // ... and add the bbox corners to _bbox_points
298         for ( unsigned i = 0 ; i < 4 ; i++ ) {
299             _bbox_points.push_back(_bbox->corner(i));
300         }
301         // There are two separate "opposites" (i.e. opposite w.r.t. the handle being dragged):
302         //  - one for snapping the boundingbox, which can be either visual or geometric
303         //  - one for snapping the special points
304         // The "opposite" in case of a geometric boundingbox always coincides with the "opposite" for the special points
305         // These distinct "opposites" are needed in the snapmanager to avoid bugs such as #1540195 (in which 
306         // a box is caught between to guides)
307         _opposite_for_bboxpoints = _bbox->min() + _bbox->dimensions() * NR::scale(1-x, 1-y);
308         _opposite_for_specpoints = (snap_points_bbox.min() + (snap_points_bbox.dimensions() * NR::scale(1-x, 1-y) ) );
309         // Only a single "opposite" can be used in calculating transformations.
310         _opposite = _opposite_for_bboxpoints;
311     }
312     
313     /*std::cout << "Number of snap points:  " << _snap_points.size() << std::endl;
314     for (std::vector<NR::Point>::const_iterator i = _snap_points.begin(); i != _snap_points.end(); i++)
315     {
316         std::cout << "    " << *i << std::endl;
317     }
318     
319     std::cout << "Number of bbox points:  " << _bbox_points.size() << std::endl;
320     for (std::vector<NR::Point>::const_iterator i = _bbox_points.begin(); i != _bbox_points.end(); i++)
321     {
322         std::cout << "    " << *i << std::endl;
323     }*/
324     
325     if ((x != -1) && (y != -1)) {
326         sp_canvas_item_show(_norm);
327         sp_canvas_item_show(_grip);
328     }
330     if (_show == SHOW_OUTLINE) {
331         for (int i = 0; i < 4; i++)
332             sp_canvas_item_show(_l[i]);
333     }
335     _updateHandles();
336     g_return_if_fail(_stamp_cache == NULL);
339 void Inkscape::SelTrans::transform(NR::Matrix const &rel_affine, NR::Point const &norm)
341     g_return_if_fail(_grabbed);
342     g_return_if_fail(!_empty);
344     NR::Matrix const affine( NR::translate(-norm) * rel_affine * NR::translate(norm) );
346     if (_show == SHOW_CONTENT) {
347         // update the content
348         for (unsigned i = 0; i < _items.size(); i++) {
349             SPItem &item = *_items[i].first;
350             NR::Matrix const &prev_transform = _items[i].second;
351             sp_item_set_i2d_affine(&item, prev_transform * affine);
352         }
353     } else {
354         if (_bbox) {
355             NR::Point p[4];
356             /* update the outline */
357             for (unsigned i = 0 ; i < 4 ; i++) {
358                 p[i] = _bbox->corner(i) * affine;
359             }
360             for (unsigned i = 0 ; i < 4 ; i++) {
361                 sp_ctrlline_set_coords(SP_CTRLLINE(_l[i]), p[i], p[(i+1)%4]);
362             }
363         }
364     }
366     _current = affine;
367     _changed = true;
368     _updateHandles();
371 void Inkscape::SelTrans::ungrab()
373     g_return_if_fail(_grabbed);
374     _grabbed = false;
375     _show_handles = true;
377     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
378     _updateVolatileState();
380     for (unsigned i = 0; i < _items.size(); i++) {
381         sp_object_unref(SP_OBJECT(_items[i].first), NULL);
382     }
384     sp_canvas_item_hide(_norm);
385     sp_canvas_item_hide(_grip);
387     if (_show == SHOW_OUTLINE) {
388         for (int i = 0; i < 4; i++)
389             sp_canvas_item_hide(_l[i]);
390     }
392     if (_stamp_cache) {
393         g_slist_free(_stamp_cache);
394         _stamp_cache = NULL;
395     }
397     _message_context.clear();
399     if (!_empty && _changed) {
400         sp_selection_apply_affine(selection, _current, (_show == SHOW_OUTLINE)? true : false);
401         if (_center) {
402             *_center *= _current;
403             _center_is_set = true;
404         }
406 // If dragging showed content live, sp_selection_apply_affine cannot change the centers
407 // appropriately - it does not know the original positions of the centers (all objects already have
408 // the new bboxes). So we need to reset the centers from our saved array.
409         if (_show != SHOW_OUTLINE && !_current.is_translation()) {
410             for (unsigned i = 0; i < _items_centers.size(); i++) {
411                 SPItem *currentItem = _items_centers[i].first;
412                 if (currentItem->isCenterSet()) { // only if it's already set
413                     currentItem->setCenter (_items_centers[i].second * _current);
414                     SP_OBJECT(currentItem)->updateRepr();
415                 }
416             }
417         }
419         _items.clear();
420         _items_centers.clear();
422         if (_current.is_translation()) {
423             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
424                              _("Move"));
425         } else if (_current.is_scale()) {
426             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
427                              _("Scale"));
428         } else if (_current.is_rotation()) {
429             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
430                              _("Rotate"));
431         } else {
432             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
433                              _("Skew"));
434         }
436     } else {
438         if (_center_is_set) {
439             // we were dragging center; update reprs and commit undoable action
440             for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
441                 SPItem *it = (SPItem*)SP_OBJECT(l->data);
442                 SP_OBJECT(it)->updateRepr();
443             }
444             sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
445                             _("Set center"));
446         }
448         _items.clear();
449         _items_centers.clear();
450         _updateHandles();
451     }
454 /* fixme: This is really bad, as we compare positions for each stamp (Lauris) */
455 /* fixme: IMHO the best way to keep sort cache would be to implement timestamping at last */
457 void Inkscape::SelTrans::stamp()
459     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
461     bool fixup = !_grabbed;
462     if ( fixup && _stamp_cache ) {
463         // TODO - give a proper fix. Simple temproary work-around for the grab() issue
464         g_slist_free(_stamp_cache);
465         _stamp_cache = NULL;
466     }
468     /* stamping mode */
469     if (!_empty) {
470         GSList *l;
471         if (_stamp_cache) {
472             l = _stamp_cache;
473         } else {
474             /* Build cache */
475             l  = g_slist_copy((GSList *) selection->itemList());
476             l  = g_slist_sort(l, (GCompareFunc) sp_object_compare_position);
477             _stamp_cache = l;
478         }
480         while (l) {
481             SPItem *original_item = SP_ITEM(l->data);
482             Inkscape::XML::Node *original_repr = SP_OBJECT_REPR(original_item);
484             // remember the position of the item
485             gint pos = original_repr->position();
486             // remember parent
487             Inkscape::XML::Node *parent = sp_repr_parent(original_repr);
489             Inkscape::XML::Node *copy_repr = original_repr->duplicate(parent->document());
491             // add the new repr to the parent
492             parent->appendChild(copy_repr);
493             // move to the saved position
494             copy_repr->setPosition(pos > 0 ? pos : 0);
496             SPItem *copy_item = (SPItem *) sp_desktop_document(_desktop)->getObjectByRepr(copy_repr);
498             NR::Matrix const *new_affine;
499             if (_show == SHOW_OUTLINE) {
500                 NR::Matrix const i2d(sp_item_i2d_affine(original_item));
501                 NR::Matrix const i2dnew( i2d * _current );
502                 sp_item_set_i2d_affine(copy_item, i2dnew);
503                 new_affine = &copy_item->transform;
504             } else {
505                 new_affine = &original_item->transform;
506             }
508             sp_item_write_transform(copy_item, copy_repr, *new_affine);
510             if ( copy_item->isCenterSet() && _center ) {
511                 copy_item->setCenter(*_center * _current);
512             }
514             Inkscape::GC::release(copy_repr);
515             l = l->next;
516         }
517         sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
518                          _("Stamp"));
519     }
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     }
528 void Inkscape::SelTrans::_updateHandles()
530     if ( !_show_handles || _empty )
531     {
532         sp_remove_handles(_shandle, 8);
533         sp_remove_handles(_rhandle, 8);
534         sp_remove_handles(&_chandle, 1);
535         return;
536     }
538     // center handle
539     if ( _chandle == NULL ) {
540         _chandle = sp_knot_new(_desktop, _("<b>Center</b> of rotation and skewing: drag to reposition; scaling with Shift also uses this center"));
542         _chandle->setShape (SP_CTRL_SHAPE_BITMAP);
543         _chandle->setSize (13);
544         _chandle->setAnchor (handle_center.anchor);
545         _chandle->setMode (SP_CTRL_MODE_XOR);
546         _chandle->setFill(0x00000000, 0x00000000, 0x00000000);
547         _chandle->setStroke(0x000000ff, 0xff0000b0, 0xff0000b0);
548         _chandle->setPixbuf(handles[handle_center.control]);
549         sp_knot_update_ctrl(_chandle);
551         g_signal_connect(G_OBJECT(_chandle), "request",
552                          G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle_center);
553         g_signal_connect(G_OBJECT(_chandle), "moved",
554                          G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle_center);
555         g_signal_connect(G_OBJECT(_chandle), "grabbed",
556                          G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle_center);
557         g_signal_connect(G_OBJECT(_chandle), "ungrabbed",
558                          G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle_center);
559         g_signal_connect(G_OBJECT(_chandle), "clicked",
560                          G_CALLBACK(sp_sel_trans_handle_click), (gpointer) &handle_center);
561     }
563     sp_remove_handles(&_chandle, 1);
564     if ( _state == STATE_SCALE ) {
565         sp_remove_handles(_rhandle, 8);
566         _showHandles(_shandle, handles_scale, 8,
567                     _("<b>Squeeze or stretch</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"),
568                     _("<b>Scale</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"));
569     } else {
570         sp_remove_handles(_shandle, 8);
571         _showHandles(_rhandle, handles_rotate, 8,
572                     _("<b>Skew</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to skew around the opposite side"),
573                     _("<b>Rotate</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to rotate around the opposite corner"));
574     }
576     if (!_center_is_set) {
577         _center = _desktop->selection->center();
578         _center_is_set = true;
579     }
581     if ( _state == STATE_SCALE || !_center ) {
582         sp_knot_hide(_chandle);
583     } else {
584         sp_knot_show(_chandle);
585         sp_knot_moveto(_chandle, &*_center);
586     }
589 void Inkscape::SelTrans::_updateVolatileState()
591     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
592     _empty = selection->isEmpty();
594     if (_empty) {
595         return;
596     }
598     //Update the bboxes
599     _bbox = selection->bounds(_snap_bbox_type);
600     _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX);
601     
602     if (!_bbox) {
603         _empty = true;
604         return;
605     }
607     _strokewidth = stroke_average_width (selection->itemList());
610 static void sp_remove_handles(SPKnot *knot[], gint num)
612     for (int i = 0; i < num; i++) {
613         if (knot[i] != NULL) {
614             sp_knot_hide(knot[i]);
615         }
616     }
619 void Inkscape::SelTrans::_showHandles(SPKnot *knot[], SPSelTransHandle const handle[], gint num,
620                              gchar const *even_tip, gchar const *odd_tip)
622     g_return_if_fail( !_empty );
624     for (int i = 0; i < num; i++) {
625         if (knot[i] == NULL) {
626             knot[i] = sp_knot_new(_desktop, i % 2 ? even_tip : odd_tip);
628             knot[i]->setShape (SP_CTRL_SHAPE_BITMAP);
629             knot[i]->setSize (13);
630             knot[i]->setAnchor (handle[i].anchor);
631             knot[i]->setMode (SP_CTRL_MODE_XOR);
632             knot[i]->setFill(0x000000ff, 0x00ff6600, 0x00ff6600); // inversion, green, green
633             knot[i]->setStroke(0x000000ff, 0x000000ff, 0x000000ff); // inversion
634             knot[i]->setPixbuf(handles[handle[i].control]);
635             sp_knot_update_ctrl(knot[i]);
637             g_signal_connect(G_OBJECT(knot[i]), "request",
638                              G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle[i]);
639             g_signal_connect(G_OBJECT(knot[i]), "moved",
640                              G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle[i]);
641             g_signal_connect(G_OBJECT(knot[i]), "grabbed",
642                              G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle[i]);
643             g_signal_connect(G_OBJECT(knot[i]), "ungrabbed",
644                              G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle[i]);
645             g_signal_connect(G_OBJECT(knot[i]), "event", G_CALLBACK(sp_seltrans_handle_event), (gpointer) &handle[i]);
646         }
647         sp_knot_show(knot[i]);
649         NR::Point const handle_pt(handle[i].x, handle[i].y);
650         // shouldn't have nullary bbox, but knots
651         g_assert(_bbox);
652         NR::Point p( _bbox->min()
653                      + ( _bbox->dimensions()
654                          * NR::scale(handle_pt) ) );
656         sp_knot_moveto(knot[i], &p);
657     }
660 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data)
662     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleGrab(
663         knot, state, *(SPSelTransHandle const *) data
664         );
667 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint state, gpointer data)
669     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->ungrab();
672 static void sp_sel_trans_handle_new_event(SPKnot *knot, NR::Point *position, guint state, gpointer data)
674     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleNewEvent(
675         knot, position, state, *(SPSelTransHandle const *) data
676         );
679 static gboolean sp_sel_trans_handle_request(SPKnot *knot, NR::Point *position, guint state, gboolean *data)
681     return SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleRequest(
682         knot, position, state, *(SPSelTransHandle const *) data
683         );
686 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data)
688     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleClick(
689         knot, state, *(SPSelTransHandle const *) data
690         );
693 void Inkscape::SelTrans::handleClick(SPKnot *knot, guint state, SPSelTransHandle const &handle)
695     switch (handle.anchor) {
696         case GTK_ANCHOR_CENTER:
697             if (state & GDK_SHIFT_MASK) {
698                 // Unset the  center position for all selected items
699                 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
700                     SPItem *it = (SPItem*)(SP_OBJECT(l->data));
701                     it->unsetCenter();
702                     SP_OBJECT(it)->updateRepr();
703                     _center_is_set = false;  // center has changed
704                     _updateHandles();
705                 }
706                 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT, 
707                                         _("Reset center"));
708             }
709             break;
710         default:
711             break;
712     }
715 void Inkscape::SelTrans::handleGrab(SPKnot *knot, guint state, SPSelTransHandle const &handle)
717     switch (handle.anchor) {
718         case GTK_ANCHOR_CENTER:
719             g_object_set(G_OBJECT(_grip),
720                          "shape", SP_CTRL_SHAPE_BITMAP,
721                          "size", 13.0,
722                          NULL);
723             sp_canvas_item_show(_grip);
724             break;
725         default:
726             g_object_set(G_OBJECT(_grip),
727                          "shape", SP_CTRL_SHAPE_CROSS,
728                          "size", 7.0,
729                          NULL);
730             sp_canvas_item_show(_norm);
731             sp_canvas_item_show(_grip);
733             break;
734     }
736     grab(sp_knot_position(knot), handle.x, handle.y, FALSE);
740 void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, NR::Point *position, guint state, SPSelTransHandle const &handle)
742     if (!SP_KNOT_IS_GRABBED(knot)) {
743         return;
744     }
746     // in case items have been unhooked from the document, don't
747     // try to continue processing events for them.
748     for (unsigned int i = 0; i < _items.size(); i++) {
749         if (!SP_OBJECT_DOCUMENT(SP_OBJECT(_items[i].first)) ) {
750             return;
751         }
752     }
754     handle.action(this, handle, *position, state);
758 gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, NR::Point *position, guint state, SPSelTransHandle const &handle)
760     if (!SP_KNOT_IS_GRABBED(knot)) {
761         return TRUE;
762     }
764     knot->desktop->setPosition(*position);
766     if (state & GDK_MOD1_MASK) {
767         *position = _point + ( *position - _point ) / 10;
768     }
770     if ((!(state & GDK_SHIFT_MASK) == !(_state == STATE_ROTATE)) && (&handle != &handle_center)) {
771         _origin = _opposite;
772         _origin_for_bboxpoints = _opposite_for_bboxpoints;
773         _origin_for_specpoints = _opposite_for_specpoints;
774     } else if (_center) {
775         _origin = *_center;
776         _origin_for_bboxpoints = *_center;
777         _origin_for_specpoints = *_center;
778     } else {
779         // FIXME
780         return TRUE;
781     }
782     if (handle.request(this, handle, *position, state)) {
783         sp_knot_set_position(knot, position, state);
784         SP_CTRL(_grip)->moveto(*position);
785         SP_CTRL(_norm)->moveto(_origin);
786     }
788     return TRUE;
792 void Inkscape::SelTrans::_selChanged(Inkscape::Selection *selection)
794     if (!_grabbed) {
795         // reread in case it changed on the fly:
796         gchar const *prefs_bbox = prefs_get_string_attribute("tools.select", "bounding_box");
797         _snap_bbox_type = (prefs_bbox != NULL && strcmp(prefs_bbox, "geometric")==0)? SPItem::GEOMETRIC_BBOX : SPItem::APPROXIMATE_BBOX;
798         //SPItem::APPROXIMATE_BBOX will be replaced by SPItem::VISUAL_BBOX, as soon as the latter is implemented properly
799     
800         _updateVolatileState();
801         _current.set_identity();
802         _center_is_set = false; // center(s) may have changed
803         _updateHandles();
804     }
807 void Inkscape::SelTrans::_selModified(Inkscape::Selection *selection, guint flags)
809     if (!_grabbed) {
810         _updateVolatileState();
811         _current.set_identity();
813         // reset internal flag
814         _changed = false;
816         _center_is_set = false;  // center(s) may have changed
818         _updateHandles();
819     }
822 /*
823  * handlers for handle move-request
824  */
826 /** Returns -1 or 1 according to the sign of x.  Returns 1 for 0 and NaN. */
827 static double sign(double const x)
829     return ( x < 0
830              ? -1
831              : 1 );
834 gboolean sp_sel_trans_scale_request(Inkscape::SelTrans *seltrans,
835                                     SPSelTransHandle const &, NR::Point &pt, guint state)
837     return seltrans->scaleRequest(pt, state);
840 gboolean sp_sel_trans_stretch_request(Inkscape::SelTrans *seltrans,
841                                       SPSelTransHandle const &handle, NR::Point &pt, guint state)
843     return seltrans->stretchRequest(handle, pt, state);
846 gboolean sp_sel_trans_skew_request(Inkscape::SelTrans *seltrans,
847                                    SPSelTransHandle const &handle, NR::Point &pt, guint state)
849     return seltrans->skewRequest(handle, pt, state);
852 gboolean sp_sel_trans_rotate_request(Inkscape::SelTrans *seltrans,
853                                      SPSelTransHandle const &, NR::Point &pt, guint state)
855     return seltrans->rotateRequest(pt, state);
858 gboolean sp_sel_trans_center_request(Inkscape::SelTrans *seltrans,
859                                      SPSelTransHandle const &, NR::Point &pt, guint state)
861     return seltrans->centerRequest(pt, state);
864 gboolean Inkscape::SelTrans::scaleRequest(NR::Point &pt, guint state)
866     using NR::X;
867     using NR::Y;
869     NR::Point d = _point - _origin;
870     NR::scale s(0, 0);
872     /* Work out the new scale factors `s' */
873     for ( unsigned int i = 0 ; i < 2 ; i++ ) {
874         if ( fabs(d[i]) > 0.001 ) {
875             s[i] = ( pt[i] - _origin[i] ) / d[i];
876             if ( fabs(s[i]) < 1e-9 ) {
877                 s[i] = 1e-9;
878             }
879         }
880     }
882     SnapManager const &m = _desktop->namedview->snap_manager;
884     /* Get a STL list of the selected items.
885     ** FIXME: this should probably be done by Inkscape::Selection.
886     */
887     std::list<SPItem const*> it;
888     for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
889         it.push_back(reinterpret_cast<SPItem*>(i->data));
890     }
892     if ((state & GDK_CONTROL_MASK) || _desktop->isToolboxButtonActive ("lock")) {
893         // Scale is locked to a 1:1 aspect ratio, so that s[X] must be made to equal s[Y].
894         //
895         // The aspect-ratio must be locked before snapping
896         if (fabs(s[NR::X]) > fabs(s[NR::Y])) {
897                 s[NR::X] = fabs(s[NR::Y]) * sign(s[NR::X]);
898             } else {
899                 s[NR::Y] = fabs(s[NR::X]) * sign(s[NR::Y]);
900             }
901             
902         // Snap along a suitable constraint vector from the origin.
904         // The inclination of the constraint vector is calculated from the aspect ratio
905         NR::Point bbox_dim = _bbox->dimensions();
906         double const aspect_ratio = bbox_dim[1] / bbox_dim[0]; // = height / width
908         // Determine direction of the constraint vector
909         NR::Point const cv = NR::Point(
910             pt[NR::X] > _origin[NR::X] ? 1 : -1,
911             pt[NR::Y] > _origin[NR::Y] ? aspect_ratio : -aspect_ratio
912             );
914         std::pair<NR::scale, bool> bb = m.constrainedSnapScale(Snapper::BBOX_POINT,
915                                                                _bbox_points,
916                                                                it,
917                                                                Snapper::ConstraintLine(_origin_for_bboxpoints, cv),
918                                                                s,
919                                                                _origin_for_bboxpoints);
921         std::pair<NR::scale, bool> sn = m.constrainedSnapScale(Snapper::SNAP_POINT,
922                                                                _snap_points,
923                                                                it,
924                                                                Snapper::ConstraintLine(_origin_for_specpoints, cv),
925                                                                s,
926                                                                _origin_for_specpoints);
928         if (bb.second == false && sn.second == false) {
929             /* We didn't snap, so just keep the locked aspect ratio */
930         } else {
931             /* Choose the smaller difference in scale.  Since s[X] == s[Y] we can
932             ** just compare difference in s[X].
933             */
934             double const bd = bb.second ? fabs(bb.first[NR::X] - s[NR::X]) : NR_HUGE;
935             double const sd = sn.second ? fabs(sn.first[NR::X] - s[NR::X]) : NR_HUGE;
936             s = (bd < sd) ? bb.first : sn.first;
937         }
939     } else {
940         /* Scale aspect ratio is unlocked */
941         
942         std::pair<NR::scale, bool> bb = m.freeSnapScale(Snapper::BBOX_POINT,
943                                                         _bbox_points,
944                                                         it,
945                                                         s,
946                                                         _origin_for_bboxpoints);
947         std::pair<NR::scale, bool> sn = m.freeSnapScale(Snapper::SNAP_POINT,
948                                                         _snap_points,
949                                                         it,
950                                                         s,
951                                                         _origin_for_specpoints);
953         /* Pick the snap that puts us closest to the original scale */
954         NR::Coord bd = bb.second ?
955             fabs(NR::L2(NR::Point(bb.first[NR::X], bb.first[NR::Y])) -
956                  NR::L2(NR::Point(s[NR::X], s[NR::Y])))
957             : NR_HUGE;
958         NR::Coord sd = sn.second ?
959             fabs(NR::L2(NR::Point(sn.first[NR::X], sn.first[NR::Y])) -
960                  NR::L2(NR::Point(s[NR::X], s[NR::Y])))
961             : NR_HUGE;
962         s = (bd < sd) ? bb.first : sn.first;
963     }
965     /* Update the knot position */
966     pt = ( _point - _origin ) * s + _origin;
968     /* Status text */
969     _message_context.setF(Inkscape::NORMAL_MESSAGE,
970                           _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
971                           100 * s[NR::X], 100 * s[NR::Y]);
973     return TRUE;
976 gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, NR::Point &pt, guint state)
978     using NR::X;
979     using NR::Y;
981     NR::Dim2 axis, perp;
983     switch (handle.cursor) {
984         case GDK_TOP_SIDE:
985         case GDK_BOTTOM_SIDE:
986            axis = NR::Y;
987            perp = NR::X;
988            break;
989         case GDK_LEFT_SIDE:
990         case GDK_RIGHT_SIDE:
991            axis = NR::X;
992            perp = NR::Y;
993            break;
994         default:
995             g_assert_not_reached();
996             return TRUE;
997     };
999     if ( fabs( _point[axis] - _origin[axis] ) < 1e-15 ) {
1000         return FALSE;
1001     }
1003     NR::scale s(1, 1);
1004     s[axis] = ( ( pt[axis] - _origin[axis] )
1005                 / ( _point[axis] - _origin[axis] ) );
1006     if ( fabs(s[axis]) < 1e-15 ) {
1007         s[axis] = 1e-15;
1008     }
1010     /* Get a STL list of the selected items.
1011     ** FIXME: this should probably be done by Inkscape::Selection.
1012     */
1013     std::list<SPItem const*> it;
1014     for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
1015         it.push_back(reinterpret_cast<SPItem*>(i->data));
1016     }
1018     SnapManager const &m = _desktop->namedview->snap_manager;
1020     if ( state & GDK_CONTROL_MASK ) {
1021         // on ctrl, apply symmetrical scaling instead of stretching
1022         s[perp] = fabs(s[axis]);
1024         std::pair<NR::Coord, bool> const bb = m.freeSnapStretch(
1025             Snapper::BBOX_POINT,
1026             _bbox_points,
1027             it,
1028             s[axis],
1029             _origin_for_bboxpoints,
1030             axis,
1031             true);
1033         std::pair<NR::Coord, bool> const sn = m.freeSnapStretch(
1034             Snapper::SNAP_POINT,
1035             _snap_points,
1036             it,
1037             s[axis],
1038             _origin_for_specpoints,
1039             axis,
1040             true);
1042         NR::Coord const bd = bb.second ? fabs(bb.first - s[axis]) : NR_HUGE;
1043         NR::Coord const sd = sn.second ? fabs(sn.first - s[axis]) : NR_HUGE;
1044         NR::Coord const ratio = (bd < sd) ? bb.first : sn.first;
1046         s[axis] = fabs(ratio) * sign(s[axis]);
1047         s[perp] = fabs(s[axis]);
1048     } else {
1049         
1050         std::pair<NR::Coord, bool> const bb = m.freeSnapStretch(
1051             Snapper::BBOX_POINT,
1052             _bbox_points,
1053             it,
1054             s[axis],
1055             _origin_for_bboxpoints,
1056             axis,
1057             false);
1059         std::pair<NR::Coord, bool> const sn = m.freeSnapStretch(
1060             Snapper::SNAP_POINT,
1061             _snap_points,
1062             it,
1063             s[axis],
1064             _origin_for_specpoints,
1065             axis,
1066             false);
1068         /* Choose the smaller difference in scale */
1069         NR::Coord const bd = bb.second ? fabs(bb.first - s[axis]) : NR_HUGE;
1070         NR::Coord const sd = sn.second ? fabs(sn.first - s[axis]) : NR_HUGE;
1071         s[axis] = (bd < sd) ? bb.first : sn.first;
1072         s[perp] = 1;
1073     }
1075     pt = ( _point - _origin ) * NR::scale(s) + _origin;
1076     if (isNaN(pt[X] + pt[Y])) {
1077         g_warning("point=(%g, %g), norm=(%g, %g), s=(%g, %g)\n",
1078                   _point[X], _point[Y], _origin[X], _origin[Y], s[X], s[Y]);
1079     }
1081     // status text
1082     _message_context.setF(Inkscape::NORMAL_MESSAGE,
1083                           _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1084                           100 * s[NR::X], 100 * s[NR::Y]);
1086     return TRUE;
1089 gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, NR::Point &pt, guint state)
1091     using NR::X;
1092     using NR::Y;
1094     if (handle.cursor != GDK_SB_V_DOUBLE_ARROW && handle.cursor != GDK_SB_H_DOUBLE_ARROW) {
1095         return FALSE;
1096     }
1098     NR::Dim2 dim_a;
1099     NR::Dim2 dim_b;
1100     if (handle.cursor == GDK_SB_V_DOUBLE_ARROW) {
1101         dim_a = X;
1102         dim_b = Y;
1103     } else {
1104         dim_a = Y;
1105         dim_b = X;
1106     }
1108     double skew[2];
1109     double s[2] = { 1.0, 1.0 };
1111     if (fabs(_point[dim_a] - _origin[dim_a]) < NR_EPSILON) {
1112         return FALSE;
1113     }
1115     skew[dim_a] = ( pt[dim_b] - _point[dim_b] ) / ( _point[dim_a] - _origin[dim_a] );
1117     s[dim_a] = ( pt[dim_a] - _origin[dim_a] ) / ( _point[dim_a] - _origin[dim_a] );
1119     if ( fabs(s[dim_a]) < 1 ) {
1120         s[dim_a] = sign(s[dim_a]);
1121     } else {
1122         s[dim_a] = floor( s[dim_a] + 0.5 );
1123     }
1125     double radians = atan(skew[dim_a] / s[dim_a]);
1127     if (state & GDK_CONTROL_MASK) {
1129         int snaps = prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12);
1131         if (snaps) {
1132             double sections = floor( radians * snaps / M_PI + .5 );
1133             if (fabs(sections) >= snaps / 2) sections = sign(sections) * (snaps / 2 - 1);
1134             radians = ( M_PI / snaps ) * sections;
1135         }
1136         skew[dim_a] = tan(radians) * s[dim_a];
1137     } else {
1138         SnapManager const &m = _desktop->namedview->snap_manager;
1140         std::pair<NR::Coord, bool> bb = m.freeSnapSkew(Inkscape::Snapper::BBOX_POINT,
1141                                                        _bbox_points,
1142                                                        std::list<SPItem const *>(),
1143                                                        skew[dim_a],
1144                                                        _origin_for_bboxpoints,
1145                                                        dim_b);
1147         std::pair<NR::Coord, bool> sn = m.freeSnapSkew(Inkscape::Snapper::SNAP_POINT,
1148                                                        _snap_points,
1149                                                        std::list<SPItem const *>(),
1150                                                        skew[dim_a],
1151                                                        _origin_for_specpoints,
1152                                                        dim_b);
1153         
1154         if (bb.second || sn.second) {
1155             /* We snapped something, so change the skew to reflect it */
1156             NR::Coord const bd = bb.second ? bb.first : NR_HUGE;
1157             NR::Coord const sd = sn.second ? sn.first : NR_HUGE;
1158             skew[dim_a] = std::min(bd, sd);
1159         }
1160     }
1162     pt[dim_b] = ( _point[dim_a] - _origin[dim_a] ) * skew[dim_a] + _point[dim_b];
1163     pt[dim_a] = ( _point[dim_a] - _origin[dim_a] ) * s[dim_a] + _origin[dim_a];
1165     /* status text */
1166     double degrees = 180 / M_PI * radians;
1167     if (degrees > 180) degrees -= 360;
1168     if (degrees < -180) degrees += 360;
1170     _message_context.setF(Inkscape::NORMAL_MESSAGE,
1171                           // TRANSLATORS: don't modify the first ";"
1172                           // (it will NOT be displayed as ";" - only the second one will be)
1173                           _("<b>Skew</b>: %0.2f&#176;; with <b>Ctrl</b> to snap angle"),
1174                           degrees);
1176     return TRUE;
1179 gboolean Inkscape::SelTrans::rotateRequest(NR::Point &pt, guint state)
1181     int snaps = prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12);
1183     // rotate affine in rotate
1184     NR::Point const d1 = _point - _origin;
1185     NR::Point const d2 = pt     - _origin;
1187     NR::Coord const h1 = NR::L2(d1);
1188     if (h1 < 1e-15) return FALSE;
1189     NR::Point q1 = d1 / h1;
1190     NR::Coord const h2 = NR::L2(d2);
1191     if (fabs(h2) < 1e-15) return FALSE;
1192     NR::Point q2 = d2 / h2;
1194     double radians;
1195     if (state & GDK_CONTROL_MASK) {
1196         /* Have to restrict movement. */
1197         double cos_t = NR::dot(q1, q2);
1198         double sin_t = NR::dot(NR::rot90(q1), q2);
1199         radians = atan2(sin_t, cos_t);
1200         if (snaps) {
1201             radians = ( M_PI / snaps ) * floor( radians * snaps / M_PI + .5 );
1202         }
1203         q1 = NR::Point(1, 0);
1204         q2 = NR::Point(cos(radians), sin(radians));
1205     } else {
1206         radians = atan2(NR::dot(NR::rot90(d1), d2),
1207                         NR::dot(d1, d2));
1208     }
1210     NR::rotate const r1(q1);
1211     NR::rotate const r2(q2);
1212     pt = _point * NR::translate(-_origin) * ( r2 / r1 ) * NR::translate(_origin);
1214     /* status text */
1215     double degrees = 180 / M_PI * radians;
1216     if (degrees > 180) degrees -= 360;
1217     if (degrees < -180) degrees += 360;
1219     _message_context.setF(Inkscape::NORMAL_MESSAGE,
1220                           // TRANSLATORS: don't modify the first ";"
1221                           // (it will NOT be displayed as ";" - only the second one will be)
1222                           _("<b>Rotate</b>: %0.2f&#176;; with <b>Ctrl</b> to snap angle"), degrees);
1224     return TRUE;
1227 gboolean Inkscape::SelTrans::centerRequest(NR::Point &pt, guint state)
1229     using NR::X;
1230     using NR::Y;
1232     SnapManager const &m = _desktop->namedview->snap_manager;
1233     pt = m.freeSnap(Snapper::SNAP_POINT, pt, NULL).getPoint();
1235     if (state & GDK_CONTROL_MASK) {
1236         if ( fabs(_point[X] - pt[X]) > fabs(_point[Y] - pt[Y]) ) {
1237             pt[Y] = _point[Y];
1238         } else {
1239             pt[X] = _point[X];
1240         }
1241     }
1243     if ( !(state & GDK_SHIFT_MASK) && _bbox ) {
1244         // screen pixels to snap center to bbox
1245 #define SNAP_DIST 5
1246         // FIXME: take from prefs
1247         double snap_dist = SNAP_DIST / _desktop->current_zoom();
1249         for (int i = 0; i < 2; i++) {
1250             if (fabs(pt[i] - _bbox->min()[i]) < snap_dist) {
1251                 pt[i] = _bbox->min()[i];
1252             }
1253             if (fabs(pt[i] - _bbox->midpoint()[i]) < snap_dist) {
1254                 pt[i] = _bbox->midpoint()[i];
1255             }
1256             if (fabs(pt[i] - _bbox->max()[i]) < snap_dist) {
1257                 pt[i] = _bbox->max()[i];
1258             }
1259         }
1260     }
1262     // status text
1263     GString *xs = SP_PX_TO_METRIC_STRING(pt[X], _desktop->namedview->getDefaultMetric());
1264     GString *ys = SP_PX_TO_METRIC_STRING(pt[Y], _desktop->namedview->getDefaultMetric());
1265     _message_context.setF(Inkscape::NORMAL_MESSAGE, _("Move <b>center</b> to %s, %s"), xs->str, ys->str);
1266     g_string_free(xs, FALSE);
1267     g_string_free(ys, FALSE);
1269     return TRUE;
1272 /*
1273  * handlers for handle movement
1274  *
1275  */
1277 void sp_sel_trans_stretch(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, NR::Point &pt, guint state)
1279     seltrans->stretch(handle, pt, state);
1282 void sp_sel_trans_scale(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
1284     seltrans->scale(pt, state);
1287 void sp_sel_trans_skew(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, NR::Point &pt, guint state)
1289     seltrans->skew(handle, pt, state);
1292 void sp_sel_trans_rotate(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
1294     seltrans->rotate(pt, state);
1297 void Inkscape::SelTrans::stretch(SPSelTransHandle const &handle, NR::Point &pt, guint state)
1299     using NR::X;
1300     using NR::Y;
1302     NR::Dim2 dim;
1303     switch (handle.cursor) {
1304         case GDK_LEFT_SIDE:
1305         case GDK_RIGHT_SIDE:
1306             dim = X;
1307             break;
1308         case GDK_TOP_SIDE:
1309         case GDK_BOTTOM_SIDE:
1310             dim = Y;
1311             break;
1312         default:
1313             g_assert_not_reached();
1314             abort();
1315             break;
1316     }
1318     NR::Point const scale_origin(_origin);
1319     double const offset = _point[dim] - scale_origin[dim];
1320     if (!( fabs(offset) >= 1e-15 )) {
1321         return;
1322     }
1323     NR::scale s(1, 1);
1324     s[dim] = ( pt[dim] - scale_origin[dim] ) / offset;
1325     if (isNaN(s[dim])) {
1326         g_warning("s[dim]=%g, pt[dim]=%g, scale_origin[dim]=%g, point[dim]=%g\n",
1327                   s[dim], pt[dim], scale_origin[dim], _point[dim]);
1328     }
1329     if (!( fabs(s[dim]) >= 1e-15 )) {
1330         s[dim] = 1e-15;
1331     }
1332     if (state & GDK_CONTROL_MASK) {
1333         /* Preserve aspect ratio, but never flip in the dimension not being edited. */
1334         s[!dim] = fabs(s[dim]);
1335     }
1337     if (!_bbox) {
1338         return;
1339     }
1341     //Get two corners of the new bbox
1342     NR::Point p1 = _approximate_bbox->min() * (NR::translate(-scale_origin) * NR::Matrix(s) * NR::translate(scale_origin));
1343     NR::Point p2 = _approximate_bbox->max() * (NR::translate(-scale_origin) * NR::Matrix(s) * NR::translate(scale_origin));
1345     //Find the ones at the lower-left and upper-right, as required by get_scale_transform_with_stroke
1346     NR::Point new_bbox_min = NR::Point(std::min(p1[NR::X], p2[NR::X]), std::min(p1[NR::Y], p2[NR::Y]));
1347     NR::Point new_bbox_max = NR::Point(std::max(p1[NR::X], p2[NR::X]), std::max(p1[NR::Y], p2[NR::Y]));
1349     int transform_stroke = false;
1350     gdouble strokewidth = 0;
1351         
1352     if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
1353         transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1354         strokewidth = _strokewidth;
1355     }
1356         
1357     NR::Matrix scaler = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
1358                     new_bbox_min[NR::X], new_bbox_min[NR::Y], new_bbox_max[NR::X], new_bbox_max[NR::Y]);
1360     transform(scaler, NR::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1363 void Inkscape::SelTrans::scale(NR::Point &pt, guint state)
1365     if (!_bbox) {
1366         return;
1367     }
1369     NR::Point const offset = _point - _origin;
1371     NR::scale s (1, 1);
1372     for (int i = NR::X; i <= NR::Y; i++) {
1373         if (fabs(offset[i]) > 1e-9)
1374             s[i] = (pt[i] - _origin[i]) / offset[i];
1375         if (fabs(s[i]) < 1e-9)
1376             s[i] = 1e-9;
1377     }
1378     
1379     //Get two corners of the new bbox
1380     NR::Point p1 = _approximate_bbox->min() * (NR::translate(-_origin) * NR::Matrix(s) * NR::translate(_origin));
1381     NR::Point p2 = _approximate_bbox->max() * (NR::translate(-_origin) * NR::Matrix(s) * NR::translate(_origin));
1383     //Find the ones at the lower-left and upper-right, as required by get_scale_transform_with_stroke
1384     NR::Point new_bbox_min = NR::Point(std::min(p1[NR::X], p2[NR::X]), std::min(p1[NR::Y], p2[NR::Y]));
1385     NR::Point new_bbox_max = NR::Point(std::max(p1[NR::X], p2[NR::X]), std::max(p1[NR::Y], p2[NR::Y]));
1386     
1387     int transform_stroke = false;
1388     gdouble strokewidth = 0;
1390     if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
1391         transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1392         strokewidth = _strokewidth;
1393     }
1394         
1395     NR::Matrix scaler = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
1396                     new_bbox_min[NR::X], new_bbox_min[NR::Y], new_bbox_max[NR::X], new_bbox_max[NR::Y]);
1397     
1398     transform(scaler, NR::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1401 void Inkscape::SelTrans::skew(SPSelTransHandle const &handle, NR::Point &pt, guint state)
1403     NR::Point const offset = _point - _origin;
1405     unsigned dim;
1406     switch (handle.cursor) {
1407         case GDK_SB_H_DOUBLE_ARROW:
1408             dim = NR::Y;
1409             break;
1410         case GDK_SB_V_DOUBLE_ARROW:
1411             dim = NR::X;
1412             break;
1413         default:
1414             g_assert_not_reached();
1415             abort();
1416             break;
1417     }
1418     if (fabs(offset[dim]) < 1e-15) {
1419         return;
1420     }
1421     NR::Matrix skew = NR::identity();
1422     skew[2*dim + dim] = (pt[dim] - _origin[dim]) / offset[dim];
1423     skew[2*dim + (1-dim)] = (pt[1-dim] - _point[1-dim]) / offset[dim];
1424     skew[2*(1-dim) + (dim)] = 0;
1425     skew[2*(1-dim) + (1-dim)] = 1;
1427     for (int i = 0; i < 2; i++) {
1428         if (fabs(skew[3*i]) < 1e-15) {
1429             skew[3*i] = 1e-15;
1430         }
1431     }
1432     transform(skew, _origin);
1435 void Inkscape::SelTrans::rotate(NR::Point &pt, guint state)
1437     NR::Point const offset = _point - _origin;
1439     NR::Coord const h1 = NR::L2(offset);
1440     if (h1 < 1e-15) {
1441         return;
1442     }
1443     NR::Point const q1 = offset / h1;
1444     NR::Coord const h2 = NR::L2( pt - _origin );
1445     if (h2 < 1e-15) {
1446         return;
1447     }
1448     NR::Point const q2 = (pt - _origin) / h2;
1449     NR::rotate const r1(q1);
1450     NR::rotate const r2(q2);
1452     NR::Matrix rotate( r2 / r1 );
1453     transform(rotate, _origin);
1456 void sp_sel_trans_center(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
1458     seltrans->setCenter(pt);
1462 void Inkscape::SelTrans::moveTo(NR::Point const &xy, guint state)
1464     SnapManager const &m = _desktop->namedview->snap_manager;
1466     /* The amount that we've moved by during this drag */
1467     NR::Point dxy = xy - _point;
1469     /* Get a STL list of the selected items.
1470     ** FIXME: this should probably be done by Inkscape::Selection.
1471     */
1472     std::list<SPItem const*> it;
1473     for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
1474         it.push_back(reinterpret_cast<SPItem*>(i->data));
1475     }
1477     bool const alt = (state & GDK_MOD1_MASK);
1478     bool const control = (state & GDK_CONTROL_MASK);
1479     bool const shift = (state & GDK_SHIFT_MASK);
1481     if (alt) {
1483         /* Alt pressed means keep offset: snap the moved distance to the grid.
1484         ** FIXME: this will snap to more than just the grid, nowadays.
1485         */
1487         dxy = m.freeSnap(Snapper::SNAP_POINT, dxy, NULL).getPoint();
1489     } else if (!shift) {
1491         /* We're snapping to things, possibly with a constraint to horizontal or
1492         ** vertical movement.  Obtain a list of possible translations and then
1493         ** pick the smallest.
1494         */
1496         /* This will be our list of possible translations */
1497         std::list<std::pair<NR::Point, bool> > s;
1499         if (control) {
1501             /* Snap to things, and also constrain to horizontal or vertical movement */
1503             for (unsigned int dim = 0; dim < 2; dim++) {
1504                 s.push_back(m.constrainedSnapTranslation(Inkscape::Snapper::BBOX_POINT,
1505                                                          _bbox_points,
1506                                                          it,
1507                                                          Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1508                                                          dxy));
1509                             
1510                 s.push_back(m.constrainedSnapTranslation(Inkscape::Snapper::SNAP_POINT,
1511                                                          _snap_points,
1512                                                          it,
1513                                                          Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1514                                                          dxy));
1515             }
1517         } else {
1519             /* Snap to things with no constraint */
1521             s.push_back(m.freeSnapTranslation(Inkscape::Snapper::BBOX_POINT,
1522                                               _bbox_points, it, dxy));
1523             s.push_back(m.freeSnapTranslation(Inkscape::Snapper::SNAP_POINT,
1524                                               _snap_points, it, dxy));
1525         }
1527         /* Pick one */
1528         NR::Coord best = NR_HUGE;
1529         for (std::list<std::pair<NR::Point, bool> >::const_iterator i = s.begin(); i != s.end(); i++) {
1530             if (i->second) {
1531                 NR::Coord const m = NR::L2(i->first);
1532                 if (m < best) {
1533                     best = m;
1534                     dxy = i->first;
1535                 }
1536             }
1537         }
1538     }
1540     if (control) {
1541         /* Ensure that the horizontal and vertical constraint has been applied */
1542         if (fabs(dxy[NR::X]) > fabs(dxy[NR::Y])) {
1543             dxy[NR::Y] = 0;
1544         } else {
1545             dxy[NR::X] = 0;
1546         }
1547     }
1549     NR::Matrix const move((NR::translate(dxy)));
1550     NR::Point const norm(0, 0);
1551     transform(move, norm);
1553     // status text
1554     GString *xs = SP_PX_TO_METRIC_STRING(dxy[NR::X], _desktop->namedview->getDefaultMetric());
1555     GString *ys = SP_PX_TO_METRIC_STRING(dxy[NR::Y], _desktop->namedview->getDefaultMetric());
1556     _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);
1557     g_string_free(xs, TRUE);
1558     g_string_free(ys, TRUE);
1562 /*
1563   Local Variables:
1564   mode:c++
1565   c-file-style:"stroustrup"
1566   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1567   indent-tabs-mode:nil
1568   fill-column:99
1569   End:
1570 */
1571 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :