Code

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