Code

Warning and whitespace cleanup
[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"
55 #include "isnan.h" //temp fix.  make sure included last
57 static void sp_remove_handles(SPKnot *knot[], gint num);
59 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data);
60 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint state, gpointer data);
61 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data);
62 static void sp_sel_trans_handle_new_event(SPKnot *knot, NR::Point *position, guint32 state, gpointer data);
63 static gboolean sp_sel_trans_handle_request(SPKnot *knot, NR::Point *p, guint state, gboolean *data);
65 extern GdkPixbuf *handles[];
67 static gboolean sp_seltrans_handle_event(SPKnot *knot, GdkEvent *event, gpointer)
68 {
69     switch (event->type) {
70         case GDK_MOTION_NOTIFY:
71             break;
72         case GDK_KEY_PRESS:
73             if (get_group0_keyval (&event->key) == GDK_space) {
74                 /* stamping mode: both mode(show content and outline) operation with knot */
75                 if (!SP_KNOT_IS_GRABBED(knot)) {
76                     return FALSE;
77                 }
78                 SPDesktop *desktop = knot->desktop;
79                 Inkscape::SelTrans *seltrans = SP_SELECT_CONTEXT(desktop->event_context)->_seltrans;
80                 seltrans->stamp();
81                 return TRUE;
82             }
83             break;
84         default:
85             break;
86     }
88     return FALSE;
89 }
91 Inkscape::SelTrans::SelTrans(SPDesktop *desktop) :
92     _desktop(desktop),
93     _selcue(desktop),
94     _state(STATE_SCALE),
95     _show(SHOW_CONTENT),
96     _grabbed(false),
97     _show_handles(true),
98     _bbox(NR::Nothing()),
99     _approximate_bbox(NR::Nothing()),
100     _absolute_affine(NR::scale(1,1)),
101     _opposite(NR::Point(0,0)),
102     _opposite_for_specpoints(NR::Point(0,0)),
103     _opposite_for_bboxpoints(NR::Point(0,0)),
104     _origin_for_specpoints(NR::Point(0,0)),
105     _origin_for_bboxpoints(NR::Point(0,0)),
106     _chandle(NULL),
107     _stamp_cache(NULL),
108     _message_context(desktop->messageStack())
110     int prefs_bbox = prefs_get_int_attribute("tools", "bounding_box", 0);
111     _snap_bbox_type = (prefs_bbox ==0)?
112         SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
114     g_return_if_fail(desktop != NULL);
116     for (int i = 0; i < 8; i++) {
117         _shandle[i] = NULL;
118         _rhandle[i] = NULL;
119     }
121     _updateVolatileState();
122     _current_relative_affine.set_identity();
124     _center_is_set = false; // reread _center from items, or set to bbox midpoint
126     _updateHandles();
128     _selection = sp_desktop_selection(desktop);
130     _norm = sp_canvas_item_new(sp_desktop_controls(desktop),
131                                SP_TYPE_CTRL,
132                                "anchor", GTK_ANCHOR_CENTER,
133                                "mode", SP_CTRL_MODE_COLOR,
134                                "shape", SP_CTRL_SHAPE_BITMAP,
135                                "size", 13.0,
136                                "filled", TRUE,
137                                "fill_color", 0x00000000,
138                                "stroked", TRUE,
139                                "stroke_color", 0x000000a0,
140                                "pixbuf", handles[12],
141                                NULL);
143     _grip = sp_canvas_item_new(sp_desktop_controls(desktop),
144                                SP_TYPE_CTRL,
145                                "anchor", GTK_ANCHOR_CENTER,
146                                "mode", SP_CTRL_MODE_XOR,
147                                "shape", SP_CTRL_SHAPE_CROSS,
148                                "size", 7.0,
149                                "filled", TRUE,
150                                "fill_color", 0xffffff7f,
151                                "stroked", TRUE,
152                                "stroke_color", 0xffffffff,
153                                "pixbuf", handles[12],
154                                NULL);
156     sp_canvas_item_hide(_grip);
157     sp_canvas_item_hide(_norm);
159     for (int i = 0; i < 4; i++) {
160         _l[i] = sp_canvas_item_new(sp_desktop_controls(desktop), SP_TYPE_CTRLLINE, NULL);
161         sp_canvas_item_hide(_l[i]);
162     }
164     _sel_changed_connection = _selection->connectChanged(
165         sigc::mem_fun(*this, &Inkscape::SelTrans::_selChanged)
166         );
168     _sel_modified_connection = _selection->connectModified(
169         sigc::mem_fun(*this, &Inkscape::SelTrans::_selModified)
170         );
173 Inkscape::SelTrans::~SelTrans()
175     _sel_changed_connection.disconnect();
176     _sel_modified_connection.disconnect();
178     for (unsigned int i = 0; i < 8; i++) {
179         if (_shandle[i]) {
180             g_object_unref(G_OBJECT(_shandle[i]));
181             _shandle[i] = NULL;
182         }
183         if (_rhandle[i]) {
184             g_object_unref(G_OBJECT(_rhandle[i]));
185             _rhandle[i] = NULL;
186         }
187     }
188     if (_chandle) {
189         g_object_unref(G_OBJECT(_chandle));
190         _chandle = NULL;
191     }
193     if (_norm) {
194         gtk_object_destroy(GTK_OBJECT(_norm));
195         _norm = NULL;
196     }
197     if (_grip) {
198         gtk_object_destroy(GTK_OBJECT(_grip));
199         _grip = NULL;
200     }
201     for (int i = 0; i < 4; i++) {
202         if (_l[i]) {
203             gtk_object_destroy(GTK_OBJECT(_l[i]));
204             _l[i] = NULL;
205         }
206     }
208     for (unsigned i = 0; i < _items.size(); i++) {
209         sp_object_unref(SP_OBJECT(_items[i]), NULL);
210     }
212     _items.clear();
213     _items_const.clear();
214     _items_affines.clear();
215     _items_centers.clear();
218 void Inkscape::SelTrans::resetState()
220     _state = STATE_SCALE;
223 void Inkscape::SelTrans::increaseState()
225     if (_state == STATE_SCALE) {
226         _state = STATE_ROTATE;
227     } else {
228         _state = STATE_SCALE;
229     }
231     _center_is_set = true; // no need to reread center
233     _updateHandles();
236 void Inkscape::SelTrans::setCenter(NR::Point const &p)
238     _center = p;
239     _center_is_set = true;
241     // Write the new center position into all selected items
242     for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
243         SPItem *it = (SPItem*)SP_OBJECT(l->data);
244         it->setCenter(p);
245         // only set the value; updating repr and document_done will be done once, on ungrab
246     }
248     _updateHandles();
251 void Inkscape::SelTrans::grab(NR::Point const &p, gdouble x, gdouble y, bool show_handles)
253     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
255     g_return_if_fail(!_grabbed);
257     _grabbed = true;
258     _show_handles = show_handles;
259     _updateVolatileState();
260     _current_relative_affine.set_identity();
262     _changed = false;
264     if (_empty) {
265         return;
266     }
268     for (GSList const *l = selection->itemList(); l; l = l->next) {
269         SPItem *it = (SPItem *)sp_object_ref(SP_OBJECT(l->data), NULL);
270         _items.push_back(it);
271         _items_const.push_back(it);
272         _items_affines.push_back(sp_item_i2d_affine(it));
273         _items_centers.push_back(it->getCenter()); // for content-dragging, we need to remember original centers
274     }
276     _handle_x = x;
277     _handle_y = y;
279     // The selector tool should snap the bbox, special snappoints, and path nodes
280     // (The special points are the handles, center, rotation axis, font baseline, ends of spiral, etc.)
282     // First, determine the bounding box for snapping ...
283     _bbox = selection->bounds(_snap_bbox_type);
284     _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX); // Used for correctly scaling the strokewidth
285     _geometric_bbox = selection->bounds(SPItem::GEOMETRIC_BBOX);
286     _point = p;
287     if (_geometric_bbox) {
288         _point_geom = _geometric_bbox->min() + _geometric_bbox->dimensions() * NR::scale(x, y);
289     } else {
290         _point_geom = p;
291     }
293     // Next, get all points to consider for snapping
294     SnapManager const &m = _desktop->namedview->snap_manager;
295     _snap_points = selection->getSnapPoints(m.getIncludeItemCenter());
296     std::vector<NR::Point> snap_points_hull = selection->getSnapPointsConvexHull();
297     if (_snap_points.size() > 100) {
298         /* Snapping a huge number of nodes will take way too long, so limit the number of snappable nodes
299         An average user would rarely ever try to snap such a large number of nodes anyway, because
300         (s)he could hardly discern which node would be snapping */
301         _snap_points = snap_points_hull;
302         // Unfortunately, by now we will have lost the font-baseline snappoints :-(
303     }
305     // Find bbox hulling all special points, which excludes stroke width. Here we need to include the
306     // path nodes, for example because a rectangle which has been converted to a path doesn't have
307     // any other special points
308     NR::Rect snap_points_bbox;
309     if ( snap_points_hull.empty() == false ) {
310         std::vector<NR::Point>::iterator i = snap_points_hull.begin();
311         snap_points_bbox = NR::Rect(*i, *i);
312         i++;
313         while (i != snap_points_hull.end()) {
314             snap_points_bbox.expandTo(*i);
315             i++;
316         }
317     }
319     _bbox_points.clear();
320     if (_bbox) {
321         // ... and add the bbox corners to _bbox_points
322         for ( unsigned i = 0 ; i < 4 ; i++ ) {
323             _bbox_points.push_back(_bbox->corner(i));
324         }
325         // There are two separate "opposites" (i.e. opposite w.r.t. the handle being dragged):
326         //  - one for snapping the boundingbox, which can be either visual or geometric
327         //  - one for snapping the special points
328         // The "opposite" in case of a geometric boundingbox always coincides with the "opposite" for the special points
329         // These distinct "opposites" are needed in the snapmanager to avoid bugs such as #sf1540195 (in which
330         // a box is caught between two guides)
331         _opposite_for_bboxpoints = _bbox->min() + _bbox->dimensions() * NR::scale(1-x, 1-y);
332         _opposite_for_specpoints = snap_points_bbox.min() + snap_points_bbox.dimensions() * NR::scale(1-x, 1-y);
333         _opposite = _opposite_for_bboxpoints;
334     }
336     // The lines below are usefull for debugging any snapping issues, as they'll spit out all points that are considered for snapping
338     /*std::cout << "Number of snap points:  " << _snap_points.size() << std::endl;
339     for (std::vector<NR::Point>::const_iterator i = _snap_points.begin(); i != _snap_points.end(); i++)
340     {
341         std::cout << "    " << *i << std::endl;
342     }
344     std::cout << "Number of bbox points:  " << _bbox_points.size() << std::endl;
345     for (std::vector<NR::Point>::const_iterator i = _bbox_points.begin(); i != _bbox_points.end(); i++)
346     {
347         std::cout << "    " << *i << std::endl;
348     }*/
350     if ((x != -1) && (y != -1)) {
351         sp_canvas_item_show(_norm);
352         sp_canvas_item_show(_grip);
353     }
355     if (_show == SHOW_OUTLINE) {
356         for (int i = 0; i < 4; i++)
357             sp_canvas_item_show(_l[i]);
358     }
360     _updateHandles();
361     g_return_if_fail(_stamp_cache == NULL);
364 void Inkscape::SelTrans::transform(NR::Matrix const &rel_affine, NR::Point const &norm)
366     g_return_if_fail(_grabbed);
367     g_return_if_fail(!_empty);
369     NR::Matrix const affine( NR::translate(-norm) * rel_affine * NR::translate(norm) );
371     if (_show == SHOW_CONTENT) {
372         // update the content
373         for (unsigned i = 0; i < _items.size(); i++) {
374             SPItem &item = *_items[i];
375             NR::Matrix const &prev_transform = _items_affines[i];
376             sp_item_set_i2d_affine(&item, prev_transform * affine);
377         }
378     } else {
379         if (_bbox) {
380             NR::Point p[4];
381             /* update the outline */
382             for (unsigned i = 0 ; i < 4 ; i++) {
383                 p[i] = _bbox->corner(i) * affine;
384             }
385             for (unsigned i = 0 ; i < 4 ; i++) {
386                 sp_ctrlline_set_coords(SP_CTRLLINE(_l[i]), p[i], p[(i+1)%4]);
387             }
388         }
389     }
391     _current_relative_affine = affine;
392     _changed = true;
393     _updateHandles();
396 void Inkscape::SelTrans::ungrab()
398     g_return_if_fail(_grabbed);
399     _grabbed = false;
400     _show_handles = true;
402     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
403     _updateVolatileState();
405     for (unsigned i = 0; i < _items.size(); i++) {
406         sp_object_unref(SP_OBJECT(_items[i]), NULL);
407     }
409     sp_canvas_item_hide(_norm);
410     sp_canvas_item_hide(_grip);
412     if (_show == SHOW_OUTLINE) {
413         for (int i = 0; i < 4; i++)
414             sp_canvas_item_hide(_l[i]);
415     }
417     if (_stamp_cache) {
418         g_slist_free(_stamp_cache);
419         _stamp_cache = NULL;
420     }
422     _message_context.clear();
424     if (!_empty && _changed) {
425         sp_selection_apply_affine(selection, _current_relative_affine, (_show == SHOW_OUTLINE)? true : false);
426         if (_center) {
427             *_center *= _current_relative_affine;
428             _center_is_set = true;
429         }
431 // If dragging showed content live, sp_selection_apply_affine cannot change the centers
432 // appropriately - it does not know the original positions of the centers (all objects already have
433 // the new bboxes). So we need to reset the centers from our saved array.
434         if (_show != SHOW_OUTLINE && !_current_relative_affine.is_translation()) {
435             for (unsigned i = 0; i < _items_centers.size(); i++) {
436                 SPItem *currentItem = _items[i];
437                 if (currentItem->isCenterSet()) { // only if it's already set
438                     currentItem->setCenter (_items_centers[i] * _current_relative_affine);
439                     SP_OBJECT(currentItem)->updateRepr();
440                 }
441             }
442         }
444         _items.clear();
445         _items_const.clear();
446         _items_affines.clear();
447         _items_centers.clear();
449         if (_current_relative_affine.is_translation()) {
450             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
451                              _("Move"));
452         } else if (_current_relative_affine.is_scale()) {
453             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
454                              _("Scale"));
455         } else if (_current_relative_affine.is_rotation()) {
456             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
457                              _("Rotate"));
458         } else {
459             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
460                              _("Skew"));
461         }
463     } else {
465         if (_center_is_set) {
466             // we were dragging center; update reprs and commit undoable action
467             for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
468                 SPItem *it = (SPItem*)SP_OBJECT(l->data);
469                 SP_OBJECT(it)->updateRepr();
470             }
471             sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
472                             _("Set center"));
473         }
475         _items.clear();
476         _items_const.clear();
477         _items_affines.clear();
478         _items_centers.clear();
479         _updateHandles();
480     }
483 /* fixme: This is really bad, as we compare positions for each stamp (Lauris) */
484 /* fixme: IMHO the best way to keep sort cache would be to implement timestamping at last */
486 void Inkscape::SelTrans::stamp()
488     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
490     bool fixup = !_grabbed;
491     if ( fixup && _stamp_cache ) {
492         // TODO - give a proper fix. Simple temproary work-around for the grab() issue
493         g_slist_free(_stamp_cache);
494         _stamp_cache = NULL;
495     }
497     /* stamping mode */
498     if (!_empty) {
499         GSList *l;
500         if (_stamp_cache) {
501             l = _stamp_cache;
502         } else {
503             /* Build cache */
504             l  = g_slist_copy((GSList *) selection->itemList());
505             l  = g_slist_sort(l, (GCompareFunc) sp_object_compare_position);
506             _stamp_cache = l;
507         }
509         while (l) {
510             SPItem *original_item = SP_ITEM(l->data);
511             Inkscape::XML::Node *original_repr = SP_OBJECT_REPR(original_item);
513             // remember the position of the item
514             gint pos = original_repr->position();
515             // remember parent
516             Inkscape::XML::Node *parent = sp_repr_parent(original_repr);
518             Inkscape::XML::Node *copy_repr = original_repr->duplicate(parent->document());
520             // add the new repr to the parent
521             parent->appendChild(copy_repr);
522             // move to the saved position
523             copy_repr->setPosition(pos > 0 ? pos : 0);
525             SPItem *copy_item = (SPItem *) sp_desktop_document(_desktop)->getObjectByRepr(copy_repr);
527             NR::Matrix const *new_affine;
528             if (_show == SHOW_OUTLINE) {
529                 NR::Matrix const i2d(sp_item_i2d_affine(original_item));
530                 NR::Matrix const i2dnew( i2d * _current_relative_affine );
531                 sp_item_set_i2d_affine(copy_item, i2dnew);
532                 new_affine = &copy_item->transform;
533             } else {
534                 new_affine = &original_item->transform;
535             }
537             sp_item_write_transform(copy_item, copy_repr, *new_affine);
539             if ( copy_item->isCenterSet() && _center ) {
540                 copy_item->setCenter(*_center * _current_relative_affine);
541             }
543             Inkscape::GC::release(copy_repr);
544             l = l->next;
545         }
546         sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
547                          _("Stamp"));
548     }
550     if ( fixup && _stamp_cache ) {
551         // TODO - give a proper fix. Simple temproary work-around for the grab() issue
552         g_slist_free(_stamp_cache);
553         _stamp_cache = NULL;
554     }
557 void Inkscape::SelTrans::_updateHandles()
559     if ( !_show_handles || _empty )
560     {
561         sp_remove_handles(_shandle, 8);
562         sp_remove_handles(_rhandle, 8);
563         sp_remove_handles(&_chandle, 1);
564         return;
565     }
567     // center handle
568     if ( _chandle == NULL ) {
569         _chandle = sp_knot_new(_desktop, _("<b>Center</b> of rotation and skewing: drag to reposition; scaling with Shift also uses this center"));
571         _chandle->setShape (SP_CTRL_SHAPE_BITMAP);
572         _chandle->setSize (13);
573         _chandle->setAnchor (handle_center.anchor);
574         _chandle->setMode (SP_CTRL_MODE_XOR);
575         _chandle->setFill(0x00000000, 0x00000000, 0x00000000);
576         _chandle->setStroke(0x000000ff, 0xff0000b0, 0xff0000b0);
577         _chandle->setPixbuf(handles[handle_center.control]);
578         sp_knot_update_ctrl(_chandle);
580         g_signal_connect(G_OBJECT(_chandle), "request",
581                          G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle_center);
582         g_signal_connect(G_OBJECT(_chandle), "moved",
583                          G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle_center);
584         g_signal_connect(G_OBJECT(_chandle), "grabbed",
585                          G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle_center);
586         g_signal_connect(G_OBJECT(_chandle), "ungrabbed",
587                          G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle_center);
588         g_signal_connect(G_OBJECT(_chandle), "clicked",
589                          G_CALLBACK(sp_sel_trans_handle_click), (gpointer) &handle_center);
590     }
592     sp_remove_handles(&_chandle, 1);
593     if ( _state == STATE_SCALE ) {
594         sp_remove_handles(_rhandle, 8);
595         _showHandles(_shandle, handles_scale, 8,
596                     _("<b>Squeeze or stretch</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"),
597                     _("<b>Scale</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"));
598     } else {
599         sp_remove_handles(_shandle, 8);
600         _showHandles(_rhandle, handles_rotate, 8,
601                     _("<b>Skew</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to skew around the opposite side"),
602                     _("<b>Rotate</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to rotate around the opposite corner"));
603     }
605     if (!_center_is_set) {
606         _center = _desktop->selection->center();
607         _center_is_set = true;
608     }
610     if ( _state == STATE_SCALE || !_center ) {
611         sp_knot_hide(_chandle);
612     } else {
613         sp_knot_show(_chandle);
614         sp_knot_moveto(_chandle, &*_center);
615     }
618 void Inkscape::SelTrans::_updateVolatileState()
620     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
621     _empty = selection->isEmpty();
623     if (_empty) {
624         return;
625     }
627     //Update the bboxes
628     _bbox = selection->bounds(_snap_bbox_type);
629     _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX);
631     if (!_bbox) {
632         _empty = true;
633         return;
634     }
636     _strokewidth = stroke_average_width (selection->itemList());
639 static void sp_remove_handles(SPKnot *knot[], gint num)
641     for (int i = 0; i < num; i++) {
642         if (knot[i] != NULL) {
643             sp_knot_hide(knot[i]);
644         }
645     }
648 void Inkscape::SelTrans::_showHandles(SPKnot *knot[], SPSelTransHandle const handle[], gint num,
649                              gchar const *even_tip, gchar const *odd_tip)
651     g_return_if_fail( !_empty );
653     for (int i = 0; i < num; i++) {
654         if (knot[i] == NULL) {
655             knot[i] = sp_knot_new(_desktop, i % 2 ? even_tip : odd_tip);
657             knot[i]->setShape (SP_CTRL_SHAPE_BITMAP);
658             knot[i]->setSize (13);
659             knot[i]->setAnchor (handle[i].anchor);
660             knot[i]->setMode (SP_CTRL_MODE_XOR);
661             knot[i]->setFill(0x000000ff, 0x00ff6600, 0x00ff6600); // inversion, green, green
662             knot[i]->setStroke(0x000000ff, 0x000000ff, 0x000000ff); // inversion
663             knot[i]->setPixbuf(handles[handle[i].control]);
664             sp_knot_update_ctrl(knot[i]);
666             g_signal_connect(G_OBJECT(knot[i]), "request",
667                              G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle[i]);
668             g_signal_connect(G_OBJECT(knot[i]), "moved",
669                              G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle[i]);
670             g_signal_connect(G_OBJECT(knot[i]), "grabbed",
671                              G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle[i]);
672             g_signal_connect(G_OBJECT(knot[i]), "ungrabbed",
673                              G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle[i]);
674             g_signal_connect(G_OBJECT(knot[i]), "event", G_CALLBACK(sp_seltrans_handle_event), (gpointer) &handle[i]);
675         }
676         sp_knot_show(knot[i]);
678         NR::Point const handle_pt(handle[i].x, handle[i].y);
679         // shouldn't have nullary bbox, but knots
680         g_assert(_bbox);
681         NR::Point p( _bbox->min()
682                      + ( _bbox->dimensions()
683                          * NR::scale(handle_pt) ) );
685         sp_knot_moveto(knot[i], &p);
686     }
689 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data)
691     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleGrab(
692         knot, state, *(SPSelTransHandle const *) data
693         );
696 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint /*state*/, gpointer /*data*/)
698     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->ungrab();
701 static void sp_sel_trans_handle_new_event(SPKnot *knot, NR::Point *position, guint state, gpointer data)
703     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleNewEvent(
704         knot, position, state, *(SPSelTransHandle const *) data
705         );
708 static gboolean sp_sel_trans_handle_request(SPKnot *knot, NR::Point *position, guint state, gboolean *data)
710     return SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleRequest(
711         knot, position, state, *(SPSelTransHandle const *) data
712         );
715 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data)
717     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleClick(
718         knot, state, *(SPSelTransHandle const *) data
719         );
722 void Inkscape::SelTrans::handleClick(SPKnot */*knot*/, guint state, SPSelTransHandle const &handle)
724     switch (handle.anchor) {
725         case GTK_ANCHOR_CENTER:
726             if (state & GDK_SHIFT_MASK) {
727                 // Unset the  center position for all selected items
728                 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
729                     SPItem *it = (SPItem*)(SP_OBJECT(l->data));
730                     it->unsetCenter();
731                     SP_OBJECT(it)->updateRepr();
732                     _center_is_set = false;  // center has changed
733                     _updateHandles();
734                 }
735                 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
736                                         _("Reset center"));
737             }
738             break;
739         default:
740             break;
741     }
744 void Inkscape::SelTrans::handleGrab(SPKnot *knot, guint /*state*/, SPSelTransHandle const &handle)
746     switch (handle.anchor) {
747         case GTK_ANCHOR_CENTER:
748             g_object_set(G_OBJECT(_grip),
749                          "shape", SP_CTRL_SHAPE_BITMAP,
750                          "size", 13.0,
751                          NULL);
752             sp_canvas_item_show(_grip);
753             break;
754         default:
755             g_object_set(G_OBJECT(_grip),
756                          "shape", SP_CTRL_SHAPE_CROSS,
757                          "size", 7.0,
758                          NULL);
759             sp_canvas_item_show(_norm);
760             sp_canvas_item_show(_grip);
762             break;
763     }
765     grab(sp_knot_position(knot), handle.x, handle.y, FALSE);
769 void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, NR::Point *position, guint state, SPSelTransHandle const &handle)
771     if (!SP_KNOT_IS_GRABBED(knot)) {
772         return;
773     }
775     // in case items have been unhooked from the document, don't
776     // try to continue processing events for them.
777     for (unsigned int i = 0; i < _items.size(); i++) {
778         if (!SP_OBJECT_DOCUMENT(SP_OBJECT(_items[i])) ) {
779             return;
780         }
781     }
783     handle.action(this, handle, *position, state);
787 gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, NR::Point *position, guint state, SPSelTransHandle const &handle)
789     if (!SP_KNOT_IS_GRABBED(knot)) {
790         return TRUE;
791     }
793     knot->desktop->setPosition(*position);
795     // When holding shift while rotating or skewing, the transformation will be
796     // relative to the point opposite of the handle; otherwise it will be relative
797     // to the center as set for the selection
798     if ((!(state & GDK_SHIFT_MASK) == !(_state == STATE_ROTATE)) && (&handle != &handle_center)) {
799         _origin = _opposite;
800         _origin_for_bboxpoints = _opposite_for_bboxpoints;
801         _origin_for_specpoints = _opposite_for_specpoints;
802     } else if (_center) {
803         _origin = *_center;
804         _origin_for_bboxpoints = *_center;
805         _origin_for_specpoints = *_center;
806     } else {
807         // FIXME
808         return TRUE;
809     }
810     if (handle.request(this, handle, *position, state)) {
811         sp_knot_set_position(knot, position, state);
812         SP_CTRL(_grip)->moveto(*position);
813         SP_CTRL(_norm)->moveto(_origin);
814     }
816     return TRUE;
820 void Inkscape::SelTrans::_selChanged(Inkscape::Selection */*selection*/)
822     if (!_grabbed) {
823         // reread in case it changed on the fly:
824         int prefs_bbox = prefs_get_int_attribute("tools", "bounding_box", 0);
825          _snap_bbox_type = (prefs_bbox ==0)?
826             SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
827         //SPItem::APPROXIMATE_BBOX will be replaced by SPItem::VISUAL_BBOX, as soon as the latter is implemented properly
829         _updateVolatileState();
830         _current_relative_affine.set_identity();
831         _center_is_set = false; // center(s) may have changed
832         _updateHandles();
833     }
836 void Inkscape::SelTrans::_selModified(Inkscape::Selection */*selection*/, guint /*flags*/)
838     if (!_grabbed) {
839         _updateVolatileState();
840         _current_relative_affine.set_identity();
842         // reset internal flag
843         _changed = false;
845         _center_is_set = false;  // center(s) may have changed
847         _updateHandles();
848     }
851 /*
852  * handlers for handle move-request
853  */
855 /** Returns -1 or 1 according to the sign of x.  Returns 1 for 0 and NaN. */
856 static double sign(double const x)
858     return ( x < 0
859              ? -1
860              : 1 );
863 gboolean sp_sel_trans_scale_request(Inkscape::SelTrans *seltrans,
864                                     SPSelTransHandle const &, NR::Point &pt, guint state)
866     return seltrans->scaleRequest(pt, state);
869 gboolean sp_sel_trans_stretch_request(Inkscape::SelTrans *seltrans,
870                                       SPSelTransHandle const &handle, NR::Point &pt, guint state)
872     return seltrans->stretchRequest(handle, pt, state);
875 gboolean sp_sel_trans_skew_request(Inkscape::SelTrans *seltrans,
876                                    SPSelTransHandle const &handle, NR::Point &pt, guint state)
878     return seltrans->skewRequest(handle, pt, state);
881 gboolean sp_sel_trans_rotate_request(Inkscape::SelTrans *seltrans,
882                                      SPSelTransHandle const &, NR::Point &pt, guint state)
884     return seltrans->rotateRequest(pt, state);
887 gboolean sp_sel_trans_center_request(Inkscape::SelTrans *seltrans,
888                                      SPSelTransHandle const &, NR::Point &pt, guint state)
890     return seltrans->centerRequest(pt, state);
893 gboolean Inkscape::SelTrans::scaleRequest(NR::Point &pt, guint state)
896     // Calculate the scale factors, which can be either visual or geometric
897     // depending on which type of bbox is currently being used (see preferences -> selector tool)
898     NR::scale default_scale = calcScaleFactors(_point, pt, _origin);
900     // Find the scale factors for the geometric bbox
901     NR::Point pt_geom = _getGeomHandlePos(pt);
902     NR::scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
904     _absolute_affine = NR::identity(); //Initialize the scaler
906     if (state & GDK_MOD1_MASK) { // scale by an integer multiplier/divider
907         // We're scaling either the visual or the geometric bbox here (see the comment above)
908         for ( unsigned int i = 0 ; i < 2 ; i++ ) {
909             if (fabs(default_scale[i]) > 1) {
910                 default_scale[i] = round(default_scale[i]);
911             } else if (default_scale[i] != 0) {
912                 default_scale[i] = 1/round(1/(MIN(default_scale[i], 10)));
913             }
914         }
915         // Update the knot position
916         pt = _calcAbsAffineDefault(default_scale);
917         // When scaling by an integer, snapping is not needed
918     } else {
919         // In all other cases we should try to snap now
920         SnapManager &m = _desktop->namedview->snap_manager;
921         m.setup(NULL, _items_const);
923         Inkscape::SnappedPoint bb, sn;
924         NR::Coord bd(NR_HUGE);
925         NR::Coord sd(NR_HUGE);
927         if ((state & GDK_CONTROL_MASK) || _desktop->isToolboxButtonActive ("lock")) {
928             // Scale is locked to a 1:1 aspect ratio, so that s[X] must be made to equal s[Y].
929             //
930             // The aspect-ratio must be locked before snapping
931             if (fabs(default_scale[NR::X]) > fabs(default_scale[NR::Y])) {
932                 default_scale[NR::X] = fabs(default_scale[NR::Y]) * sign(default_scale[NR::X]);
933                 geom_scale[NR::X] = fabs(geom_scale[NR::Y]) * sign(geom_scale[NR::X]);
934             } else {
935                 default_scale[NR::Y] = fabs(default_scale[NR::X]) * sign(default_scale[NR::Y]);
936                 geom_scale[NR::Y] = fabs(geom_scale[NR::X]) * sign(geom_scale[NR::Y]);
937             }
939             // Snap along a suitable constraint vector from the origin.
940             bb = m.constrainedSnapScale(Snapper::SNAPPOINT_BBOX, _bbox_points, default_scale, _origin_for_bboxpoints);
941             sn = m.constrainedSnapScale(Snapper::SNAPPOINT_NODE, _snap_points, geom_scale, _origin_for_specpoints);
943             /* Choose the smaller difference in scale.  Since s[X] == s[Y] we can
944             ** just compare difference in s[X].
945             */
946             bd = bb.getSnapped() ? fabs(bb.getTransformation()[NR::X] - default_scale[NR::X]) : NR_HUGE;
947             sd = sn.getSnapped() ? fabs(sn.getTransformation()[NR::X] - geom_scale[NR::X]) : NR_HUGE;
948         } else {
949             /* Scale aspect ratio is unlocked */
950             bb = m.freeSnapScale(Snapper::SNAPPOINT_BBOX, _bbox_points, default_scale, _origin_for_bboxpoints);
951             sn = m.freeSnapScale(Snapper::SNAPPOINT_NODE, _snap_points, geom_scale, _origin_for_specpoints);
953             /* Pick the snap that puts us closest to the original scale */
954             bd = bb.getSnapped() ? fabs(NR::L2(bb.getTransformation()) - NR::L2(default_scale.point())) : NR_HUGE;
955             sd = sn.getSnapped() ? fabs(NR::L2(sn.getTransformation()) - NR::L2(geom_scale.point())) : NR_HUGE;
956         }
958         if (!(bb.getSnapped() || sn.getSnapped())) {
959             // We didn't snap at all! Don't update the handle position, just calculate the new transformation
960             _calcAbsAffineDefault(default_scale);
961             _desktop->snapindicator->remove_snappoint();
962         } else if (bd < sd) {
963             // We snapped the bbox (which is either visual or geometric)
964             _desktop->snapindicator->set_new_snappoint(bb);
965             default_scale = NR::scale(bb.getTransformation());
966             // Calculate the new transformation and update the handle position
967             pt = _calcAbsAffineDefault(default_scale);
968         } else {
969             _desktop->snapindicator->set_new_snappoint(sn);
970             // We snapped the special points (e.g. nodes), which are not at the visual bbox
971             // The handle location however (pt) might however be at the visual bbox, so we
972             // will have to calculate pt taking the stroke width into account
973             geom_scale = NR::scale(sn.getTransformation());
974             pt = _calcAbsAffineGeom(geom_scale);
975         }
976     }
978     /* Status text */
979     _message_context.setF(Inkscape::NORMAL_MESSAGE,
980                           _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
981                           100 * _absolute_affine[0], 100 * _absolute_affine[3]);
983     return TRUE;
986 gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, NR::Point &pt, guint state)
988     NR::Dim2 axis, perp;
989     switch (handle.cursor) {
990         case GDK_TOP_SIDE:
991         case GDK_BOTTOM_SIDE:
992             axis = NR::Y;
993             perp = NR::X;
994             break;
995         case GDK_LEFT_SIDE:
996         case GDK_RIGHT_SIDE:
997             axis = NR::X;
998             perp = NR::Y;
999             break;
1000         default:
1001             g_assert_not_reached();
1002             return TRUE;
1003     };
1005     // Calculate the scale factors, which can be either visual or geometric
1006     // depending on which type of bbox is currently being used (see preferences -> selector tool)
1007     NR::scale default_scale = calcScaleFactors(_point, pt, _origin);
1008     default_scale[perp] = 1;
1010     // Find the scale factors for the geometric bbox
1011     NR::Point pt_geom = _getGeomHandlePos(pt);
1012     NR::scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
1013     geom_scale[perp] = 1;
1015     _absolute_affine = NR::identity(); //Initialize the scaler
1017     if (state & GDK_MOD1_MASK) { // stretch by an integer multiplier/divider
1018         if (fabs(default_scale[axis]) > 1) {
1019             default_scale[axis] = round(default_scale[axis]);
1020         } else if (default_scale[axis] != 0) {
1021             default_scale[axis] = 1/round(1/(MIN(default_scale[axis], 10)));
1022         }
1023         // Calculate the new transformation and update the handle position
1024         pt = _calcAbsAffineDefault(default_scale);
1025         // When stretching by an integer, snapping is not needed
1026     } else {
1027         // In all other cases we should try to snap now
1029         SnapManager &m = _desktop->namedview->snap_manager;
1030         m.setup(NULL, _items_const);
1032         Inkscape::SnappedPoint bb, sn;
1033         g_assert(bb.getSnapped() == false); // Check initialization to catch any regression
1034         NR::Coord bd(NR_HUGE);
1035         NR::Coord sd(NR_HUGE);
1037         bool symmetrical = state & GDK_CONTROL_MASK;
1039         bb = m.constrainedSnapStretch(Snapper::SNAPPOINT_BBOX, _bbox_points, default_scale[axis], _origin_for_bboxpoints, axis, symmetrical);
1040         sn = m.constrainedSnapStretch(Snapper::SNAPPOINT_NODE, _snap_points, geom_scale[axis], _origin_for_specpoints, axis, symmetrical);
1042         if (bb.getSnapped()) {
1043             // We snapped the bbox (which is either visual or geometric)
1044             bd = fabs(bb.getTransformation()[axis] - default_scale[axis]);
1045             default_scale[axis] = bb.getTransformation()[axis];
1046         }
1048         if (sn.getSnapped()) {
1049             sd = fabs(sn.getTransformation()[axis] - geom_scale[axis]);
1050             geom_scale[axis] = sn.getTransformation()[axis];
1051         }
1053         if (symmetrical) {
1054             // on ctrl, apply symmetrical scaling instead of stretching
1055             // Preserve aspect ratio, but never flip in the dimension not being edited (by using fabs())
1056             default_scale[perp] = fabs(default_scale[axis]);
1057             geom_scale[perp] = fabs(geom_scale[axis]);
1058         }
1060         if (!(bb.getSnapped() || sn.getSnapped())) {
1061             // We didn't snap at all! Don't update the handle position, just calculate the new transformation
1062             _calcAbsAffineDefault(default_scale);
1063             _desktop->snapindicator->remove_snappoint();
1064         } else if (bd < sd) {
1065             _desktop->snapindicator->set_new_snappoint(bb);
1066             // Calculate the new transformation and update the handle position
1067             pt = _calcAbsAffineDefault(default_scale);
1068         } else {
1069             _desktop->snapindicator->set_new_snappoint(sn);
1070             // We snapped the special points (e.g. nodes), which are not at the visual bbox
1071             // The handle location however (pt) might however be at the visual bbox, so we
1072             // will have to calculate pt taking the stroke width into account
1073             pt = _calcAbsAffineGeom(geom_scale);
1074         }
1075     }
1077     // status text
1078     _message_context.setF(Inkscape::NORMAL_MESSAGE,
1079                           _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1080                           100 * _absolute_affine[0], 100 * _absolute_affine[3]);
1082     return TRUE;
1085 gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, NR::Point &pt, guint state)
1087     /* When skewing (or rotating):
1088      * 1) the stroke width will not change. This makes life much easier because we don't have to
1089      *    account for that (like for scaling or stretching). As a consequence, all points will
1090      *    have the same origin for the transformation and for the snapping.
1091      * 2) When holding shift, the transformation will be relative to the point opposite of
1092      *    the handle; otherwise it will be relative to the center as set for the selection
1093      */
1095     NR::Dim2 dim_a;
1096     NR::Dim2 dim_b;
1098     switch (handle.cursor) {
1099         case GDK_SB_H_DOUBLE_ARROW:
1100             dim_a = NR::Y;
1101             dim_b = NR::X;
1102             break;
1103         case GDK_SB_V_DOUBLE_ARROW:
1104             dim_a = NR::X;
1105             dim_b = NR::Y;
1106             break;
1107         default:
1108             g_assert_not_reached();
1109             abort();
1110             break;
1111     }
1113     NR::Point const initial_delta = _point - _origin;
1115     if (fabs(initial_delta[dim_a]) < 1e-15) {
1116         return false;
1117     }
1119     // Calculate the scale factors, which can be either visual or geometric
1120     // depending on which type of bbox is currently being used (see preferences -> selector tool)
1121     NR::scale scale = calcScaleFactors(_point, pt, _origin, false);
1122     NR::scale skew = calcScaleFactors(_point, pt, _origin, true);
1123     scale[dim_b] = 1;
1124     skew[dim_b] = 1;
1126     if (fabs(scale[dim_a]) < 1) {
1127         // Prevent shrinking of the selected object, while allowing mirroring
1128         scale[dim_a] = sign(scale[dim_a]);
1129     } else {
1130         // Allow expanding of the selected object by integer multiples
1131         scale[dim_a] = floor(scale[dim_a] + 0.5);
1132     }
1134     double radians = atan(skew[dim_a] / scale[dim_a]);
1136     if (state & GDK_CONTROL_MASK) {
1137         // Snap to defined angle increments
1138         int snaps = prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12);
1139         if (snaps) {
1140             double sections = floor(radians * snaps / M_PI + .5);
1141             if (fabs(sections) >= snaps / 2) {
1142                 sections = sign(sections) * (snaps / 2 - 1);
1143             }
1144             radians = (M_PI / snaps) * sections;
1145         }
1146         skew[dim_a] = tan(radians) * scale[dim_a];
1147     } else {
1148         // Snap to objects, grids, guides
1150         SnapManager &m = _desktop->namedview->snap_manager;
1151         m.setup(NULL, _items_const);
1153         //TODO: While skewing, scaling in the opposite direction by integer multiples is also allowed. This is not handled though by freeSnapSkew / _snapTransformed yet!
1154         //TODO: We need a constrainedSnapSkew instead of a freeSnapSkew
1155         Inkscape::SnappedPoint bb = m.freeSnapSkew(Inkscape::Snapper::SNAPPOINT_BBOX, _bbox_points, skew[dim_a], _origin, dim_b);
1156         Inkscape::SnappedPoint sn = m.freeSnapSkew(Inkscape::Snapper::SNAPPOINT_NODE, _snap_points, skew[dim_a], _origin, dim_b);
1158         if (bb.getSnapped() || sn.getSnapped()) {
1159             // We snapped something, so change the skew to reflect it
1160             NR::Coord const bd = bb.getSnapped() ? bb.getTransformation()[dim_b] : NR_HUGE;
1161             NR::Coord const sd = sn.getSnapped() ? sn.getTransformation()[dim_b] : NR_HUGE;
1162             if (bd < sd) {
1163                 _desktop->snapindicator->set_new_snappoint(bb);
1164                 skew[dim_a] = bd;
1165             } else {
1166                 _desktop->snapindicator->set_new_snappoint(sn);
1167                 skew[dim_a] = sd;
1168             }
1169         } else {
1170             _desktop->snapindicator->remove_snappoint();
1171         }
1172     }
1174     // Update the handle position
1175     pt[dim_b] = initial_delta[dim_a] * skew[dim_a] + _point[dim_b];
1176     pt[dim_a] = initial_delta[dim_a] * scale[dim_a] + _origin[dim_a];
1178     // Calculate the relative affine
1179     _relative_affine = NR::identity();
1180     _relative_affine[2*dim_a + dim_a] = (pt[dim_a] - _origin[dim_a]) / initial_delta[dim_a];
1181     _relative_affine[2*dim_a + (dim_b)] = (pt[dim_b] - _point[dim_b]) / initial_delta[dim_a];
1182     _relative_affine[2*(dim_b) + (dim_a)] = 0;
1183     _relative_affine[2*(dim_b) + (dim_b)] = 1;
1185     for (int i = 0; i < 2; i++) {
1186         if (fabs(_relative_affine[3*i]) < 1e-15) {
1187             _relative_affine[3*i] = 1e-15;
1188         }
1189     }
1191     // Update the status text
1192     double degrees = mod360symm(Geom::rad_to_deg(radians));
1193     _message_context.setF(Inkscape::NORMAL_MESSAGE,
1194                           // TRANSLATORS: don't modify the first ";"
1195                           // (it will NOT be displayed as ";" - only the second one will be)
1196                           _("<b>Skew</b>: %0.2f&#176;; with <b>Ctrl</b> to snap angle"),
1197                           degrees);
1199     return TRUE;
1202 gboolean Inkscape::SelTrans::rotateRequest(NR::Point &pt, guint state)
1204     /* When rotating (or skewing):
1205      * 1) the stroke width will not change. This makes life much easier because we don't have to
1206      *    account for that (like for scaling or stretching). As a consequence, all points will
1207      *    have the same origin for the transformation and for the snapping.
1208      * 2) When holding shift, the transformation will be relative to the point opposite of
1209      *    the handle; otherwise it will be relative to the center as set for the selection
1210      */
1212     int snaps = prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12);
1214     // rotate affine in rotate
1215     NR::Point const d1 = _point - _origin;
1216     NR::Point const d2 = pt     - _origin;
1218     NR::Coord const h1 = NR::L2(d1); // initial radius
1219     if (h1 < 1e-15) return FALSE;
1220     NR::Point q1 = d1 / h1; // normalized initial vector to handle
1221     NR::Coord const h2 = NR::L2(d2); // new radius
1222     if (fabs(h2) < 1e-15) return FALSE;
1223     NR::Point q2 = d2 / h2; // normalized new vector to handle
1225     double radians;
1226     if (state & GDK_CONTROL_MASK) {
1227         // Snap to defined angle increments
1228         double cos_t = NR::dot(q1, q2);
1229         double sin_t = NR::dot(NR::rot90(q1), q2);
1230         radians = atan2(sin_t, cos_t);
1231         if (snaps) {
1232             radians = ( M_PI / snaps ) * floor( radians * snaps / M_PI + .5 );
1233         }
1234         q1 = NR::Point(1, 0);
1235         q2 = NR::Point(cos(radians), sin(radians));
1236     } else {
1237         radians = atan2(NR::dot(NR::rot90(d1), d2),
1238                         NR::dot(d1, d2));
1239     }
1241     NR::rotate const r1(q1);
1242     NR::rotate const r2(q2);
1244     // Calculate the relative affine
1245     _relative_affine = NR::Matrix(r2/r1);
1247     // Update the handle position
1248     pt = _point * NR::translate(-_origin) * _relative_affine * NR::translate(_origin);
1250     // Update the status text
1251     double degrees = mod360symm(Geom::rad_to_deg(radians));
1252     _message_context.setF(Inkscape::NORMAL_MESSAGE,
1253                           // TRANSLATORS: don't modify the first ";"
1254                           // (it will NOT be displayed as ";" - only the second one will be)
1255                           _("<b>Rotate</b>: %0.2f&#176;; with <b>Ctrl</b> to snap angle"), degrees);
1257     return TRUE;
1260 gboolean Inkscape::SelTrans::centerRequest(NR::Point &pt, guint state)
1262     SnapManager &m = _desktop->namedview->snap_manager;
1263     m.setup(_desktop);
1264     pt = m.freeSnap(Snapper::SNAPPOINT_NODE, pt).getPoint();
1266     if (state & GDK_CONTROL_MASK) {
1267         if ( fabs(_point[NR::X] - pt[NR::X]) > fabs(_point[NR::Y] - pt[NR::Y]) ) {
1268             pt[NR::Y] = _point[NR::Y];
1269         } else {
1270             pt[NR::X] = _point[NR::X];
1271         }
1272     }
1274     if ( !(state & GDK_SHIFT_MASK) && _bbox ) {
1275         // screen pixels to snap center to bbox
1276 #define SNAP_DIST 5
1277         // FIXME: take from prefs
1278         double snap_dist = SNAP_DIST / _desktop->current_zoom();
1280         for (int i = 0; i < 2; i++) {
1281             if (fabs(pt[i] - _bbox->min()[i]) < snap_dist) {
1282                 pt[i] = _bbox->min()[i];
1283             }
1284             if (fabs(pt[i] - _bbox->midpoint()[i]) < snap_dist) {
1285                 pt[i] = _bbox->midpoint()[i];
1286             }
1287             if (fabs(pt[i] - _bbox->max()[i]) < snap_dist) {
1288                 pt[i] = _bbox->max()[i];
1289             }
1290         }
1291     }
1293     // status text
1294     GString *xs = SP_PX_TO_METRIC_STRING(pt[NR::X], _desktop->namedview->getDefaultMetric());
1295     GString *ys = SP_PX_TO_METRIC_STRING(pt[NR::Y], _desktop->namedview->getDefaultMetric());
1296     _message_context.setF(Inkscape::NORMAL_MESSAGE, _("Move <b>center</b> to %s, %s"), xs->str, ys->str);
1297     g_string_free(xs, FALSE);
1298     g_string_free(ys, FALSE);
1300     return TRUE;
1303 /*
1304  * handlers for handle movement
1305  *
1306  */
1308 void sp_sel_trans_stretch(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, NR::Point &pt, guint state)
1310     seltrans->stretch(handle, pt, state);
1313 void sp_sel_trans_scale(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
1315     seltrans->scale(pt, state);
1318 void sp_sel_trans_skew(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, NR::Point &pt, guint state)
1320     seltrans->skew(handle, pt, state);
1323 void sp_sel_trans_rotate(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
1325     seltrans->rotate(pt, state);
1328 void Inkscape::SelTrans::stretch(SPSelTransHandle const &/*handle*/, NR::Point &/*pt*/, guint /*state*/)
1330     transform(_absolute_affine, NR::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1333 void Inkscape::SelTrans::scale(NR::Point &/*pt*/, guint /*state*/)
1335     transform(_absolute_affine, NR::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1338 void Inkscape::SelTrans::skew(SPSelTransHandle const &/*handle*/, NR::Point &/*pt*/, guint /*state*/)
1340     transform(_relative_affine, _origin);
1343 void Inkscape::SelTrans::rotate(NR::Point &/*pt*/, guint /*state*/)
1345     transform(_relative_affine, _origin);
1348 void sp_sel_trans_center(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint /*state*/)
1350     seltrans->setCenter(pt);
1354 void Inkscape::SelTrans::moveTo(NR::Point const &xy, guint state)
1356     SnapManager &m = _desktop->namedview->snap_manager;
1357     m.setup(_desktop, _items_const);
1359     /* The amount that we've moved by during this drag */
1360     NR::Point dxy = xy - _point;
1362     bool const alt = (state & GDK_MOD1_MASK);
1363     bool const control = (state & GDK_CONTROL_MASK);
1364     bool const shift = (state & GDK_SHIFT_MASK);
1366     if (alt) {
1368         /* Alt pressed means keep offset: snap the moved distance to the grid.
1369         ** FIXME: this will snap to more than just the grid, nowadays.
1370         */
1372         dxy = m.freeSnap(Snapper::SNAPPOINT_NODE, dxy).getPoint();
1374     } else if (!shift) {
1376         /* We're snapping to things, possibly with a constraint to horizontal or
1377         ** vertical movement.  Obtain a list of possible translations and then
1378         ** pick the smallest.
1379         */
1381         /* This will be our list of possible translations */
1382         std::list<Inkscape::SnappedPoint> s;
1384         if (control) {
1386             /* Snap to things, and also constrain to horizontal or vertical movement */
1388             for (unsigned int dim = 0; dim < 2; dim++) {
1389                 s.push_back(m.constrainedSnapTranslation(Inkscape::Snapper::SNAPPOINT_BBOX,
1390                                                          _bbox_points,
1391                                                          Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1392                                                          dxy));
1394                 s.push_back(m.constrainedSnapTranslation(Inkscape::Snapper::SNAPPOINT_NODE,
1395                                                          _snap_points,
1396                                                          Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1397                                                          dxy));
1398             }
1400         } else {
1402             // Let's leave this timer code here for a while. I'll probably need it in the near future (Diederik van Lierop)
1403             /* GTimeVal starttime;
1404             GTimeVal endtime;
1405                 g_get_current_time(&starttime); */
1407             /* Snap to things with no constraint */
1408                         s.push_back(m.freeSnapTranslation(Inkscape::Snapper::SNAPPOINT_BBOX, _bbox_points, dxy));
1409             s.push_back(m.freeSnapTranslation(Inkscape::Snapper::SNAPPOINT_NODE, _snap_points, dxy));
1411                 /*g_get_current_time(&endtime);
1412                 double elapsed = ((((double)endtime.tv_sec - starttime.tv_sec) * G_USEC_PER_SEC + (endtime.tv_usec - starttime.tv_usec))) / 1000.0;
1413                 std::cout << "Time spent snapping: " << elapsed << std::endl; */
1414         }
1416         /* Pick one */
1417         Inkscape::SnappedPoint best_snapped_point;
1418         g_assert(best_snapped_point.getDistance() == NR_HUGE);
1419         for (std::list<Inkscape::SnappedPoint>::const_iterator i = s.begin(); i != s.end(); i++) {
1420             if (i->getSnapped()) {
1421                 // std::cout << "moveTo() -> snapped to point: " << i->getPoint() << " with transformation: " << i->getTransformation();
1422                 if (i->getDistance() < best_snapped_point.getDistance()) {
1423                     best_snapped_point = *i;
1424                     dxy = i->getTransformation();
1425                     // std::cout << " SEL";
1426                 }
1427                 //std::cout << std::endl;
1428             }
1429         }
1430         if (best_snapped_point.getSnapped()) {
1431             _desktop->snapindicator->set_new_snappoint(best_snapped_point);
1432         } else {
1433             _desktop->snapindicator->remove_snappoint();
1434         }
1435     }
1437     if (control) {
1438         /* Ensure that the horizontal and vertical constraint has been applied */
1439         if (fabs(dxy[NR::X]) > fabs(dxy[NR::Y])) {
1440             dxy[NR::Y] = 0;
1441         } else {
1442             dxy[NR::X] = 0;
1443         }
1444     }
1446     NR::Matrix const move((NR::translate(dxy)));
1447     NR::Point const norm(0, 0);
1448     transform(move, norm);
1450     // status text
1451     GString *xs = SP_PX_TO_METRIC_STRING(dxy[NR::X], _desktop->namedview->getDefaultMetric());
1452     GString *ys = SP_PX_TO_METRIC_STRING(dxy[NR::Y], _desktop->namedview->getDefaultMetric());
1453     _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);
1454     g_string_free(xs, TRUE);
1455     g_string_free(ys, TRUE);
1458 // Given a location of a handle at the visual bounding box, find the corresponding location at the
1459 // geometrical bounding box
1460 NR::Point Inkscape::SelTrans::_getGeomHandlePos(NR::Point const &visual_handle_pos)
1462     if ( _snap_bbox_type == SPItem::GEOMETRIC_BBOX) {
1463         // When the selector tool is using geometric bboxes, then the handle is already
1464         // located at one of the geometric bbox corners
1465         return visual_handle_pos;
1466     }
1468     if (!_geometric_bbox) {
1469         //_getGeomHandlePos() can only be used after _geometric_bbox has been defined!
1470         return visual_handle_pos;
1471     }
1473     // Using the NR::Rect constructor below ensures that "min() < max()", which is important
1474     // because this will also hold for _bbox, and which is required for get_scale_transform_with_stroke()
1475     NR::Rect new_bbox = NR::Rect(_origin_for_bboxpoints, visual_handle_pos); // new visual bounding box
1476     // Please note that the new_bbox might in fact be just a single line, for example when stretching (in
1477     // which case the handle and origin will be aligned vertically or horizontally)
1478     NR::Point normalized_handle_pos = (visual_handle_pos - new_bbox.min()) * NR::scale(new_bbox.dimensions()).inverse();
1480     // Calculate the absolute affine while taking into account the scaling of the stroke width
1481     int transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1482     NR::Matrix abs_affine = get_scale_transform_with_stroke (*_bbox, _strokewidth, transform_stroke,
1483                     new_bbox.min()[NR::X], new_bbox.min()[NR::Y], new_bbox.max()[NR::X], new_bbox.max()[NR::Y]);
1485     // Calculate the scaled geometrical bbox
1486     NR::Rect new_geom_bbox = NR::Rect(_geometric_bbox->min() * abs_affine, _geometric_bbox->max() * abs_affine);
1487     // Find the location of the handle on this new geometrical bbox
1488     return normalized_handle_pos * NR::scale(new_geom_bbox.dimensions()) + new_geom_bbox.min(); //new position of the geometric handle
1491 NR::scale Inkscape::calcScaleFactors(NR::Point const &initial_point, NR::Point const &new_point, NR::Point const &origin, bool const skew)
1493     // Work out the new scale factors for the bbox
1495     NR::Point const initial_delta = initial_point - origin;
1496     NR::Point const new_delta = new_point - origin;
1497     NR::Point const offset = new_point - initial_point;
1498     NR::scale scale(1, 1);
1500     for ( unsigned int i = 0 ; i < 2 ; i++ ) {
1501         if ( fabs(initial_delta[i]) > 1e-6 ) {
1502             if (skew) {
1503                 scale[i] = offset[1-i] / initial_delta[i];
1504             } else {
1505                 scale[i] = new_delta[i] / initial_delta[i];
1506             }
1507         }
1508     }
1510     return scale;
1513 // Only for scaling/stretching
1514 NR::Point Inkscape::SelTrans::_calcAbsAffineDefault(NR::scale const default_scale)
1516     NR::Matrix abs_affine = NR::translate(-_origin) * NR::Matrix(default_scale) * NR::translate(_origin);
1517     NR::Point new_bbox_min = _approximate_bbox->min() * abs_affine;
1518     NR::Point new_bbox_max = _approximate_bbox->max() * abs_affine;
1520     int transform_stroke = false;
1521     gdouble strokewidth = 0;
1523     if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
1524         transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1525         strokewidth = _strokewidth;
1526     }
1528     _absolute_affine = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
1529                     new_bbox_min[NR::X], new_bbox_min[NR::Y], new_bbox_max[NR::X], new_bbox_max[NR::Y]);
1531     // return the new handle position
1532     return ( _point - _origin ) * default_scale + _origin;
1535 // Only for scaling/stretching
1536 NR::Point Inkscape::SelTrans::_calcAbsAffineGeom(NR::scale const geom_scale)
1538     _relative_affine = NR::Matrix(geom_scale);
1539     _absolute_affine = NR::translate(-_origin_for_specpoints) * _relative_affine * NR::translate(_origin_for_specpoints);
1541     bool const transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1542     NR::Rect visual_bbox = get_visual_bbox(_geometric_bbox, _absolute_affine, _strokewidth, transform_stroke);
1544     // return the new handle position
1545     return visual_bbox.min() + visual_bbox.dimensions() * NR::scale(_handle_x, _handle_y);
1549 /*
1550   Local Variables:
1551   mode:c++
1552   c-file-style:"stroustrup"
1553   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1554   indent-tabs-mode:nil
1555   fill-column:99
1556   End:
1557 */
1558 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :