Code

Next roud of NR ==> Geom conversion
[inkscape.git] / src / seltrans.cpp
1 #define __SELTRANS_C__
3 /*
4  * Helper object for transforming selected items
5  *
6  * Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   bulia byak <buliabyak@users.sf.net>
9  *   Carl Hetherington <inkscape@carlh.net>
10  *   Diederik van Lierop <mail@diedenrezi.nl>
11  *
12  * Copyright (C) 1999-2002 Lauris Kaplinski
13  * Copyright (C) 1999-2008 Authors
14  *
15  * Released under GNU GPL, read the file 'COPYING' for more information
16  */
18 #ifdef HAVE_CONFIG_H
19 # include <config.h>
20 #endif
21 #include <cstring>
22 #include <string>
24 #include <libnr/nr-matrix-ops.h>
25 #include <libnr/nr-matrix-translate-ops.h>
26 #include <libnr/nr-rotate-ops.h>
27 #include <libnr/nr-scale-ops.h>
28 #include <libnr/nr-translate-matrix-ops.h>
29 #include <libnr/nr-translate-ops.h>
30 #include <gdk/gdkkeysyms.h>
31 #include "document.h"
32 #include "sp-namedview.h"
33 #include "desktop.h"
34 #include "desktop-handles.h"
35 #include "desktop-style.h"
36 #include "knot.h"
37 #include "snap.h"
38 #include "selection.h"
39 #include "select-context.h"
40 #include "sp-item.h"
41 #include "sp-item-transform.h"
42 #include "seltrans-handles.h"
43 #include "seltrans.h"
44 #include "selection-chemistry.h"
45 #include "sp-metrics.h"
46 #include "verbs.h"
47 #include <glibmm/i18n.h>
48 #include "display/sp-ctrlline.h"
49 #include "prefs-utils.h"
50 #include "xml/repr.h"
51 #include "mod360.h"
52 #include "2geom/angle.h"
53 #include "display/snap-indicator.h"
56 static void sp_remove_handles(SPKnot *knot[], gint num);
58 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data);
59 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint state, gpointer data);
60 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data);
61 static void sp_sel_trans_handle_new_event(SPKnot *knot, NR::Point *position, guint32 state, gpointer data);
62 static gboolean sp_sel_trans_handle_request(SPKnot *knot, NR::Point *p, guint state, gboolean *data);
64 extern GdkPixbuf *handles[];
66 static gboolean sp_seltrans_handle_event(SPKnot *knot, GdkEvent *event, gpointer)
67 {
68     switch (event->type) {
69         case GDK_MOTION_NOTIFY:
70             break;
71         case GDK_KEY_PRESS:
72             if (get_group0_keyval (&event->key) == GDK_space) {
73                 /* stamping mode: both mode(show content and outline) operation with knot */
74                 if (!SP_KNOT_IS_GRABBED(knot)) {
75                     return FALSE;
76                 }
77                 SPDesktop *desktop = knot->desktop;
78                 Inkscape::SelTrans *seltrans = SP_SELECT_CONTEXT(desktop->event_context)->_seltrans;
79                 seltrans->stamp();
80                 return TRUE;
81             }
82             break;
83         default:
84             break;
85     }
87     return FALSE;
88 }
90 Inkscape::SelTrans::SelTrans(SPDesktop *desktop) :
91     _desktop(desktop),
92     _selcue(desktop),
93     _state(STATE_SCALE),
94     _show(SHOW_CONTENT),
95     _grabbed(false),
96     _show_handles(true),
97     _bbox(),
98     _approximate_bbox(),
99     _absolute_affine(NR::scale(1,1)),
100     _opposite(NR::Point(0,0)),
101     _opposite_for_specpoints(NR::Point(0,0)),
102     _opposite_for_bboxpoints(NR::Point(0,0)),
103     _origin_for_specpoints(NR::Point(0,0)),
104     _origin_for_bboxpoints(NR::Point(0,0)),
105     _chandle(NULL),
106     _stamp_cache(NULL),
107     _message_context(desktop->messageStack())
109     int prefs_bbox = prefs_get_int_attribute("tools", "bounding_box", 0);
110     _snap_bbox_type = (prefs_bbox ==0)?
111         SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
113     g_return_if_fail(desktop != NULL);
115     for (int i = 0; i < 8; i++) {
116         _shandle[i] = NULL;
117         _rhandle[i] = NULL;
118     }
120     _updateVolatileState();
121     _current_relative_affine.set_identity();
123     _center_is_set = false; // reread _center from items, or set to bbox midpoint
125     _updateHandles();
127     _selection = sp_desktop_selection(desktop);
129     _norm = sp_canvas_item_new(sp_desktop_controls(desktop),
130                                SP_TYPE_CTRL,
131                                "anchor", GTK_ANCHOR_CENTER,
132                                "mode", SP_CTRL_MODE_COLOR,
133                                "shape", SP_CTRL_SHAPE_BITMAP,
134                                "size", 13.0,
135                                "filled", TRUE,
136                                "fill_color", 0x00000000,
137                                "stroked", TRUE,
138                                "stroke_color", 0x000000a0,
139                                "pixbuf", handles[12],
140                                NULL);
142     _grip = sp_canvas_item_new(sp_desktop_controls(desktop),
143                                SP_TYPE_CTRL,
144                                "anchor", GTK_ANCHOR_CENTER,
145                                "mode", SP_CTRL_MODE_XOR,
146                                "shape", SP_CTRL_SHAPE_CROSS,
147                                "size", 7.0,
148                                "filled", TRUE,
149                                "fill_color", 0xffffff7f,
150                                "stroked", TRUE,
151                                "stroke_color", 0xffffffff,
152                                "pixbuf", handles[12],
153                                NULL);
155     sp_canvas_item_hide(_grip);
156     sp_canvas_item_hide(_norm);
158     for (int i = 0; i < 4; i++) {
159         _l[i] = sp_canvas_item_new(sp_desktop_controls(desktop), SP_TYPE_CTRLLINE, NULL);
160         sp_canvas_item_hide(_l[i]);
161     }
163     _sel_changed_connection = _selection->connectChanged(
164         sigc::mem_fun(*this, &Inkscape::SelTrans::_selChanged)
165         );
167     _sel_modified_connection = _selection->connectModified(
168         sigc::mem_fun(*this, &Inkscape::SelTrans::_selModified)
169         );
172 Inkscape::SelTrans::~SelTrans()
174     _sel_changed_connection.disconnect();
175     _sel_modified_connection.disconnect();
177     for (unsigned int i = 0; i < 8; i++) {
178         if (_shandle[i]) {
179             g_object_unref(G_OBJECT(_shandle[i]));
180             _shandle[i] = NULL;
181         }
182         if (_rhandle[i]) {
183             g_object_unref(G_OBJECT(_rhandle[i]));
184             _rhandle[i] = NULL;
185         }
186     }
187     if (_chandle) {
188         g_object_unref(G_OBJECT(_chandle));
189         _chandle = NULL;
190     }
192     if (_norm) {
193         gtk_object_destroy(GTK_OBJECT(_norm));
194         _norm = NULL;
195     }
196     if (_grip) {
197         gtk_object_destroy(GTK_OBJECT(_grip));
198         _grip = NULL;
199     }
200     for (int i = 0; i < 4; i++) {
201         if (_l[i]) {
202             gtk_object_destroy(GTK_OBJECT(_l[i]));
203             _l[i] = NULL;
204         }
205     }
207     for (unsigned i = 0; i < _items.size(); i++) {
208         sp_object_unref(SP_OBJECT(_items[i]), NULL);
209     }
211     _items.clear();
212     _items_const.clear();
213     _items_affines.clear();
214     _items_centers.clear();
217 void Inkscape::SelTrans::resetState()
219     _state = STATE_SCALE;
222 void Inkscape::SelTrans::increaseState()
224     if (_state == STATE_SCALE) {
225         _state = STATE_ROTATE;
226     } else {
227         _state = STATE_SCALE;
228     }
230     _center_is_set = true; // no need to reread center
232     _updateHandles();
235 void Inkscape::SelTrans::setCenter(NR::Point const &p)
237     _center = p;
238     _center_is_set = true;
240     // Write the new center position into all selected items
241     for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
242         SPItem *it = (SPItem*)SP_OBJECT(l->data);
243         it->setCenter(p);
244         // only set the value; updating repr and document_done will be done once, on ungrab
245     }
247     _updateHandles();
250 void Inkscape::SelTrans::grab(NR::Point const &p, gdouble x, gdouble y, bool show_handles)
252     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
254     g_return_if_fail(!_grabbed);
256     _grabbed = true;
257     _show_handles = show_handles;
258     _updateVolatileState();
259     _current_relative_affine.set_identity();
261     _changed = false;
263     if (_empty) {
264         return;
265     }
267     for (GSList const *l = selection->itemList(); l; l = l->next) {
268         SPItem *it = (SPItem *)sp_object_ref(SP_OBJECT(l->data), NULL);
269         _items.push_back(it);
270         _items_const.push_back(it);
271         _items_affines.push_back(sp_item_i2d_affine(it));
272         _items_centers.push_back(it->getCenter()); // for content-dragging, we need to remember original centers
273     }
275     _handle_x = x;
276     _handle_y = y;
278     // The selector tool should snap the bbox, special snappoints, and path nodes
279     // (The special points are the handles, center, rotation axis, font baseline, ends of spiral, etc.)
281     // First, determine the bounding box for snapping ...
282     _bbox = selection->bounds(_snap_bbox_type);
283     _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX); // Used for correctly scaling the strokewidth
284     _geometric_bbox = selection->bounds(SPItem::GEOMETRIC_BBOX);
285     _point = p;
286     if (_geometric_bbox) {
287         _point_geom = _geometric_bbox->min() + _geometric_bbox->dimensions() * NR::scale(x, y);
288     } else {
289         _point_geom = p;
290     }
292     // Next, get all points to consider for snapping
293     SnapManager const &m = _desktop->namedview->snap_manager;
294     _snap_points.clear();
295     to_2geom(selection->getSnapPoints(m.getIncludeItemCenter()), _snap_points);
296     std::vector<Geom::Point> snap_points_hull;
297     to_2geom(selection->getSnapPointsConvexHull(), snap_points_hull);
298     if (_snap_points.size() > 100) {
299         /* Snapping a huge number of nodes will take way too long, so limit the number of snappable nodes
300         An average user would rarely ever try to snap such a large number of nodes anyway, because
301         (s)he could hardly discern which node would be snapping */
302         _snap_points = snap_points_hull;
303         // Unfortunately, by now we will have lost the font-baseline snappoints :-(
304     }
306     // Find bbox hulling all special points, which excludes stroke width. Here we need to include the
307     // path nodes, for example because a rectangle which has been converted to a path doesn't have
308     // any other special points
309     NR::Rect snap_points_bbox;
310     if ( snap_points_hull.empty() == false ) {
311         std::vector<Geom::Point>::iterator i = snap_points_hull.begin();
312         snap_points_bbox = NR::Rect(*i, *i);
313         i++;
314         while (i != snap_points_hull.end()) {
315             snap_points_bbox.expandTo(*i);
316             i++;
317         }
318     }
320     _bbox_points.clear();
321     if (_bbox) {
322         // ... and add the bbox corners to _bbox_points
323         for ( unsigned i = 0 ; i < 4 ; i++ ) {
324             _bbox_points.push_back(to_2geom(_bbox->corner(i)));
325         }
326         // There are two separate "opposites" (i.e. opposite w.r.t. the handle being dragged):
327         //  - one for snapping the boundingbox, which can be either visual or geometric
328         //  - one for snapping the special points
329         // The "opposite" in case of a geometric boundingbox always coincides with the "opposite" for the special points
330         // These distinct "opposites" are needed in the snapmanager to avoid bugs such as #sf1540195 (in which
331         // a box is caught between two guides)
332         _opposite_for_bboxpoints = _bbox->min() + _bbox->dimensions() * NR::scale(1-x, 1-y);
333         _opposite_for_specpoints = snap_points_bbox.min() + snap_points_bbox.dimensions() * NR::scale(1-x, 1-y);
334         _opposite = _opposite_for_bboxpoints;
335     }
337     // The lines below are usefull for debugging any snapping issues, as they'll spit out all points that are considered for snapping
339     /*std::cout << "Number of snap points:  " << _snap_points.size() << std::endl;
340     for (std::vector<NR::Point>::const_iterator i = _snap_points.begin(); i != _snap_points.end(); i++)
341     {
342         std::cout << "    " << *i << std::endl;
343     }
345     std::cout << "Number of bbox points:  " << _bbox_points.size() << std::endl;
346     for (std::vector<NR::Point>::const_iterator i = _bbox_points.begin(); i != _bbox_points.end(); i++)
347     {
348         std::cout << "    " << *i << std::endl;
349     }*/
351     if ((x != -1) && (y != -1)) {
352         sp_canvas_item_show(_norm);
353         sp_canvas_item_show(_grip);
354     }
356     if (_show == SHOW_OUTLINE) {
357         for (int i = 0; i < 4; i++)
358             sp_canvas_item_show(_l[i]);
359     }
361     _updateHandles();
362     g_return_if_fail(_stamp_cache == NULL);
365 void Inkscape::SelTrans::transform(NR::Matrix const &rel_affine, NR::Point const &norm)
367     g_return_if_fail(_grabbed);
368     g_return_if_fail(!_empty);
370     NR::Matrix const affine( NR::translate(-norm) * rel_affine * NR::translate(norm) );
372     if (_show == SHOW_CONTENT) {
373         // update the content
374         for (unsigned i = 0; i < _items.size(); i++) {
375             SPItem &item = *_items[i];
376             NR::Matrix const &prev_transform = _items_affines[i];
377             sp_item_set_i2d_affine(&item, prev_transform * affine);
378         }
379     } else {
380         if (_bbox) {
381             NR::Point p[4];
382             /* update the outline */
383             for (unsigned i = 0 ; i < 4 ; i++) {
384                 p[i] = _bbox->corner(i) * affine;
385             }
386             for (unsigned i = 0 ; i < 4 ; i++) {
387                 sp_ctrlline_set_coords(SP_CTRLLINE(_l[i]), p[i], p[(i+1)%4]);
388             }
389         }
390     }
392     _current_relative_affine = affine;
393     _changed = true;
394     _updateHandles();
397 void Inkscape::SelTrans::ungrab()
399     g_return_if_fail(_grabbed);
400     _grabbed = false;
401     _show_handles = true;
403     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
404     _updateVolatileState();
406     for (unsigned i = 0; i < _items.size(); i++) {
407         sp_object_unref(SP_OBJECT(_items[i]), NULL);
408     }
410     sp_canvas_item_hide(_norm);
411     sp_canvas_item_hide(_grip);
413     if (_show == SHOW_OUTLINE) {
414         for (int i = 0; i < 4; i++)
415             sp_canvas_item_hide(_l[i]);
416     }
418     if (_stamp_cache) {
419         g_slist_free(_stamp_cache);
420         _stamp_cache = NULL;
421     }
423     _message_context.clear();
425     if (!_empty && _changed) {
426         sp_selection_apply_affine(selection, _current_relative_affine, (_show == SHOW_OUTLINE)? true : false);
427         if (_center) {
428             *_center *= _current_relative_affine;
429             _center_is_set = true;
430         }
432 // If dragging showed content live, sp_selection_apply_affine cannot change the centers
433 // appropriately - it does not know the original positions of the centers (all objects already have
434 // the new bboxes). So we need to reset the centers from our saved array.
435         if (_show != SHOW_OUTLINE && !_current_relative_affine.is_translation()) {
436             for (unsigned i = 0; i < _items_centers.size(); i++) {
437                 SPItem *currentItem = _items[i];
438                 if (currentItem->isCenterSet()) { // only if it's already set
439                     currentItem->setCenter (_items_centers[i] * _current_relative_affine);
440                     SP_OBJECT(currentItem)->updateRepr();
441                 }
442             }
443         }
445         _items.clear();
446         _items_const.clear();
447         _items_affines.clear();
448         _items_centers.clear();
450         if (_current_relative_affine.is_translation()) {
451             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
452                              _("Move"));
453         } else if (_current_relative_affine.is_scale()) {
454             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
455                              _("Scale"));
456         } else if (_current_relative_affine.is_rotation()) {
457             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
458                              _("Rotate"));
459         } else {
460             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
461                              _("Skew"));
462         }
464     } else {
466         if (_center_is_set) {
467             // we were dragging center; update reprs and commit undoable action
468             for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
469                 SPItem *it = (SPItem*)SP_OBJECT(l->data);
470                 SP_OBJECT(it)->updateRepr();
471             }
472             sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
473                             _("Set center"));
474         }
476         _items.clear();
477         _items_const.clear();
478         _items_affines.clear();
479         _items_centers.clear();
480         _updateHandles();
481     }
484 /* fixme: This is really bad, as we compare positions for each stamp (Lauris) */
485 /* fixme: IMHO the best way to keep sort cache would be to implement timestamping at last */
487 void Inkscape::SelTrans::stamp()
489     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
491     bool fixup = !_grabbed;
492     if ( fixup && _stamp_cache ) {
493         // TODO - give a proper fix. Simple temproary work-around for the grab() issue
494         g_slist_free(_stamp_cache);
495         _stamp_cache = NULL;
496     }
498     /* stamping mode */
499     if (!_empty) {
500         GSList *l;
501         if (_stamp_cache) {
502             l = _stamp_cache;
503         } else {
504             /* Build cache */
505             l  = g_slist_copy((GSList *) selection->itemList());
506             l  = g_slist_sort(l, (GCompareFunc) sp_object_compare_position);
507             _stamp_cache = l;
508         }
510         while (l) {
511             SPItem *original_item = SP_ITEM(l->data);
512             Inkscape::XML::Node *original_repr = SP_OBJECT_REPR(original_item);
514             // remember the position of the item
515             gint pos = original_repr->position();
516             // remember parent
517             Inkscape::XML::Node *parent = sp_repr_parent(original_repr);
519             Inkscape::XML::Node *copy_repr = original_repr->duplicate(parent->document());
521             // add the new repr to the parent
522             parent->appendChild(copy_repr);
523             // move to the saved position
524             copy_repr->setPosition(pos > 0 ? pos : 0);
526             SPItem *copy_item = (SPItem *) sp_desktop_document(_desktop)->getObjectByRepr(copy_repr);
528             Geom::Matrix const *new_affine;
529             if (_show == SHOW_OUTLINE) {
530                 NR::Matrix const i2d(sp_item_i2d_affine(original_item));
531                 NR::Matrix const i2dnew( i2d * _current_relative_affine );
532                 sp_item_set_i2d_affine(copy_item, i2dnew);
533                 new_affine = &copy_item->transform;
534             } else {
535                 new_affine = &original_item->transform;
536             }
538             sp_item_write_transform(copy_item, copy_repr, *new_affine);
540             if ( copy_item->isCenterSet() && _center ) {
541                 copy_item->setCenter(*_center * _current_relative_affine);
542             }
544             Inkscape::GC::release(copy_repr);
545             l = l->next;
546         }
547         sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
548                          _("Stamp"));
549     }
551     if ( fixup && _stamp_cache ) {
552         // TODO - give a proper fix. Simple temproary work-around for the grab() issue
553         g_slist_free(_stamp_cache);
554         _stamp_cache = NULL;
555     }
558 void Inkscape::SelTrans::_updateHandles()
560     if ( !_show_handles || _empty )
561     {
562         sp_remove_handles(_shandle, 8);
563         sp_remove_handles(_rhandle, 8);
564         sp_remove_handles(&_chandle, 1);
565         return;
566     }
568     // center handle
569     if ( _chandle == NULL ) {
570         _chandle = sp_knot_new(_desktop, _("<b>Center</b> of rotation and skewing: drag to reposition; scaling with Shift also uses this center"));
572         _chandle->setShape (SP_CTRL_SHAPE_BITMAP);
573         _chandle->setSize (13);
574         _chandle->setAnchor (handle_center.anchor);
575         _chandle->setMode (SP_CTRL_MODE_XOR);
576         _chandle->setFill(0x00000000, 0x00000000, 0x00000000);
577         _chandle->setStroke(0x000000ff, 0xff0000b0, 0xff0000b0);
578         _chandle->setPixbuf(handles[handle_center.control]);
579         sp_knot_update_ctrl(_chandle);
581         g_signal_connect(G_OBJECT(_chandle), "request",
582                          G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle_center);
583         g_signal_connect(G_OBJECT(_chandle), "moved",
584                          G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle_center);
585         g_signal_connect(G_OBJECT(_chandle), "grabbed",
586                          G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle_center);
587         g_signal_connect(G_OBJECT(_chandle), "ungrabbed",
588                          G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle_center);
589         g_signal_connect(G_OBJECT(_chandle), "clicked",
590                          G_CALLBACK(sp_sel_trans_handle_click), (gpointer) &handle_center);
591     }
593     sp_remove_handles(&_chandle, 1);
594     if ( _state == STATE_SCALE ) {
595         sp_remove_handles(_rhandle, 8);
596         _showHandles(_shandle, handles_scale, 8,
597                     _("<b>Squeeze or stretch</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"),
598                     _("<b>Scale</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"));
599     } else {
600         sp_remove_handles(_shandle, 8);
601         _showHandles(_rhandle, handles_rotate, 8,
602                     _("<b>Skew</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to skew around the opposite side"),
603                     _("<b>Rotate</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to rotate around the opposite corner"));
604     }
606     if (!_center_is_set) {
607         _center = _desktop->selection->center();
608         _center_is_set = true;
609     }
611     if ( _state == STATE_SCALE || !_center ) {
612         sp_knot_hide(_chandle);
613     } else {
614         sp_knot_show(_chandle);
615         sp_knot_moveto(_chandle, *_center);
616     }
619 void Inkscape::SelTrans::_updateVolatileState()
621     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
622     _empty = selection->isEmpty();
624     if (_empty) {
625         return;
626     }
628     //Update the bboxes
629     _bbox = selection->bounds(_snap_bbox_type);
630     _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX);
632     if (!_bbox) {
633         _empty = true;
634         return;
635     }
637     _strokewidth = stroke_average_width (selection->itemList());
640 static void sp_remove_handles(SPKnot *knot[], gint num)
642     for (int i = 0; i < num; i++) {
643         if (knot[i] != NULL) {
644             sp_knot_hide(knot[i]);
645         }
646     }
649 void Inkscape::SelTrans::_showHandles(SPKnot *knot[], SPSelTransHandle const handle[], gint num,
650                              gchar const *even_tip, gchar const *odd_tip)
652     g_return_if_fail( !_empty );
654     for (int i = 0; i < num; i++) {
655         if (knot[i] == NULL) {
656             knot[i] = sp_knot_new(_desktop, i % 2 ? even_tip : odd_tip);
658             knot[i]->setShape (SP_CTRL_SHAPE_BITMAP);
659             knot[i]->setSize (13);
660             knot[i]->setAnchor (handle[i].anchor);
661             knot[i]->setMode (SP_CTRL_MODE_XOR);
662             knot[i]->setFill(0x000000ff, 0x00ff6600, 0x00ff6600); // inversion, green, green
663             knot[i]->setStroke(0x000000ff, 0x000000ff, 0x000000ff); // inversion
664             knot[i]->setPixbuf(handles[handle[i].control]);
665             sp_knot_update_ctrl(knot[i]);
667             g_signal_connect(G_OBJECT(knot[i]), "request",
668                              G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle[i]);
669             g_signal_connect(G_OBJECT(knot[i]), "moved",
670                              G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle[i]);
671             g_signal_connect(G_OBJECT(knot[i]), "grabbed",
672                              G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle[i]);
673             g_signal_connect(G_OBJECT(knot[i]), "ungrabbed",
674                              G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle[i]);
675             g_signal_connect(G_OBJECT(knot[i]), "event", G_CALLBACK(sp_seltrans_handle_event), (gpointer) &handle[i]);
676         }
677         sp_knot_show(knot[i]);
679         NR::Point const handle_pt(handle[i].x, handle[i].y);
680         // shouldn't have nullary bbox, but knots
681         g_assert(_bbox);
682         NR::Point p( _bbox->min()
683                      + ( _bbox->dimensions()
684                          * NR::scale(handle_pt) ) );
686         sp_knot_moveto(knot[i], p);
687     }
690 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data)
692     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleGrab(
693         knot, state, *(SPSelTransHandle const *) data
694         );
697 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint /*state*/, gpointer /*data*/)
699     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->ungrab();
702 static void sp_sel_trans_handle_new_event(SPKnot *knot, NR::Point *position, guint state, gpointer data)
704     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleNewEvent(
705         knot, position, state, *(SPSelTransHandle const *) data
706         );
709 static gboolean sp_sel_trans_handle_request(SPKnot *knot, NR::Point *position, guint state, gboolean *data)
711     return SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleRequest(
712         knot, position, state, *(SPSelTransHandle const *) data
713         );
716 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data)
718     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleClick(
719         knot, state, *(SPSelTransHandle const *) data
720         );
723 void Inkscape::SelTrans::handleClick(SPKnot */*knot*/, guint state, SPSelTransHandle const &handle)
725     switch (handle.anchor) {
726         case GTK_ANCHOR_CENTER:
727             if (state & GDK_SHIFT_MASK) {
728                 // Unset the  center position for all selected items
729                 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
730                     SPItem *it = (SPItem*)(SP_OBJECT(l->data));
731                     it->unsetCenter();
732                     SP_OBJECT(it)->updateRepr();
733                     _center_is_set = false;  // center has changed
734                     _updateHandles();
735                 }
736                 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
737                                         _("Reset center"));
738             }
739             break;
740         default:
741             break;
742     }
745 void Inkscape::SelTrans::handleGrab(SPKnot *knot, guint /*state*/, SPSelTransHandle const &handle)
747     switch (handle.anchor) {
748         case GTK_ANCHOR_CENTER:
749             g_object_set(G_OBJECT(_grip),
750                          "shape", SP_CTRL_SHAPE_BITMAP,
751                          "size", 13.0,
752                          NULL);
753             sp_canvas_item_show(_grip);
754             break;
755         default:
756             g_object_set(G_OBJECT(_grip),
757                          "shape", SP_CTRL_SHAPE_CROSS,
758                          "size", 7.0,
759                          NULL);
760             sp_canvas_item_show(_norm);
761             sp_canvas_item_show(_grip);
763             break;
764     }
766     grab(sp_knot_position(knot), handle.x, handle.y, FALSE);
770 void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, NR::Point *position, guint state, SPSelTransHandle const &handle)
772     if (!SP_KNOT_IS_GRABBED(knot)) {
773         return;
774     }
776     // in case items have been unhooked from the document, don't
777     // try to continue processing events for them.
778     for (unsigned int i = 0; i < _items.size(); i++) {
779         if (!SP_OBJECT_DOCUMENT(SP_OBJECT(_items[i])) ) {
780             return;
781         }
782     }
784     handle.action(this, handle, *position, state);
788 gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, NR::Point *position, guint state, SPSelTransHandle const &handle)
790     if (!SP_KNOT_IS_GRABBED(knot)) {
791         return TRUE;
792     }
794     knot->desktop->setPosition(*position);
796     // When holding shift while rotating or skewing, the transformation will be
797     // relative to the point opposite of the handle; otherwise it will be relative
798     // to the center as set for the selection
799     if ((!(state & GDK_SHIFT_MASK) == !(_state == STATE_ROTATE)) && (&handle != &handle_center)) {
800         _origin = _opposite;
801         _origin_for_bboxpoints = _opposite_for_bboxpoints;
802         _origin_for_specpoints = _opposite_for_specpoints;
803     } else if (_center) {
804         _origin = *_center;
805         _origin_for_bboxpoints = *_center;
806         _origin_for_specpoints = *_center;
807     } else {
808         // FIXME
809         return TRUE;
810     }
811     if (handle.request(this, handle, *position, state)) {
812         sp_knot_set_position(knot, *position, state);
813         SP_CTRL(_grip)->moveto(*position);
814         SP_CTRL(_norm)->moveto(_origin);
815     }
817     return TRUE;
821 void Inkscape::SelTrans::_selChanged(Inkscape::Selection */*selection*/)
823     if (!_grabbed) {
824         // reread in case it changed on the fly:
825         int prefs_bbox = prefs_get_int_attribute("tools", "bounding_box", 0);
826          _snap_bbox_type = (prefs_bbox ==0)?
827             SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
828         //SPItem::APPROXIMATE_BBOX will be replaced by SPItem::VISUAL_BBOX, as soon as the latter is implemented properly
830         _updateVolatileState();
831         _current_relative_affine.set_identity();
832         _center_is_set = false; // center(s) may have changed
833         _updateHandles();
834     }
837 void Inkscape::SelTrans::_selModified(Inkscape::Selection */*selection*/, guint /*flags*/)
839     if (!_grabbed) {
840         _updateVolatileState();
841         _current_relative_affine.set_identity();
843         // reset internal flag
844         _changed = false;
846         _center_is_set = false;  // center(s) may have changed
848         _updateHandles();
849     }
852 /*
853  * handlers for handle move-request
854  */
856 /** Returns -1 or 1 according to the sign of x.  Returns 1 for 0 and NaN. */
857 static double sign(double const x)
859     return ( x < 0
860              ? -1
861              : 1 );
864 gboolean sp_sel_trans_scale_request(Inkscape::SelTrans *seltrans,
865                                     SPSelTransHandle const &, NR::Point &pt, guint state)
867     return seltrans->scaleRequest(pt, state);
870 gboolean sp_sel_trans_stretch_request(Inkscape::SelTrans *seltrans,
871                                       SPSelTransHandle const &handle, NR::Point &pt, guint state)
873     return seltrans->stretchRequest(handle, pt, state);
876 gboolean sp_sel_trans_skew_request(Inkscape::SelTrans *seltrans,
877                                    SPSelTransHandle const &handle, NR::Point &pt, guint state)
879     return seltrans->skewRequest(handle, pt, state);
882 gboolean sp_sel_trans_rotate_request(Inkscape::SelTrans *seltrans,
883                                      SPSelTransHandle const &, NR::Point &pt, guint state)
885     return seltrans->rotateRequest(pt, state);
888 gboolean sp_sel_trans_center_request(Inkscape::SelTrans *seltrans,
889                                      SPSelTransHandle const &, NR::Point &pt, guint state)
891     return seltrans->centerRequest(pt, state);
894 gboolean Inkscape::SelTrans::scaleRequest(NR::Point &pt, guint state)
897     // Calculate the scale factors, which can be either visual or geometric
898     // depending on which type of bbox is currently being used (see preferences -> selector tool)
899     NR::scale default_scale = calcScaleFactors(_point, pt, _origin);
901     // Find the scale factors for the geometric bbox
902     NR::Point pt_geom = _getGeomHandlePos(pt);
903     NR::scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
905     _absolute_affine = Geom::identity(); //Initialize the scaler
907     if (state & GDK_MOD1_MASK) { // scale by an integer multiplier/divider
908         // We're scaling either the visual or the geometric bbox here (see the comment above)
909         for ( unsigned int i = 0 ; i < 2 ; i++ ) {
910             if (fabs(default_scale[i]) > 1) {
911                 default_scale[i] = round(default_scale[i]);
912             } else if (default_scale[i] != 0) {
913                 default_scale[i] = 1/round(1/(MIN(default_scale[i], 10)));
914             }
915         }
916         // Update the knot position
917         pt = _calcAbsAffineDefault(default_scale);
918         // When scaling by an integer, snapping is not needed
919     } else {
920         // In all other cases we should try to snap now
921         SnapManager &m = _desktop->namedview->snap_manager;
922         m.setup(_desktop, false, _items_const);
924         Inkscape::SnappedPoint bb, sn;
925         NR::Coord bd(NR_HUGE);
926         NR::Coord sd(NR_HUGE);
928         if ((state & GDK_CONTROL_MASK) || _desktop->isToolboxButtonActive ("lock")) {
929             // Scale is locked to a 1:1 aspect ratio, so that s[X] must be made to equal s[Y].
930             //
931             // The aspect-ratio must be locked before snapping
932             if (fabs(default_scale[NR::X]) > fabs(default_scale[NR::Y])) {
933                 default_scale[NR::X] = fabs(default_scale[NR::Y]) * sign(default_scale[NR::X]);
934                 geom_scale[NR::X] = fabs(geom_scale[NR::Y]) * sign(geom_scale[NR::X]);
935             } else {
936                 default_scale[NR::Y] = fabs(default_scale[NR::X]) * sign(default_scale[NR::Y]);
937                 geom_scale[NR::Y] = fabs(geom_scale[NR::X]) * sign(geom_scale[NR::Y]);
938             }
940             // Snap along a suitable constraint vector from the origin.
941             Geom::Scale default_scale_2geom = to_2geom(default_scale);
942             Geom::Scale geom_scale_2geom = to_2geom(geom_scale);
943             bb = m.constrainedSnapScale(Snapper::SNAPPOINT_BBOX, _bbox_points, default_scale_2geom, to_2geom(_origin_for_bboxpoints));
944             sn = m.constrainedSnapScale(Snapper::SNAPPOINT_NODE, _snap_points, geom_scale_2geom, to_2geom(_origin_for_specpoints));
946             /* Choose the smaller difference in scale.  Since s[X] == s[Y] we can
947             ** just compare difference in s[X].
948             */
949             bd = bb.getSnapped() ? fabs(bb.getTransformation()[NR::X] - default_scale_2geom[Geom::X]) : NR_HUGE;
950             sd = sn.getSnapped() ? fabs(sn.getTransformation()[NR::X] - geom_scale_2geom[Geom::X]) : NR_HUGE;
951         } else {
952             /* Scale aspect ratio is unlocked */
953             Geom::Scale default_scale_2geom = to_2geom(default_scale);
954             Geom::Scale geom_scale_2geom = to_2geom(geom_scale);
955             bb = m.freeSnapScale(Snapper::SNAPPOINT_BBOX, _bbox_points, default_scale_2geom, to_2geom(_origin_for_bboxpoints));
956             sn = m.freeSnapScale(Snapper::SNAPPOINT_NODE, _snap_points, geom_scale_2geom, to_2geom(_origin_for_specpoints));
958             /* Pick the snap that puts us closest to the original scale */
959             bd = bb.getSnapped() ? fabs(NR::L2(bb.getTransformation()) - NR::L2(NR::Point(default_scale_2geom[Geom::X], default_scale_2geom[Geom::Y]))) : NR_HUGE;
960             sd = sn.getSnapped() ? fabs(NR::L2(sn.getTransformation()) - NR::L2(NR::Point(geom_scale_2geom[Geom::X], geom_scale_2geom[Geom::Y]))) : NR_HUGE;
961         }
963         if (!(bb.getSnapped() || sn.getSnapped())) {
964             // We didn't snap at all! Don't update the handle position, just calculate the new transformation
965             _calcAbsAffineDefault(default_scale);
966             _desktop->snapindicator->remove_snappoint();
967         } else if (bd < sd) {
968             // We snapped the bbox (which is either visual or geometric)
969             _desktop->snapindicator->set_new_snappoint(bb);
970             default_scale = NR::scale(bb.getTransformation());
971             // Calculate the new transformation and update the handle position
972             pt = _calcAbsAffineDefault(default_scale);
973         } else {
974             _desktop->snapindicator->set_new_snappoint(sn);
975             // We snapped the special points (e.g. nodes), which are not at the visual bbox
976             // The handle location however (pt) might however be at the visual bbox, so we
977             // will have to calculate pt taking the stroke width into account
978             geom_scale = NR::scale(sn.getTransformation());
979             pt = _calcAbsAffineGeom(geom_scale);
980         }
981     }
983     /* Status text */
984     _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
985                           _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
986                           100 * _absolute_affine[0], 100 * _absolute_affine[3]);
988     return TRUE;
991 gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, NR::Point &pt, guint state)
993     NR::Dim2 axis, perp;
994     switch (handle.cursor) {
995         case GDK_TOP_SIDE:
996         case GDK_BOTTOM_SIDE:
997             axis = NR::Y;
998             perp = NR::X;
999             break;
1000         case GDK_LEFT_SIDE:
1001         case GDK_RIGHT_SIDE:
1002             axis = NR::X;
1003             perp = NR::Y;
1004             break;
1005         default:
1006             g_assert_not_reached();
1007             return TRUE;
1008     };
1010     // Calculate the scale factors, which can be either visual or geometric
1011     // depending on which type of bbox is currently being used (see preferences -> selector tool)
1012     NR::scale default_scale = calcScaleFactors(_point, pt, _origin);
1013     default_scale[perp] = 1;
1015     // Find the scale factors for the geometric bbox
1016     NR::Point pt_geom = _getGeomHandlePos(pt);
1017     NR::scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
1018     geom_scale[perp] = 1;
1020     _absolute_affine = Geom::identity(); //Initialize the scaler
1022     if (state & GDK_MOD1_MASK) { // stretch by an integer multiplier/divider
1023         if (fabs(default_scale[axis]) > 1) {
1024             default_scale[axis] = round(default_scale[axis]);
1025         } else if (default_scale[axis] != 0) {
1026             default_scale[axis] = 1/round(1/(MIN(default_scale[axis], 10)));
1027         }
1028         // Calculate the new transformation and update the handle position
1029         pt = _calcAbsAffineDefault(default_scale);
1030         // When stretching by an integer, snapping is not needed
1031     } else {
1032         // In all other cases we should try to snap now
1034         SnapManager &m = _desktop->namedview->snap_manager;
1035         m.setup(_desktop, false, _items_const);
1037         Inkscape::SnappedPoint bb, sn;
1038         g_assert(bb.getSnapped() == false); // Check initialization to catch any regression
1039         NR::Coord bd(NR_HUGE);
1040         NR::Coord sd(NR_HUGE);
1042         bool symmetrical = state & GDK_CONTROL_MASK;
1044         Geom::Scale default_scale_2geom = to_2geom(default_scale);
1045         Geom::Scale geom_scale_2geom = to_2geom(geom_scale);
1047         bb = m.constrainedSnapStretch(Snapper::SNAPPOINT_BBOX, _bbox_points, Geom::Coord(default_scale_2geom[axis]), to_2geom(_origin_for_bboxpoints), Geom::Dim2(axis), symmetrical);
1048         sn = m.constrainedSnapStretch(Snapper::SNAPPOINT_NODE, _snap_points, Geom::Coord(geom_scale_2geom[axis]), to_2geom(_origin_for_specpoints), Geom::Dim2(axis), symmetrical);
1050         if (bb.getSnapped()) {
1051             // We snapped the bbox (which is either visual or geometric)
1052             bd = fabs(bb.getTransformation()[axis] - default_scale_2geom[axis]);
1053             default_scale_2geom[axis] = bb.getTransformation()[axis];
1054         }
1056         if (sn.getSnapped()) {
1057             sd = fabs(sn.getTransformation()[axis] - geom_scale_2geom[axis]);
1058             geom_scale_2geom[axis] = sn.getTransformation()[axis];
1059         }
1061         if (symmetrical) {
1062             // on ctrl, apply symmetrical scaling instead of stretching
1063             // Preserve aspect ratio, but never flip in the dimension not being edited (by using fabs())
1064             default_scale_2geom[perp] = fabs(default_scale_2geom[axis]);
1065             geom_scale_2geom[perp] = fabs(geom_scale_2geom[axis]);
1066         }
1068         if (!(bb.getSnapped() || sn.getSnapped())) {
1069             // We didn't snap at all! Don't update the handle position, just calculate the new transformation
1070             _calcAbsAffineDefault(from_2geom(default_scale_2geom));
1071             _desktop->snapindicator->remove_snappoint();
1072         } else if (bd < sd) {
1073             _desktop->snapindicator->set_new_snappoint(bb);
1074             // Calculate the new transformation and update the handle position
1075             pt = _calcAbsAffineDefault(from_2geom(default_scale_2geom));
1076         } else {
1077             _desktop->snapindicator->set_new_snappoint(sn);
1078             // We snapped the special points (e.g. nodes), which are not at the visual bbox
1079             // The handle location however (pt) might however be at the visual bbox, so we
1080             // will have to calculate pt taking the stroke width into account
1081             pt = _calcAbsAffineGeom(from_2geom(geom_scale_2geom));
1082         }
1083     }
1085     // status text
1086     _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1087                           _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1088                           100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1090     return TRUE;
1093 gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, NR::Point &pt, guint state)
1095     /* When skewing (or rotating):
1096      * 1) the stroke width will not change. This makes life much easier because we don't have to
1097      *    account for that (like for scaling or stretching). As a consequence, all points will
1098      *    have the same origin for the transformation and for the snapping.
1099      * 2) When holding shift, the transformation will be relative to the point opposite of
1100      *    the handle; otherwise it will be relative to the center as set for the selection
1101      */
1103     NR::Dim2 dim_a;
1104     NR::Dim2 dim_b;
1106     switch (handle.cursor) {
1107         case GDK_SB_H_DOUBLE_ARROW:
1108             dim_a = NR::Y;
1109             dim_b = NR::X;
1110             break;
1111         case GDK_SB_V_DOUBLE_ARROW:
1112             dim_a = NR::X;
1113             dim_b = NR::Y;
1114             break;
1115         default:
1116             g_assert_not_reached();
1117             abort();
1118             break;
1119     }
1121     NR::Point const initial_delta = _point - _origin;
1123     if (fabs(initial_delta[dim_a]) < 1e-15) {
1124         return false;
1125     }
1127     // Calculate the scale factors, which can be either visual or geometric
1128     // depending on which type of bbox is currently being used (see preferences -> selector tool)
1129     NR::scale scale = calcScaleFactors(_point, pt, _origin, false);
1130     NR::scale skew = calcScaleFactors(_point, pt, _origin, true);
1131     scale[dim_b] = 1;
1132     skew[dim_b] = 1;
1134     if (fabs(scale[dim_a]) < 1) {
1135         // Prevent shrinking of the selected object, while allowing mirroring
1136         scale[dim_a] = sign(scale[dim_a]);
1137     } else {
1138         // Allow expanding of the selected object by integer multiples
1139         scale[dim_a] = floor(scale[dim_a] + 0.5);
1140     }
1142     double radians = atan(skew[dim_a] / scale[dim_a]);
1144     if (state & GDK_CONTROL_MASK) {
1145         // Snap to defined angle increments
1146         int snaps = prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12);
1147         if (snaps) {
1148             double sections = floor(radians * snaps / M_PI + .5);
1149             if (fabs(sections) >= snaps / 2) {
1150                 sections = sign(sections) * (snaps / 2 - 1);
1151             }
1152             radians = (M_PI / snaps) * sections;
1153         }
1154         skew[dim_a] = tan(radians) * scale[dim_a];
1155     } else {
1156         // Snap to objects, grids, guides
1158         SnapManager &m = _desktop->namedview->snap_manager;
1159         m.setup(_desktop, false, _items_const);
1161         Inkscape::Snapper::ConstraintLine const constraint(component_vectors[dim_b]);
1162         NR::Point const s(skew[dim_a], scale[dim_a]);
1163         Inkscape::SnappedPoint bb = m.constrainedSnapSkew(Inkscape::Snapper::SNAPPOINT_BBOX, _bbox_points, constraint, to_2geom(s), to_2geom(_origin), Geom::Dim2(dim_b));
1164         Inkscape::SnappedPoint sn = m.constrainedSnapSkew(Inkscape::Snapper::SNAPPOINT_NODE, _snap_points, constraint, to_2geom(s), to_2geom(_origin), Geom::Dim2(dim_b));
1166         if (bb.getSnapped() || sn.getSnapped()) {
1167             // We snapped something, so change the skew to reflect it
1168             NR::Coord const bd = bb.getSnapped() ? bb.getTransformation()[0] : NR_HUGE;
1169             NR::Coord const sd = sn.getSnapped() ? sn.getTransformation()[0] : NR_HUGE;
1170             if (bd < sd) {
1171                 _desktop->snapindicator->set_new_snappoint(bb);
1172                 skew[dim_a] = bd;
1173             } else {
1174                 _desktop->snapindicator->set_new_snappoint(sn);
1175                 skew[dim_a] = sd;
1176             }
1177         } else {
1178             _desktop->snapindicator->remove_snappoint();
1179         }
1180     }
1182     // Update the handle position
1183     pt[dim_b] = initial_delta[dim_a] * skew[dim_a] + _point[dim_b];
1184     pt[dim_a] = initial_delta[dim_a] * scale[dim_a] + _origin[dim_a];
1186     // Calculate the relative affine
1187     _relative_affine = Geom::identity();
1188     _relative_affine[2*dim_a + dim_a] = (pt[dim_a] - _origin[dim_a]) / initial_delta[dim_a];
1189     _relative_affine[2*dim_a + (dim_b)] = (pt[dim_b] - _point[dim_b]) / initial_delta[dim_a];
1190     _relative_affine[2*(dim_b) + (dim_a)] = 0;
1191     _relative_affine[2*(dim_b) + (dim_b)] = 1;
1193     for (int i = 0; i < 2; i++) {
1194         if (fabs(_relative_affine[3*i]) < 1e-15) {
1195             _relative_affine[3*i] = 1e-15;
1196         }
1197     }
1199     // Update the status text
1200     double degrees = mod360symm(Geom::rad_to_deg(radians));
1201     _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1202                           // TRANSLATORS: don't modify the first ";"
1203                           // (it will NOT be displayed as ";" - only the second one will be)
1204                           _("<b>Skew</b>: %0.2f&#176;; with <b>Ctrl</b> to snap angle"),
1205                           degrees);
1207     return TRUE;
1210 gboolean Inkscape::SelTrans::rotateRequest(NR::Point &pt, guint state)
1212     /* When rotating (or skewing):
1213      * 1) the stroke width will not change. This makes life much easier because we don't have to
1214      *    account for that (like for scaling or stretching). As a consequence, all points will
1215      *    have the same origin for the transformation and for the snapping.
1216      * 2) When holding shift, the transformation will be relative to the point opposite of
1217      *    the handle; otherwise it will be relative to the center as set for the selection
1218      */
1220     int snaps = prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12);
1222     // rotate affine in rotate
1223     NR::Point const d1 = _point - _origin;
1224     NR::Point const d2 = pt     - _origin;
1226     NR::Coord const h1 = NR::L2(d1); // initial radius
1227     if (h1 < 1e-15) return FALSE;
1228     NR::Point q1 = d1 / h1; // normalized initial vector to handle
1229     NR::Coord const h2 = NR::L2(d2); // new radius
1230     if (fabs(h2) < 1e-15) return FALSE;
1231     NR::Point q2 = d2 / h2; // normalized new vector to handle
1233     double radians;
1234     if (state & GDK_CONTROL_MASK) {
1235         // Snap to defined angle increments
1236         double cos_t = NR::dot(q1, q2);
1237         double sin_t = NR::dot(NR::rot90(q1), q2);
1238         radians = atan2(sin_t, cos_t);
1239         if (snaps) {
1240             radians = ( M_PI / snaps ) * floor( radians * snaps / M_PI + .5 );
1241         }
1242         q1 = NR::Point(1, 0);
1243         q2 = NR::Point(cos(radians), sin(radians));
1244     } else {
1245         radians = atan2(NR::dot(NR::rot90(d1), d2),
1246                         NR::dot(d1, d2));
1247     }
1249     NR::rotate const r1(q1);
1250     NR::rotate const r2(q2);
1252     // Calculate the relative affine
1253     _relative_affine = NR::Matrix(r2/r1);
1255     // Update the handle position
1256     pt = _point * NR::translate(-_origin) * _relative_affine * NR::translate(_origin);
1258     // Update the status text
1259     double degrees = mod360symm(Geom::rad_to_deg(radians));
1260     _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
1261                           // TRANSLATORS: don't modify the first ";"
1262                           // (it will NOT be displayed as ";" - only the second one will be)
1263                           _("<b>Rotate</b>: %0.2f&#176;; with <b>Ctrl</b> to snap angle"), degrees);
1265     return TRUE;
1268 gboolean Inkscape::SelTrans::centerRequest(NR::Point &pt, guint state)
1270     SnapManager &m = _desktop->namedview->snap_manager;
1271     m.setup(_desktop);
1272     Geom::Point pt2g = to_2geom(pt);
1273     m.freeSnapReturnByRef(Snapper::SNAPPOINT_NODE, pt2g);
1274     pt = from_2geom(pt2g);
1276     if (state & GDK_CONTROL_MASK) {
1277         if ( fabs(_point[NR::X] - pt[NR::X]) > fabs(_point[NR::Y] - pt[NR::Y]) ) {
1278             pt[NR::Y] = _point[NR::Y];
1279         } else {
1280             pt[NR::X] = _point[NR::X];
1281         }
1282     }
1284     if ( !(state & GDK_SHIFT_MASK) && _bbox ) {
1285         // screen pixels to snap center to bbox
1286 #define SNAP_DIST 5
1287         // FIXME: take from prefs
1288         double snap_dist = SNAP_DIST / _desktop->current_zoom();
1290         for (int i = 0; i < 2; i++) {
1291             if (fabs(pt[i] - _bbox->min()[i]) < snap_dist) {
1292                 pt[i] = _bbox->min()[i];
1293             }
1294             if (fabs(pt[i] - _bbox->midpoint()[i]) < snap_dist) {
1295                 pt[i] = _bbox->midpoint()[i];
1296             }
1297             if (fabs(pt[i] - _bbox->max()[i]) < snap_dist) {
1298                 pt[i] = _bbox->max()[i];
1299             }
1300         }
1301     }
1303     // status text
1304     GString *xs = SP_PX_TO_METRIC_STRING(pt[NR::X], _desktop->namedview->getDefaultMetric());
1305     GString *ys = SP_PX_TO_METRIC_STRING(pt[NR::Y], _desktop->namedview->getDefaultMetric());
1306     _message_context.setF(Inkscape::NORMAL_MESSAGE, _("Move <b>center</b> to %s, %s"), xs->str, ys->str);
1307     g_string_free(xs, FALSE);
1308     g_string_free(ys, FALSE);
1310     return TRUE;
1313 /*
1314  * handlers for handle movement
1315  *
1316  */
1318 void sp_sel_trans_stretch(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, NR::Point &pt, guint state)
1320     seltrans->stretch(handle, pt, state);
1323 void sp_sel_trans_scale(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
1325     seltrans->scale(pt, state);
1328 void sp_sel_trans_skew(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, NR::Point &pt, guint state)
1330     seltrans->skew(handle, pt, state);
1333 void sp_sel_trans_rotate(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
1335     seltrans->rotate(pt, state);
1338 void Inkscape::SelTrans::stretch(SPSelTransHandle const &/*handle*/, NR::Point &/*pt*/, guint /*state*/)
1340     transform(_absolute_affine, NR::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1343 void Inkscape::SelTrans::scale(NR::Point &/*pt*/, guint /*state*/)
1345     transform(_absolute_affine, NR::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1348 void Inkscape::SelTrans::skew(SPSelTransHandle const &/*handle*/, NR::Point &/*pt*/, guint /*state*/)
1350     transform(_relative_affine, _origin);
1353 void Inkscape::SelTrans::rotate(NR::Point &/*pt*/, guint /*state*/)
1355     transform(_relative_affine, _origin);
1358 void sp_sel_trans_center(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint /*state*/)
1360     seltrans->setCenter(pt);
1364 void Inkscape::SelTrans::moveTo(NR::Point const &xy, guint state)
1366     SnapManager &m = _desktop->namedview->snap_manager;
1367     m.setup(_desktop, true, _items_const);
1369     /* The amount that we've moved by during this drag */
1370     Geom::Point dxy = to_2geom(xy - _point);
1372     bool const alt = (state & GDK_MOD1_MASK);
1373     bool const control = (state & GDK_CONTROL_MASK);
1374     bool const shift = (state & GDK_SHIFT_MASK);
1376     if (alt) {
1378         /* Alt pressed means keep offset: snap the moved distance to the grid.
1379         ** FIXME: this will snap to more than just the grid, nowadays.
1380         */
1382         m.freeSnapReturnByRef(Snapper::SNAPPOINT_NODE, dxy);
1384     } else if (!shift) {
1386         /* We're snapping to things, possibly with a constraint to horizontal or
1387         ** vertical movement.  Obtain a list of possible translations and then
1388         ** pick the smallest.
1389         */
1391         /* This will be our list of possible translations */
1392         std::list<Inkscape::SnappedPoint> s;
1394         if (control) {
1396             /* Snap to things, and also constrain to horizontal or vertical movement */
1398             for (unsigned int dim = 0; dim < 2; dim++) {
1399                 // When doing a constrained translation, all points will move in the same direction, i.e.
1400                 // either horizontally or vertically. Therefore we only have to specify the direction of
1401                 // the constraint-line once. The constraint lines are parallel, but might not be colinear.
1402                 // Therefore we will have to set the point through which the constraint-line runs
1403                 // individually for each point to be snapped; this will be handled however by _snapTransformed()
1404                 s.push_back(m.constrainedSnapTranslation(Inkscape::Snapper::SNAPPOINT_BBOX,
1405                                                          _bbox_points,
1406                                                          Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1407                                                          dxy));
1409                 s.push_back(m.constrainedSnapTranslation(Inkscape::Snapper::SNAPPOINT_NODE,
1410                                                          _snap_points,
1411                                                          Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1412                                                          dxy));
1413             }
1415         } else {
1417             // Let's leave this timer code here for a while. I'll probably need it in the near future (Diederik van Lierop)
1418             /* GTimeVal starttime;
1419             GTimeVal endtime;
1420                 g_get_current_time(&starttime); */
1422             /* Snap to things with no constraint */
1423                         s.push_back(m.freeSnapTranslation(Inkscape::Snapper::SNAPPOINT_BBOX, _bbox_points, dxy));
1424             s.push_back(m.freeSnapTranslation(Inkscape::Snapper::SNAPPOINT_NODE, _snap_points, dxy));
1426                 /*g_get_current_time(&endtime);
1427                 double elapsed = ((((double)endtime.tv_sec - starttime.tv_sec) * G_USEC_PER_SEC + (endtime.tv_usec - starttime.tv_usec))) / 1000.0;
1428                 std::cout << "Time spent snapping: " << elapsed << std::endl; */
1429         }
1431         /* Pick one */
1432         Inkscape::SnappedPoint best_snapped_point;
1433         g_assert(best_snapped_point.getDistance() == NR_HUGE);
1434         for (std::list<Inkscape::SnappedPoint>::const_iterator i = s.begin(); i != s.end(); i++) {
1435             if (i->getSnapped()) {
1436                 if (i->getDistance() < best_snapped_point.getDistance()) {
1437                     best_snapped_point = *i;
1438                     dxy = i->getTransformation();
1439                 }
1440             }
1441         }
1442         if (best_snapped_point.getSnapped()) {
1443             _desktop->snapindicator->set_new_snappoint(best_snapped_point);
1444         } else {
1445             // We didn't snap, so remove any previous snap indicator 
1446             _desktop->snapindicator->remove_snappoint();            
1447             if (control) {
1448                 // If we didn't snap, then we should still constrain horizontally or vertically
1449                 // (When we did snap, then this constraint has already been enforced by
1450                 // calling constrainedSnapTranslation() above)
1451                 if (fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y])) {
1452                     dxy[Geom::Y] = 0;
1453                 } else {
1454                     dxy[Geom::X] = 0;
1455                 }
1456             }
1457         }
1458     }
1459     
1460     Geom::Matrix const move((Geom::Translate(dxy)));
1461     Geom::Point const norm(0, 0);
1462     transform(from_2geom(move), from_2geom(norm));
1464     // status text
1465     GString *xs = SP_PX_TO_METRIC_STRING(dxy[Geom::X], _desktop->namedview->getDefaultMetric());
1466     GString *ys = SP_PX_TO_METRIC_STRING(dxy[Geom::Y], _desktop->namedview->getDefaultMetric());
1467     _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);
1468     g_string_free(xs, TRUE);
1469     g_string_free(ys, TRUE);
1472 // Given a location of a handle at the visual bounding box, find the corresponding location at the
1473 // geometrical bounding box
1474 NR::Point Inkscape::SelTrans::_getGeomHandlePos(NR::Point const &visual_handle_pos)
1476     if ( _snap_bbox_type == SPItem::GEOMETRIC_BBOX) {
1477         // When the selector tool is using geometric bboxes, then the handle is already
1478         // located at one of the geometric bbox corners
1479         return visual_handle_pos;
1480     }
1482     if (!_geometric_bbox) {
1483         //_getGeomHandlePos() can only be used after _geometric_bbox has been defined!
1484         return visual_handle_pos;
1485     }
1487     // Using the NR::Rect constructor below ensures that "min() < max()", which is important
1488     // because this will also hold for _bbox, and which is required for get_scale_transform_with_stroke()
1489     NR::Rect new_bbox = NR::Rect(_origin_for_bboxpoints, visual_handle_pos); // new visual bounding box
1490     // Please note that the new_bbox might in fact be just a single line, for example when stretching (in
1491     // which case the handle and origin will be aligned vertically or horizontally)
1492     NR::Point normalized_handle_pos = (visual_handle_pos - new_bbox.min()) * NR::scale(new_bbox.dimensions()).inverse();
1494     // Calculate the absolute affine while taking into account the scaling of the stroke width
1495     int transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1496     NR::Matrix abs_affine = get_scale_transform_with_stroke (*_bbox, _strokewidth, transform_stroke,
1497                     new_bbox.min()[NR::X], new_bbox.min()[NR::Y], new_bbox.max()[NR::X], new_bbox.max()[NR::Y]);
1499     // Calculate the scaled geometrical bbox
1500     NR::Rect new_geom_bbox = NR::Rect(_geometric_bbox->min() * abs_affine, _geometric_bbox->max() * abs_affine);
1501     // Find the location of the handle on this new geometrical bbox
1502     return normalized_handle_pos * NR::scale(new_geom_bbox.dimensions()) + new_geom_bbox.min(); //new position of the geometric handle
1505 NR::scale Inkscape::calcScaleFactors(NR::Point const &initial_point, NR::Point const &new_point, NR::Point const &origin, bool const skew)
1507     // Work out the new scale factors for the bbox
1509     NR::Point const initial_delta = initial_point - origin;
1510     NR::Point const new_delta = new_point - origin;
1511     NR::Point const offset = new_point - initial_point;
1512     NR::scale scale(1, 1);
1514     for ( unsigned int i = 0 ; i < 2 ; i++ ) {
1515         if ( fabs(initial_delta[i]) > 1e-6 ) {
1516             if (skew) {
1517                 scale[i] = offset[1-i] / initial_delta[i];
1518             } else {
1519                 scale[i] = new_delta[i] / initial_delta[i];
1520             }
1521         }
1522     }
1524     return scale;
1527 // Only for scaling/stretching
1528 NR::Point Inkscape::SelTrans::_calcAbsAffineDefault(NR::scale const default_scale)
1530     NR::Matrix abs_affine = NR::translate(-_origin) * NR::Matrix(default_scale) * NR::translate(_origin);
1531     NR::Point new_bbox_min = _approximate_bbox->min() * abs_affine;
1532     NR::Point new_bbox_max = _approximate_bbox->max() * abs_affine;
1534     int transform_stroke = false;
1535     gdouble strokewidth = 0;
1537     if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
1538         transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1539         strokewidth = _strokewidth;
1540     }
1542     _absolute_affine = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
1543                     new_bbox_min[NR::X], new_bbox_min[NR::Y], new_bbox_max[NR::X], new_bbox_max[NR::Y]);
1545     // return the new handle position
1546     return ( _point - _origin ) * default_scale + _origin;
1549 // Only for scaling/stretching
1550 NR::Point Inkscape::SelTrans::_calcAbsAffineGeom(NR::scale const geom_scale)
1552     _relative_affine = NR::Matrix(geom_scale);
1553     _absolute_affine = NR::translate(-_origin_for_specpoints) * _relative_affine * NR::translate(_origin_for_specpoints);
1555     bool const transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1556     NR::Rect visual_bbox = get_visual_bbox(_geometric_bbox, _absolute_affine, _strokewidth, transform_stroke);
1558     // return the new handle position
1559     return visual_bbox.min() + visual_bbox.dimensions() * NR::scale(_handle_x, _handle_y);
1563 /*
1564   Local Variables:
1565   mode:c++
1566   c-file-style:"stroustrup"
1567   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1568   indent-tabs-mode:nil
1569   fill-column:99
1570   End:
1571 */
1572 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :