Code

Applying fixes for gcc 4.3 build issues (closes LP: #169115)
[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
19 #include <cstring>
20 #include <string>
22 #include <libnr/nr-matrix-ops.h>
23 #include <libnr/nr-matrix-translate-ops.h>
24 #include <libnr/nr-rotate-ops.h>
25 #include <libnr/nr-scale-ops.h>
26 #include <libnr/nr-translate-matrix-ops.h>
27 #include <libnr/nr-translate-ops.h>
28 #include <gdk/gdkkeysyms.h>
29 #include "document.h"
30 #include "sp-namedview.h"
31 #include "desktop.h"
32 #include "desktop-handles.h"
33 #include "desktop-style.h"
34 #include "knot.h"
35 #include "snap.h"
36 #include "selection.h"
37 #include "select-context.h"
38 #include "sp-item.h"
39 #include "sp-item-transform.h"
40 #include "seltrans-handles.h"
41 #include "seltrans.h"
42 #include "selection-chemistry.h"
43 #include "sp-metrics.h"
44 #include "verbs.h"
45 #include <glibmm/i18n.h>
46 #include "display/sp-ctrlline.h"
47 #include "prefs-utils.h"
48 #include "xml/repr.h"
50 #include "isnan.h" //temp fix.  make sure included last
52 static void sp_remove_handles(SPKnot *knot[], gint num);
54 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data);
55 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint state, gpointer data);
56 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data);
57 static void sp_sel_trans_handle_new_event(SPKnot *knot, NR::Point *position, guint32 state, gpointer data);
58 static gboolean sp_sel_trans_handle_request(SPKnot *knot, NR::Point *p, guint state, gboolean *data);
60 extern GdkPixbuf *handles[];
62 static gboolean sp_seltrans_handle_event(SPKnot *knot, GdkEvent *event, gpointer)
63 {
64     switch (event->type) {
65         case GDK_MOTION_NOTIFY:
66             break;
67         case GDK_KEY_PRESS:
68             if (get_group0_keyval (&event->key) == GDK_space) {
69                 /* stamping mode: both mode(show content and outline) operation with knot */
70                 if (!SP_KNOT_IS_GRABBED(knot)) {
71                     return FALSE;
72                 }
73                 SPDesktop *desktop = knot->desktop;
74                 Inkscape::SelTrans *seltrans = SP_SELECT_CONTEXT(desktop->event_context)->_seltrans;
75                 seltrans->stamp();
76                 return TRUE;
77             }
78             break;
79         default:
80             break;
81     }
83     return FALSE;
84 }
86 Inkscape::SelTrans::SelTrans(SPDesktop *desktop) :
87     _desktop(desktop),
88     _selcue(desktop),
89     _state(STATE_SCALE),
90     _show(SHOW_CONTENT),
91     _grabbed(false),
92     _show_handles(true),
93     _bbox(NR::Nothing()),
94     _approximate_bbox(NR::Nothing()),
95     _chandle(NULL),
96     _stamp_cache(NULL),
97     _message_context(desktop->messageStack())
98 {
99     gchar const *prefs_bbox = prefs_get_string_attribute("tools", "bounding_box");
100     _snap_bbox_type = (prefs_bbox != NULL && strcmp(prefs_bbox, "geometric")==0)? SPItem::GEOMETRIC_BBOX : SPItem::APPROXIMATE_BBOX;
102     g_return_if_fail(desktop != NULL);
104     for (int i = 0; i < 8; i++) {
105         _shandle[i] = NULL;
106         _rhandle[i] = NULL;
107     }
109     _updateVolatileState();
110     _current.set_identity();
112     _center_is_set = false; // reread _center from items, or set to bbox midpoint
114     _updateHandles();
116     _selection = sp_desktop_selection(desktop);
118     _norm = sp_canvas_item_new(sp_desktop_controls(desktop),
119                                SP_TYPE_CTRL,
120                                "anchor", GTK_ANCHOR_CENTER,
121                                "mode", SP_CTRL_MODE_COLOR,
122                                "shape", SP_CTRL_SHAPE_BITMAP,
123                                "size", 13.0,
124                                "filled", TRUE,
125                                "fill_color", 0x00000000,
126                                "stroked", TRUE,
127                                "stroke_color", 0x000000a0,
128                                "pixbuf", handles[12],
129                                NULL);
131     _grip = sp_canvas_item_new(sp_desktop_controls(desktop),
132                                SP_TYPE_CTRL,
133                                "anchor", GTK_ANCHOR_CENTER,
134                                "mode", SP_CTRL_MODE_XOR,
135                                "shape", SP_CTRL_SHAPE_CROSS,
136                                "size", 7.0,
137                                "filled", TRUE,
138                                "fill_color", 0xffffff7f,
139                                "stroked", TRUE,
140                                "stroke_color", 0xffffffff,
141                                "pixbuf", handles[12],
142                                NULL);
144     sp_canvas_item_hide(_grip);
145     sp_canvas_item_hide(_norm);
147     for (int i = 0; i < 4; i++) {
148         _l[i] = sp_canvas_item_new(sp_desktop_controls(desktop), SP_TYPE_CTRLLINE, NULL);
149         sp_canvas_item_hide(_l[i]);
150     }
152     _sel_changed_connection = _selection->connectChanged(
153         sigc::mem_fun(*this, &Inkscape::SelTrans::_selChanged)
154         );
156     _sel_modified_connection = _selection->connectModified(
157         sigc::mem_fun(*this, &Inkscape::SelTrans::_selModified)
158         );
161 Inkscape::SelTrans::~SelTrans()
163     _sel_changed_connection.disconnect();
164     _sel_modified_connection.disconnect();
166     for (unsigned int i = 0; i < 8; i++) {
167         if (_shandle[i]) {
168             g_object_unref(G_OBJECT(_shandle[i]));
169             _shandle[i] = NULL;
170         }
171         if (_rhandle[i]) {
172             g_object_unref(G_OBJECT(_rhandle[i]));
173             _rhandle[i] = NULL;
174         }
175     }
176     if (_chandle) {
177         g_object_unref(G_OBJECT(_chandle));
178         _chandle = NULL;
179     }
181     if (_norm) {
182         gtk_object_destroy(GTK_OBJECT(_norm));
183         _norm = NULL;
184     }
185     if (_grip) {
186         gtk_object_destroy(GTK_OBJECT(_grip));
187         _grip = NULL;
188     }
189     for (int i = 0; i < 4; i++) {
190         if (_l[i]) {
191             gtk_object_destroy(GTK_OBJECT(_l[i]));
192             _l[i] = NULL;
193         }
194     }
196     for (unsigned i = 0; i < _items.size(); i++) {
197         sp_object_unref(SP_OBJECT(_items[i].first), NULL);
198     }
200     _items.clear();
201     _items_centers.clear();
204 void Inkscape::SelTrans::resetState()
206     _state = STATE_SCALE;
209 void Inkscape::SelTrans::increaseState()
211     if (_state == STATE_SCALE) {
212         _state = STATE_ROTATE;
213     } else {
214         _state = STATE_SCALE;
215     }
217     _center_is_set = true; // no need to reread center
219     _updateHandles();
222 void Inkscape::SelTrans::setCenter(NR::Point const &p)
224     _center = p;
225     _center_is_set = true;
227     // Write the new center position into all selected items
228     for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
229         SPItem *it = (SPItem*)SP_OBJECT(l->data);
230         it->setCenter(p);
231         // only set the value; updating repr and document_done will be done once, on ungrab
232     }
234     _updateHandles();
237 void Inkscape::SelTrans::grab(NR::Point const &p, gdouble x, gdouble y, bool show_handles)
239     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
241     g_return_if_fail(!_grabbed);
243     _grabbed = true;
244     _show_handles = show_handles;
245     _updateVolatileState();
246     _current.set_identity();
248     _changed = false;
250     if (_empty) {
251         return;
252     }
254     for (GSList const *l = selection->itemList(); l; l = l->next) {
255         SPItem *it = (SPItem*)sp_object_ref(SP_OBJECT(l->data), NULL);
256         _items.push_back(std::pair<SPItem *, NR::Matrix>(it, sp_item_i2d_affine(it)));
257         _items_centers.push_back(std::pair<SPItem *, NR::Point>(it, it->getCenter())); // for content-dragging, we need to remember original centers
258     }
260     _current.set_identity();
262     _point = p;
264     // The selector tool should snap the bbox, special snappoints, and path nodes
265     // (The special points are the handles, center, rotation axis, font baseline, ends of spiral, etc.)
267     // First, determine the bounding box for snapping ...
268     _bbox = selection->bounds(_snap_bbox_type);
269     _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX); // Used for correctly scaling the strokewidth
271     // Next, get all points to consider for snapping
272     SnapManager const &m = _desktop->namedview->snap_manager;
273     _snap_points = selection->getSnapPoints(m.getIncludeItemCenter());
274     std::vector<NR::Point> snap_points_hull = selection->getSnapPointsConvexHull();
275     if (_snap_points.size() > 100) {
276         /* Snapping a huge number of nodes will take way too long, so limit the number of snappable nodes
277         An average user would rarely ever try to snap such a large number of nodes anyway, because
278         (s)he could hardly discern which node would be snapping */
279         _snap_points = snap_points_hull;
280         // Unfortunately, by now we will have lost the font-baseline snappoints :-(
281     }
283     // Find bbox hulling all special points, which excludes stroke width. Here we need to include the
284     // path nodes, for example because a rectangle which has been converted to a path doesn't have
285     // any other special points
286     NR::Rect snap_points_bbox;
287     if ( snap_points_hull.empty() == false ) {
288         std::vector<NR::Point>::iterator i = snap_points_hull.begin();
289         snap_points_bbox = NR::Rect(*i, *i);
290         i++;
291         while (i != snap_points_hull.end()) {
292             snap_points_bbox.expandTo(*i);
293             i++;
294         }
295     }
297     _bbox_points.clear();
298     if (_bbox) {
299         // ... and add the bbox corners to _bbox_points
300         for ( unsigned i = 0 ; i < 4 ; i++ ) {
301             _bbox_points.push_back(_bbox->corner(i));
302         }
303         // There are two separate "opposites" (i.e. opposite w.r.t. the handle being dragged):
304         //  - one for snapping the boundingbox, which can be either visual or geometric
305         //  - one for snapping the special points
306         // The "opposite" in case of a geometric boundingbox always coincides with the "opposite" for the special points
307         // These distinct "opposites" are needed in the snapmanager to avoid bugs such as #1540195 (in which
308         // a box is caught between to guides)
309         _opposite_for_bboxpoints = _bbox->min() + _bbox->dimensions() * NR::scale(1-x, 1-y);
310         _opposite_for_specpoints = (snap_points_bbox.min() + (snap_points_bbox.dimensions() * NR::scale(1-x, 1-y) ) );
311         // Only a single "opposite" can be used in calculating transformations.
312         _opposite = _opposite_for_bboxpoints;
313     }
315     // The lines below are usefull for debugging any snapping issues, as they'll spit out all points that are considered for snapping
317     /*std::cout << "Number of snap points:  " << _snap_points.size() << std::endl;
318     for (std::vector<NR::Point>::const_iterator i = _snap_points.begin(); i != _snap_points.end(); i++)
319     {
320         std::cout << "    " << *i << std::endl;
321     }
323     std::cout << "Number of bbox points:  " << _bbox_points.size() << std::endl;
324     for (std::vector<NR::Point>::const_iterator i = _bbox_points.begin(); i != _bbox_points.end(); i++)
325     {
326         std::cout << "    " << *i << std::endl;
327     }*/
329     if ((x != -1) && (y != -1)) {
330         sp_canvas_item_show(_norm);
331         sp_canvas_item_show(_grip);
332     }
334     if (_show == SHOW_OUTLINE) {
335         for (int i = 0; i < 4; i++)
336             sp_canvas_item_show(_l[i]);
337     }
339     _updateHandles();
340     g_return_if_fail(_stamp_cache == NULL);
343 void Inkscape::SelTrans::transform(NR::Matrix const &rel_affine, NR::Point const &norm)
345     g_return_if_fail(_grabbed);
346     g_return_if_fail(!_empty);
348     NR::Matrix const affine( NR::translate(-norm) * rel_affine * NR::translate(norm) );
350     if (_show == SHOW_CONTENT) {
351         // update the content
352         for (unsigned i = 0; i < _items.size(); i++) {
353             SPItem &item = *_items[i].first;
354             NR::Matrix const &prev_transform = _items[i].second;
355             sp_item_set_i2d_affine(&item, prev_transform * affine);
356         }
357     } else {
358         if (_bbox) {
359             NR::Point p[4];
360             /* update the outline */
361             for (unsigned i = 0 ; i < 4 ; i++) {
362                 p[i] = _bbox->corner(i) * affine;
363             }
364             for (unsigned i = 0 ; i < 4 ; i++) {
365                 sp_ctrlline_set_coords(SP_CTRLLINE(_l[i]), p[i], p[(i+1)%4]);
366             }
367         }
368     }
370     _current = affine;
371     _changed = true;
372     _updateHandles();
375 void Inkscape::SelTrans::ungrab()
377     g_return_if_fail(_grabbed);
378     _grabbed = false;
379     _show_handles = true;
381     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
382     _updateVolatileState();
384     for (unsigned i = 0; i < _items.size(); i++) {
385         sp_object_unref(SP_OBJECT(_items[i].first), NULL);
386     }
388     sp_canvas_item_hide(_norm);
389     sp_canvas_item_hide(_grip);
391     if (_show == SHOW_OUTLINE) {
392         for (int i = 0; i < 4; i++)
393             sp_canvas_item_hide(_l[i]);
394     }
396     if (_stamp_cache) {
397         g_slist_free(_stamp_cache);
398         _stamp_cache = NULL;
399     }
401     _message_context.clear();
403     if (!_empty && _changed) {
404         sp_selection_apply_affine(selection, _current, (_show == SHOW_OUTLINE)? true : false);
405         if (_center) {
406             *_center *= _current;
407             _center_is_set = true;
408         }
410 // If dragging showed content live, sp_selection_apply_affine cannot change the centers
411 // appropriately - it does not know the original positions of the centers (all objects already have
412 // the new bboxes). So we need to reset the centers from our saved array.
413         if (_show != SHOW_OUTLINE && !_current.is_translation()) {
414             for (unsigned i = 0; i < _items_centers.size(); i++) {
415                 SPItem *currentItem = _items_centers[i].first;
416                 if (currentItem->isCenterSet()) { // only if it's already set
417                     currentItem->setCenter (_items_centers[i].second * _current);
418                     SP_OBJECT(currentItem)->updateRepr();
419                 }
420             }
421         }
423         _items.clear();
424         _items_centers.clear();
426         if (_current.is_translation()) {
427             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
428                              _("Move"));
429         } else if (_current.is_scale()) {
430             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
431                              _("Scale"));
432         } else if (_current.is_rotation()) {
433             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
434                              _("Rotate"));
435         } else {
436             sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
437                              _("Skew"));
438         }
440     } else {
442         if (_center_is_set) {
443             // we were dragging center; update reprs and commit undoable action
444             for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
445                 SPItem *it = (SPItem*)SP_OBJECT(l->data);
446                 SP_OBJECT(it)->updateRepr();
447             }
448             sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
449                             _("Set center"));
450         }
452         _items.clear();
453         _items_centers.clear();
454         _updateHandles();
455     }
458 /* fixme: This is really bad, as we compare positions for each stamp (Lauris) */
459 /* fixme: IMHO the best way to keep sort cache would be to implement timestamping at last */
461 void Inkscape::SelTrans::stamp()
463     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
465     bool fixup = !_grabbed;
466     if ( fixup && _stamp_cache ) {
467         // TODO - give a proper fix. Simple temproary work-around for the grab() issue
468         g_slist_free(_stamp_cache);
469         _stamp_cache = NULL;
470     }
472     /* stamping mode */
473     if (!_empty) {
474         GSList *l;
475         if (_stamp_cache) {
476             l = _stamp_cache;
477         } else {
478             /* Build cache */
479             l  = g_slist_copy((GSList *) selection->itemList());
480             l  = g_slist_sort(l, (GCompareFunc) sp_object_compare_position);
481             _stamp_cache = l;
482         }
484         while (l) {
485             SPItem *original_item = SP_ITEM(l->data);
486             Inkscape::XML::Node *original_repr = SP_OBJECT_REPR(original_item);
488             // remember the position of the item
489             gint pos = original_repr->position();
490             // remember parent
491             Inkscape::XML::Node *parent = sp_repr_parent(original_repr);
493             Inkscape::XML::Node *copy_repr = original_repr->duplicate(parent->document());
495             // add the new repr to the parent
496             parent->appendChild(copy_repr);
497             // move to the saved position
498             copy_repr->setPosition(pos > 0 ? pos : 0);
500             SPItem *copy_item = (SPItem *) sp_desktop_document(_desktop)->getObjectByRepr(copy_repr);
502             NR::Matrix const *new_affine;
503             if (_show == SHOW_OUTLINE) {
504                 NR::Matrix const i2d(sp_item_i2d_affine(original_item));
505                 NR::Matrix const i2dnew( i2d * _current );
506                 sp_item_set_i2d_affine(copy_item, i2dnew);
507                 new_affine = &copy_item->transform;
508             } else {
509                 new_affine = &original_item->transform;
510             }
512             sp_item_write_transform(copy_item, copy_repr, *new_affine);
514             if ( copy_item->isCenterSet() && _center ) {
515                 copy_item->setCenter(*_center * _current);
516             }
518             Inkscape::GC::release(copy_repr);
519             l = l->next;
520         }
521         sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
522                          _("Stamp"));
523     }
525     if ( fixup && _stamp_cache ) {
526         // TODO - give a proper fix. Simple temproary work-around for the grab() issue
527         g_slist_free(_stamp_cache);
528         _stamp_cache = NULL;
529     }
532 void Inkscape::SelTrans::_updateHandles()
534     if ( !_show_handles || _empty )
535     {
536         sp_remove_handles(_shandle, 8);
537         sp_remove_handles(_rhandle, 8);
538         sp_remove_handles(&_chandle, 1);
539         return;
540     }
542     // center handle
543     if ( _chandle == NULL ) {
544         _chandle = sp_knot_new(_desktop, _("<b>Center</b> of rotation and skewing: drag to reposition; scaling with Shift also uses this center"));
546         _chandle->setShape (SP_CTRL_SHAPE_BITMAP);
547         _chandle->setSize (13);
548         _chandle->setAnchor (handle_center.anchor);
549         _chandle->setMode (SP_CTRL_MODE_XOR);
550         _chandle->setFill(0x00000000, 0x00000000, 0x00000000);
551         _chandle->setStroke(0x000000ff, 0xff0000b0, 0xff0000b0);
552         _chandle->setPixbuf(handles[handle_center.control]);
553         sp_knot_update_ctrl(_chandle);
555         g_signal_connect(G_OBJECT(_chandle), "request",
556                          G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle_center);
557         g_signal_connect(G_OBJECT(_chandle), "moved",
558                          G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle_center);
559         g_signal_connect(G_OBJECT(_chandle), "grabbed",
560                          G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle_center);
561         g_signal_connect(G_OBJECT(_chandle), "ungrabbed",
562                          G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle_center);
563         g_signal_connect(G_OBJECT(_chandle), "clicked",
564                          G_CALLBACK(sp_sel_trans_handle_click), (gpointer) &handle_center);
565     }
567     sp_remove_handles(&_chandle, 1);
568     if ( _state == STATE_SCALE ) {
569         sp_remove_handles(_rhandle, 8);
570         _showHandles(_shandle, handles_scale, 8,
571                     _("<b>Squeeze or stretch</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"),
572                     _("<b>Scale</b> selection; with <b>Ctrl</b> to scale uniformly; with <b>Shift</b> to scale around rotation center"));
573     } else {
574         sp_remove_handles(_shandle, 8);
575         _showHandles(_rhandle, handles_rotate, 8,
576                     _("<b>Skew</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to skew around the opposite side"),
577                     _("<b>Rotate</b> selection; with <b>Ctrl</b> to snap angle; with <b>Shift</b> to rotate around the opposite corner"));
578     }
580     if (!_center_is_set) {
581         _center = _desktop->selection->center();
582         _center_is_set = true;
583     }
585     if ( _state == STATE_SCALE || !_center ) {
586         sp_knot_hide(_chandle);
587     } else {
588         sp_knot_show(_chandle);
589         sp_knot_moveto(_chandle, &*_center);
590     }
593 void Inkscape::SelTrans::_updateVolatileState()
595     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
596     _empty = selection->isEmpty();
598     if (_empty) {
599         return;
600     }
602     //Update the bboxes
603     _bbox = selection->bounds(_snap_bbox_type);
604     _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX);
606     if (!_bbox) {
607         _empty = true;
608         return;
609     }
611     _strokewidth = stroke_average_width (selection->itemList());
614 static void sp_remove_handles(SPKnot *knot[], gint num)
616     for (int i = 0; i < num; i++) {
617         if (knot[i] != NULL) {
618             sp_knot_hide(knot[i]);
619         }
620     }
623 void Inkscape::SelTrans::_showHandles(SPKnot *knot[], SPSelTransHandle const handle[], gint num,
624                              gchar const *even_tip, gchar const *odd_tip)
626     g_return_if_fail( !_empty );
628     for (int i = 0; i < num; i++) {
629         if (knot[i] == NULL) {
630             knot[i] = sp_knot_new(_desktop, i % 2 ? even_tip : odd_tip);
632             knot[i]->setShape (SP_CTRL_SHAPE_BITMAP);
633             knot[i]->setSize (13);
634             knot[i]->setAnchor (handle[i].anchor);
635             knot[i]->setMode (SP_CTRL_MODE_XOR);
636             knot[i]->setFill(0x000000ff, 0x00ff6600, 0x00ff6600); // inversion, green, green
637             knot[i]->setStroke(0x000000ff, 0x000000ff, 0x000000ff); // inversion
638             knot[i]->setPixbuf(handles[handle[i].control]);
639             sp_knot_update_ctrl(knot[i]);
641             g_signal_connect(G_OBJECT(knot[i]), "request",
642                              G_CALLBACK(sp_sel_trans_handle_request), (gpointer) &handle[i]);
643             g_signal_connect(G_OBJECT(knot[i]), "moved",
644                              G_CALLBACK(sp_sel_trans_handle_new_event), (gpointer) &handle[i]);
645             g_signal_connect(G_OBJECT(knot[i]), "grabbed",
646                              G_CALLBACK(sp_sel_trans_handle_grab), (gpointer) &handle[i]);
647             g_signal_connect(G_OBJECT(knot[i]), "ungrabbed",
648                              G_CALLBACK(sp_sel_trans_handle_ungrab), (gpointer) &handle[i]);
649             g_signal_connect(G_OBJECT(knot[i]), "event", G_CALLBACK(sp_seltrans_handle_event), (gpointer) &handle[i]);
650         }
651         sp_knot_show(knot[i]);
653         NR::Point const handle_pt(handle[i].x, handle[i].y);
654         // shouldn't have nullary bbox, but knots
655         g_assert(_bbox);
656         NR::Point p( _bbox->min()
657                      + ( _bbox->dimensions()
658                          * NR::scale(handle_pt) ) );
660         sp_knot_moveto(knot[i], &p);
661     }
664 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data)
666     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleGrab(
667         knot, state, *(SPSelTransHandle const *) data
668         );
671 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint /*state*/, gpointer /*data*/)
673     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->ungrab();
676 static void sp_sel_trans_handle_new_event(SPKnot *knot, NR::Point *position, guint state, gpointer data)
678     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleNewEvent(
679         knot, position, state, *(SPSelTransHandle const *) data
680         );
683 static gboolean sp_sel_trans_handle_request(SPKnot *knot, NR::Point *position, guint state, gboolean *data)
685     return SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleRequest(
686         knot, position, state, *(SPSelTransHandle const *) data
687         );
690 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data)
692     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleClick(
693         knot, state, *(SPSelTransHandle const *) data
694         );
697 void Inkscape::SelTrans::handleClick(SPKnot */*knot*/, guint state, SPSelTransHandle const &handle)
699     switch (handle.anchor) {
700         case GTK_ANCHOR_CENTER:
701             if (state & GDK_SHIFT_MASK) {
702                 // Unset the  center position for all selected items
703                 for (GSList const *l = _desktop->selection->itemList(); l; l = l->next) {
704                     SPItem *it = (SPItem*)(SP_OBJECT(l->data));
705                     it->unsetCenter();
706                     SP_OBJECT(it)->updateRepr();
707                     _center_is_set = false;  // center has changed
708                     _updateHandles();
709                 }
710                 sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
711                                         _("Reset center"));
712             }
713             break;
714         default:
715             break;
716     }
719 void Inkscape::SelTrans::handleGrab(SPKnot *knot, guint /*state*/, SPSelTransHandle const &handle)
721     switch (handle.anchor) {
722         case GTK_ANCHOR_CENTER:
723             g_object_set(G_OBJECT(_grip),
724                          "shape", SP_CTRL_SHAPE_BITMAP,
725                          "size", 13.0,
726                          NULL);
727             sp_canvas_item_show(_grip);
728             break;
729         default:
730             g_object_set(G_OBJECT(_grip),
731                          "shape", SP_CTRL_SHAPE_CROSS,
732                          "size", 7.0,
733                          NULL);
734             sp_canvas_item_show(_norm);
735             sp_canvas_item_show(_grip);
737             break;
738     }
740     grab(sp_knot_position(knot), handle.x, handle.y, FALSE);
744 void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, NR::Point *position, guint state, SPSelTransHandle const &handle)
746     if (!SP_KNOT_IS_GRABBED(knot)) {
747         return;
748     }
750     // in case items have been unhooked from the document, don't
751     // try to continue processing events for them.
752     for (unsigned int i = 0; i < _items.size(); i++) {
753         if (!SP_OBJECT_DOCUMENT(SP_OBJECT(_items[i].first)) ) {
754             return;
755         }
756     }
758     handle.action(this, handle, *position, state);
762 gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, NR::Point *position, guint state, SPSelTransHandle const &handle)
764     if (!SP_KNOT_IS_GRABBED(knot)) {
765         return TRUE;
766     }
768     knot->desktop->setPosition(*position);
770     if ((!(state & GDK_SHIFT_MASK) == !(_state == STATE_ROTATE)) && (&handle != &handle_center)) {
771         _origin = _opposite;
772         _origin_for_bboxpoints = _opposite_for_bboxpoints;
773         _origin_for_specpoints = _opposite_for_specpoints;
774     } else if (_center) {
775         _origin = *_center;
776         _origin_for_bboxpoints = *_center;
777         _origin_for_specpoints = *_center;
778     } else {
779         // FIXME
780         return TRUE;
781     }
782     if (handle.request(this, handle, *position, state)) {
783         sp_knot_set_position(knot, position, state);
784         SP_CTRL(_grip)->moveto(*position);
785         SP_CTRL(_norm)->moveto(_origin);
786     }
788     return TRUE;
792 void Inkscape::SelTrans::_selChanged(Inkscape::Selection */*selection*/)
794     if (!_grabbed) {
795         // reread in case it changed on the fly:
796         gchar const *prefs_bbox = prefs_get_string_attribute("tools", "bounding_box");
797         _snap_bbox_type = (prefs_bbox != NULL && strcmp(prefs_bbox, "geometric")==0)? SPItem::GEOMETRIC_BBOX : SPItem::APPROXIMATE_BBOX;
798         //SPItem::APPROXIMATE_BBOX will be replaced by SPItem::VISUAL_BBOX, as soon as the latter is implemented properly
800         _updateVolatileState();
801         _current.set_identity();
802         _center_is_set = false; // center(s) may have changed
803         _updateHandles();
804     }
807 void Inkscape::SelTrans::_selModified(Inkscape::Selection */*selection*/, guint /*flags*/)
809     if (!_grabbed) {
810         _updateVolatileState();
811         _current.set_identity();
813         // reset internal flag
814         _changed = false;
816         _center_is_set = false;  // center(s) may have changed
818         _updateHandles();
819     }
822 /*
823  * handlers for handle move-request
824  */
826 /** Returns -1 or 1 according to the sign of x.  Returns 1 for 0 and NaN. */
827 static double sign(double const x)
829     return ( x < 0
830              ? -1
831              : 1 );
834 gboolean sp_sel_trans_scale_request(Inkscape::SelTrans *seltrans,
835                                     SPSelTransHandle const &, NR::Point &pt, guint state)
837     return seltrans->scaleRequest(pt, state);
840 gboolean sp_sel_trans_stretch_request(Inkscape::SelTrans *seltrans,
841                                       SPSelTransHandle const &handle, NR::Point &pt, guint state)
843     return seltrans->stretchRequest(handle, pt, state);
846 gboolean sp_sel_trans_skew_request(Inkscape::SelTrans *seltrans,
847                                    SPSelTransHandle const &handle, NR::Point &pt, guint state)
849     return seltrans->skewRequest(handle, pt, state);
852 gboolean sp_sel_trans_rotate_request(Inkscape::SelTrans *seltrans,
853                                      SPSelTransHandle const &, NR::Point &pt, guint state)
855     return seltrans->rotateRequest(pt, state);
858 gboolean sp_sel_trans_center_request(Inkscape::SelTrans *seltrans,
859                                      SPSelTransHandle const &, NR::Point &pt, guint state)
861     return seltrans->centerRequest(pt, state);
864 gboolean Inkscape::SelTrans::scaleRequest(NR::Point &pt, guint state)
866     using NR::X;
867     using NR::Y;
869     NR::Point d = _point - _origin;
870     NR::scale s(0, 0);
872     /* Work out the new scale factors `s' */
873     for ( unsigned int i = 0 ; i < 2 ; i++ ) {
874         if ( fabs(d[i]) > 0.001 ) {
875             s[i] = ( pt[i] - _origin[i] ) / d[i];
876             if ( fabs(s[i]) < 1e-9 ) {
877                 s[i] = 1e-9;
878             }
879         }
880     }
882     if (state & GDK_MOD1_MASK) { // scale by an integer multiplier/divider
883         for ( unsigned int i = 0 ; i < 2 ; i++ ) {
884             if (fabs(s[i]) > 1)
885                 s[i] = round(s[i]);
886             else
887                 s[i] = 1/round(1/(MIN(s[i], 10)));
888         }
889     }
891     SnapManager const &m = _desktop->namedview->snap_manager;
893     /* Get a STL list of the selected items.
894     ** FIXME: this should probably be done by Inkscape::Selection.
895     */
896     std::list<SPItem const*> it;
897     for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
898         it.push_back(reinterpret_cast<SPItem*>(i->data));
899     }
901     if ((state & GDK_CONTROL_MASK) || _desktop->isToolboxButtonActive ("lock")) {
902         // Scale is locked to a 1:1 aspect ratio, so that s[X] must be made to equal s[Y].
903         //
904         // The aspect-ratio must be locked before snapping
905         if (fabs(s[NR::X]) > fabs(s[NR::Y])) {
906                 s[NR::X] = fabs(s[NR::Y]) * sign(s[NR::X]);
907             } else {
908                 s[NR::Y] = fabs(s[NR::X]) * sign(s[NR::Y]);
909             }
911         // Snap along a suitable constraint vector from the origin.
912         std::pair<NR::scale, bool> bb = m.constrainedSnapScale(Snapper::SNAPPOINT_BBOX,
913                                                                _bbox_points,
914                                                                it,
915                                                                s,
916                                                                _origin_for_bboxpoints);
918         std::pair<NR::scale, bool> sn = m.constrainedSnapScale(Snapper::SNAPPOINT_NODE,
919                                                                _snap_points,
920                                                                it,
921                                                                s,
922                                                                _origin_for_specpoints);
924         if (bb.second || sn.second) { // If we snapped to something
925             /* Choose the smaller difference in scale.  Since s[X] == s[Y] we can
926             ** just compare difference in s[X].
927             */
928             double const bd = bb.second ? fabs(bb.first[NR::X] - s[NR::X]) : NR_HUGE;
929             double const sd = sn.second ? fabs(sn.first[NR::X] - s[NR::X]) : NR_HUGE;
930             s = (bd < sd) ? bb.first : sn.first;
931         }
933     } else {
934         /* Scale aspect ratio is unlocked */
936         std::pair<NR::scale, bool> bb = m.freeSnapScale(Snapper::SNAPPOINT_BBOX,
937                                                         _bbox_points,
938                                                         it,
939                                                         s,
940                                                         _origin_for_bboxpoints);
941         std::pair<NR::scale, bool> sn = m.freeSnapScale(Snapper::SNAPPOINT_NODE,
942                                                         _snap_points,
943                                                         it,
944                                                         s,
945                                                         _origin_for_specpoints);
947         if (bb.second || sn.second) { // If we snapped to something
948             /* Pick the snap that puts us closest to the original scale */
949             NR::Coord bd = bb.second ?
950                 fabs(NR::L2(NR::Point(bb.first[NR::X], bb.first[NR::Y])) -
951                      NR::L2(NR::Point(s[NR::X], s[NR::Y])))
952                 : NR_HUGE;
953             NR::Coord sd = sn.second ?
954                 fabs(NR::L2(NR::Point(sn.first[NR::X], sn.first[NR::Y])) -
955                      NR::L2(NR::Point(s[NR::X], s[NR::Y])))
956                 : NR_HUGE;
957             s = (bd < sd) ? bb.first : sn.first;
958         }
959     }
961     /* Update the knot position */
962     pt = ( _point - _origin ) * s + _origin;
964     /* Status text */
965     _message_context.setF(Inkscape::NORMAL_MESSAGE,
966                           _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
967                           100 * s[NR::X], 100 * s[NR::Y]);
969     return TRUE;
972 gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, NR::Point &pt, guint state)
974     using NR::X;
975     using NR::Y;
977     NR::Dim2 axis, perp;
979     switch (handle.cursor) {
980         case GDK_TOP_SIDE:
981         case GDK_BOTTOM_SIDE:
982            axis = NR::Y;
983            perp = NR::X;
984            break;
985         case GDK_LEFT_SIDE:
986         case GDK_RIGHT_SIDE:
987            axis = NR::X;
988            perp = NR::Y;
989            break;
990         default:
991             g_assert_not_reached();
992             return TRUE;
993     };
995     if ( fabs( _point[axis] - _origin[axis] ) < 1e-15 ) {
996         return FALSE;
997     }
999     NR::scale s(1, 1);
1000     s[axis] = ( ( pt[axis] - _origin[axis] )
1001                 / ( _point[axis] - _origin[axis] ) );
1002     if ( fabs(s[axis]) < 1e-15 ) {
1003         s[axis] = 1e-15;
1004     }
1006     if (state & GDK_MOD1_MASK) { // scale by an integer multiplier/divider
1007         if (fabs(s[axis]) > 1)
1008             s[axis] = round(s[axis]);
1009         else
1010             s[axis] = 1/round(1/(MIN(s[axis], 10)));
1011     }
1013     /* Get a STL list of the selected items.
1014     ** FIXME: this should probably be done by Inkscape::Selection.
1015     */
1016     std::list<SPItem const*> it;
1017     for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
1018         it.push_back(reinterpret_cast<SPItem*>(i->data));
1019     }
1021     SnapManager const &m = _desktop->namedview->snap_manager;
1023     if ( state & GDK_CONTROL_MASK ) {
1024         // on ctrl, apply symmetrical scaling instead of stretching
1025         s[perp] = fabs(s[axis]);
1027         std::pair<NR::Coord, bool> const bb = m.constrainedSnapStretch(
1028             Snapper::SNAPPOINT_BBOX,
1029             _bbox_points,
1030             it,
1031             s[axis],
1032             _origin_for_bboxpoints,
1033             axis,
1034             true);
1036         std::pair<NR::Coord, bool> const sn = m.constrainedSnapStretch(
1037             Snapper::SNAPPOINT_NODE,
1038             _snap_points,
1039             it,
1040             s[axis],
1041             _origin_for_specpoints,
1042             axis,
1043             true);
1045         if (bb.second || sn.second) { // If we snapped to something
1046             /* Choose the smaller difference in scale */
1047             NR::Coord const bd = bb.second ? fabs(bb.first - s[axis]) : NR_HUGE;
1048             NR::Coord const sd = sn.second ? fabs(sn.first - s[axis]) : NR_HUGE;
1049             NR::Coord const ratio = (bd < sd) ? bb.first : sn.first;
1050             
1051             if (fabs(ratio) < NR_HUGE) {
1052                 s[axis] = fabs(ratio) * sign(s[axis]);
1053             }
1054             s[perp] = fabs(s[axis]);
1055         }
1056     } else {
1058         std::pair<NR::Coord, bool> const bb = m.constrainedSnapStretch(
1059             Snapper::SNAPPOINT_BBOX,
1060             _bbox_points,
1061             it,
1062             s[axis],
1063             _origin_for_bboxpoints,
1064             axis,
1065             false);
1067         std::pair<NR::Coord, bool> const sn = m.constrainedSnapStretch(
1068             Snapper::SNAPPOINT_NODE,
1069             _snap_points,
1070             it,
1071             s[axis],
1072             _origin_for_specpoints,
1073             axis,
1074             false);
1076         if (bb.second || sn.second) { // If we snapped to something
1077             /* Choose the smaller difference in scale */
1078             NR::Coord const bd = bb.second ? fabs(bb.first - s[axis]) : NR_HUGE;
1079             NR::Coord const sd = sn.second ? fabs(sn.first - s[axis]) : NR_HUGE;
1080             NR::Coord const nw = (bd < sd) ? bb.first : sn.first; // new stretch scale
1081             if (fabs(nw) < NR_HUGE) {
1082                 s[axis] = nw;
1083             }
1084             s[perp] = 1;
1085         }
1086     }
1088     pt = ( _point - _origin ) * NR::scale(s) + _origin;
1089     if (isNaN(pt[X] + pt[Y])) {
1090         g_warning("point=(%g, %g), norm=(%g, %g), s=(%g, %g)\n",
1091                   _point[X], _point[Y], _origin[X], _origin[Y], s[X], s[Y]);
1092     }
1094     // status text
1095     _message_context.setF(Inkscape::NORMAL_MESSAGE,
1096                           _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
1097                           100 * s[NR::X], 100 * s[NR::Y]);
1099     return TRUE;
1102 gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, NR::Point &pt, guint state)
1104     using NR::X;
1105     using NR::Y;
1107     if (handle.cursor != GDK_SB_V_DOUBLE_ARROW && handle.cursor != GDK_SB_H_DOUBLE_ARROW) {
1108         return FALSE;
1109     }
1111     NR::Dim2 dim_a;
1112     NR::Dim2 dim_b;
1113     if (handle.cursor == GDK_SB_V_DOUBLE_ARROW) {
1114         dim_a = X;
1115         dim_b = Y;
1116     } else {
1117         dim_a = Y;
1118         dim_b = X;
1119     }
1121     double skew[2];
1122     double s[2] = { 1.0, 1.0 };
1124     if (fabs(_point[dim_a] - _origin[dim_a]) < NR_EPSILON) {
1125         return FALSE;
1126     }
1128     skew[dim_a] = ( pt[dim_b] - _point[dim_b] ) / ( _point[dim_a] - _origin[dim_a] );
1130     s[dim_a] = ( pt[dim_a] - _origin[dim_a] ) / ( _point[dim_a] - _origin[dim_a] );
1132     if ( fabs(s[dim_a]) < 1 ) {
1133         s[dim_a] = sign(s[dim_a]);
1134     } else {
1135         s[dim_a] = floor( s[dim_a] + 0.5 );
1136     }
1138     double radians = atan(skew[dim_a] / s[dim_a]);
1140     if (state & GDK_CONTROL_MASK) {
1142         int snaps = prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12);
1144         if (snaps) {
1145             double sections = floor( radians * snaps / M_PI + .5 );
1146             if (fabs(sections) >= snaps / 2) sections = sign(sections) * (snaps / 2 - 1);
1147             radians = ( M_PI / snaps ) * sections;
1148         }
1149         skew[dim_a] = tan(radians) * s[dim_a];
1150     } else {
1151         /* Get a STL list of the selected items.
1152             ** FIXME: this should probably be done by Inkscape::Selection.
1153             */
1154             std::list<SPItem const*> it;
1155             for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
1156                 it.push_back(reinterpret_cast<SPItem*>(i->data));
1157             }
1158         
1159         SnapManager const &m = _desktop->namedview->snap_manager;
1161         std::pair<NR::Coord, bool> bb = m.freeSnapSkew(Inkscape::Snapper::SNAPPOINT_BBOX,
1162                                                        _bbox_points,
1163                                                        it,
1164                                                        skew[dim_a],
1165                                                        _origin_for_bboxpoints,
1166                                                        dim_b);
1168         std::pair<NR::Coord, bool> sn = m.freeSnapSkew(Inkscape::Snapper::SNAPPOINT_NODE,
1169                                                        _snap_points,
1170                                                        it,
1171                                                        skew[dim_a],
1172                                                        _origin_for_specpoints,
1173                                                        dim_b);
1175         if (bb.second || sn.second) {
1176             /* We snapped something, so change the skew to reflect it */
1177             NR::Coord const bd = bb.second ? bb.first : NR_HUGE;
1178             NR::Coord const sd = sn.second ? sn.first : NR_HUGE;
1179             skew[dim_a] = std::min(bd, sd);
1180         }
1181     }
1183     pt[dim_b] = ( _point[dim_a] - _origin[dim_a] ) * skew[dim_a] + _point[dim_b];
1184     pt[dim_a] = ( _point[dim_a] - _origin[dim_a] ) * s[dim_a] + _origin[dim_a];
1186     /* status text */
1187     double degrees = 180 / M_PI * radians;
1188     if (degrees > 180) degrees -= 360;
1189     if (degrees < -180) degrees += 360;
1191     _message_context.setF(Inkscape::NORMAL_MESSAGE,
1192                           // TRANSLATORS: don't modify the first ";"
1193                           // (it will NOT be displayed as ";" - only the second one will be)
1194                           _("<b>Skew</b>: %0.2f&#176;; with <b>Ctrl</b> to snap angle"),
1195                           degrees);
1197     return TRUE;
1200 gboolean Inkscape::SelTrans::rotateRequest(NR::Point &pt, guint state)
1202     int snaps = prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12);
1204     // rotate affine in rotate
1205     NR::Point const d1 = _point - _origin;
1206     NR::Point const d2 = pt     - _origin;
1208     NR::Coord const h1 = NR::L2(d1);
1209     if (h1 < 1e-15) return FALSE;
1210     NR::Point q1 = d1 / h1;
1211     NR::Coord const h2 = NR::L2(d2);
1212     if (fabs(h2) < 1e-15) return FALSE;
1213     NR::Point q2 = d2 / h2;
1215     double radians;
1216     if (state & GDK_CONTROL_MASK) {
1217         /* Have to restrict movement. */
1218         double cos_t = NR::dot(q1, q2);
1219         double sin_t = NR::dot(NR::rot90(q1), q2);
1220         radians = atan2(sin_t, cos_t);
1221         if (snaps) {
1222             radians = ( M_PI / snaps ) * floor( radians * snaps / M_PI + .5 );
1223         }
1224         q1 = NR::Point(1, 0);
1225         q2 = NR::Point(cos(radians), sin(radians));
1226     } else {
1227         radians = atan2(NR::dot(NR::rot90(d1), d2),
1228                         NR::dot(d1, d2));
1229     }
1231     NR::rotate const r1(q1);
1232     NR::rotate const r2(q2);
1233     pt = _point * NR::translate(-_origin) * ( r2 / r1 ) * NR::translate(_origin);
1235     /* status text */
1236     double degrees = 180 / M_PI * radians;
1237     if (degrees > 180) degrees -= 360;
1238     if (degrees < -180) degrees += 360;
1240     _message_context.setF(Inkscape::NORMAL_MESSAGE,
1241                           // TRANSLATORS: don't modify the first ";"
1242                           // (it will NOT be displayed as ";" - only the second one will be)
1243                           _("<b>Rotate</b>: %0.2f&#176;; with <b>Ctrl</b> to snap angle"), degrees);
1245     return TRUE;
1248 gboolean Inkscape::SelTrans::centerRequest(NR::Point &pt, guint state)
1250     using NR::X;
1251     using NR::Y;
1253     SnapManager const &m = _desktop->namedview->snap_manager;
1254     pt = m.freeSnap(Snapper::SNAPPOINT_NODE, pt, NULL).getPoint();
1256     if (state & GDK_CONTROL_MASK) {
1257         if ( fabs(_point[X] - pt[X]) > fabs(_point[Y] - pt[Y]) ) {
1258             pt[Y] = _point[Y];
1259         } else {
1260             pt[X] = _point[X];
1261         }
1262     }
1264     if ( !(state & GDK_SHIFT_MASK) && _bbox ) {
1265         // screen pixels to snap center to bbox
1266 #define SNAP_DIST 5
1267         // FIXME: take from prefs
1268         double snap_dist = SNAP_DIST / _desktop->current_zoom();
1270         for (int i = 0; i < 2; i++) {
1271             if (fabs(pt[i] - _bbox->min()[i]) < snap_dist) {
1272                 pt[i] = _bbox->min()[i];
1273             }
1274             if (fabs(pt[i] - _bbox->midpoint()[i]) < snap_dist) {
1275                 pt[i] = _bbox->midpoint()[i];
1276             }
1277             if (fabs(pt[i] - _bbox->max()[i]) < snap_dist) {
1278                 pt[i] = _bbox->max()[i];
1279             }
1280         }
1281     }
1283     // status text
1284     GString *xs = SP_PX_TO_METRIC_STRING(pt[X], _desktop->namedview->getDefaultMetric());
1285     GString *ys = SP_PX_TO_METRIC_STRING(pt[Y], _desktop->namedview->getDefaultMetric());
1286     _message_context.setF(Inkscape::NORMAL_MESSAGE, _("Move <b>center</b> to %s, %s"), xs->str, ys->str);
1287     g_string_free(xs, FALSE);
1288     g_string_free(ys, FALSE);
1290     return TRUE;
1293 /*
1294  * handlers for handle movement
1295  *
1296  */
1298 void sp_sel_trans_stretch(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, NR::Point &pt, guint state)
1300     seltrans->stretch(handle, pt, state);
1303 void sp_sel_trans_scale(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
1305     seltrans->scale(pt, state);
1308 void sp_sel_trans_skew(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, NR::Point &pt, guint state)
1310     seltrans->skew(handle, pt, state);
1313 void sp_sel_trans_rotate(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
1315     seltrans->rotate(pt, state);
1318 void Inkscape::SelTrans::stretch(SPSelTransHandle const &handle, NR::Point &pt, guint state)
1320     using NR::X;
1321     using NR::Y;
1323     NR::Dim2 dim;
1324     switch (handle.cursor) {
1325         case GDK_LEFT_SIDE:
1326         case GDK_RIGHT_SIDE:
1327             dim = X;
1328             break;
1329         case GDK_TOP_SIDE:
1330         case GDK_BOTTOM_SIDE:
1331             dim = Y;
1332             break;
1333         default:
1334             g_assert_not_reached();
1335             abort();
1336             break;
1337     }
1339     NR::Point const scale_origin(_origin);
1340     double const offset = _point[dim] - scale_origin[dim];
1341     if (!( fabs(offset) >= 1e-15 )) {
1342         return;
1343     }
1344     NR::scale s(1, 1);
1345     s[dim] = ( pt[dim] - scale_origin[dim] ) / offset;
1346     if (isNaN(s[dim])) {
1347         g_warning("s[dim]=%g, pt[dim]=%g, scale_origin[dim]=%g, point[dim]=%g\n",
1348                   s[dim], pt[dim], scale_origin[dim], _point[dim]);
1349     }
1350     if (!( fabs(s[dim]) >= 1e-15 )) {
1351         s[dim] = 1e-15;
1352     }
1353     if (state & GDK_CONTROL_MASK) {
1354         /* Preserve aspect ratio, but never flip in the dimension not being edited. */
1355         s[!dim] = fabs(s[dim]);
1356     }
1358     if (!_bbox) {
1359         return;
1360     }
1362     NR::Point new_bbox_min = _approximate_bbox->min() * (NR::translate(-scale_origin) * NR::Matrix(s) * NR::translate(scale_origin));
1363     NR::Point new_bbox_max = _approximate_bbox->max() * (NR::translate(-scale_origin) * NR::Matrix(s) * NR::translate(scale_origin));
1365     int transform_stroke = false;
1366     gdouble strokewidth = 0;
1368     if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
1369         transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1370         strokewidth = _strokewidth;
1371     }
1373     NR::Matrix scaler = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
1374                     new_bbox_min[NR::X], new_bbox_min[NR::Y], new_bbox_max[NR::X], new_bbox_max[NR::Y]);
1376     transform(scaler, NR::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1379 void Inkscape::SelTrans::scale(NR::Point &pt, guint /*state*/)
1381     if (!_bbox) {
1382         return;
1383     }
1385     NR::Point const offset = _point - _origin;
1387     NR::scale s (1, 1);
1388     for (int i = NR::X; i <= NR::Y; i++) {
1389         if (fabs(offset[i]) > 1e-9)
1390             s[i] = (pt[i] - _origin[i]) / offset[i];
1391         if (fabs(s[i]) < 1e-9)
1392             s[i] = 1e-9;
1393     }
1395     NR::Point new_bbox_min = _approximate_bbox->min() * (NR::translate(-_origin) * NR::Matrix(s) * NR::translate(_origin));
1396     NR::Point new_bbox_max = _approximate_bbox->max() * (NR::translate(-_origin) * NR::Matrix(s) * NR::translate(_origin));
1398     int transform_stroke = false;
1399     gdouble strokewidth = 0;
1401     if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
1402         transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
1403         strokewidth = _strokewidth;
1404     }
1406     NR::Matrix scaler = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
1407                     new_bbox_min[NR::X], new_bbox_min[NR::Y], new_bbox_max[NR::X], new_bbox_max[NR::Y]);
1409     transform(scaler, NR::Point(0, 0)); // we have already accounted for origin, so pass 0,0
1412 void Inkscape::SelTrans::skew(SPSelTransHandle const &handle, NR::Point &pt, guint /*state*/)
1414     NR::Point const offset = _point - _origin;
1416     unsigned dim;
1417     switch (handle.cursor) {
1418         case GDK_SB_H_DOUBLE_ARROW:
1419             dim = NR::Y;
1420             break;
1421         case GDK_SB_V_DOUBLE_ARROW:
1422             dim = NR::X;
1423             break;
1424         default:
1425             g_assert_not_reached();
1426             abort();
1427             break;
1428     }
1429     if (fabs(offset[dim]) < 1e-15) {
1430         return;
1431     }
1432     NR::Matrix skew = NR::identity();
1433     skew[2*dim + dim] = (pt[dim] - _origin[dim]) / offset[dim];
1434     skew[2*dim + (1-dim)] = (pt[1-dim] - _point[1-dim]) / offset[dim];
1435     skew[2*(1-dim) + (dim)] = 0;
1436     skew[2*(1-dim) + (1-dim)] = 1;
1438     for (int i = 0; i < 2; i++) {
1439         if (fabs(skew[3*i]) < 1e-15) {
1440             skew[3*i] = 1e-15;
1441         }
1442     }
1443     transform(skew, _origin);
1446 void Inkscape::SelTrans::rotate(NR::Point &pt, guint /*state*/)
1448     NR::Point const offset = _point - _origin;
1450     NR::Coord const h1 = NR::L2(offset);
1451     if (h1 < 1e-15) {
1452         return;
1453     }
1454     NR::Point const q1 = offset / h1;
1455     NR::Coord const h2 = NR::L2( pt - _origin );
1456     if (h2 < 1e-15) {
1457         return;
1458     }
1459     NR::Point const q2 = (pt - _origin) / h2;
1460     NR::rotate const r1(q1);
1461     NR::rotate const r2(q2);
1463     NR::Matrix rotate( r2 / r1 );
1464     transform(rotate, _origin);
1467 void sp_sel_trans_center(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint /*state*/)
1469     seltrans->setCenter(pt);
1473 void Inkscape::SelTrans::moveTo(NR::Point const &xy, guint state)
1475     SnapManager const &m = _desktop->namedview->snap_manager;
1477     /* The amount that we've moved by during this drag */
1478     NR::Point dxy = xy - _point;
1480     /* Get a STL list of the selected items.
1481     ** FIXME: this should probably be done by Inkscape::Selection.
1482     */
1483     std::list<SPItem const*> it;
1484     for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
1485         it.push_back(reinterpret_cast<SPItem*>(i->data));
1486     }
1488     bool const alt = (state & GDK_MOD1_MASK);
1489     bool const control = (state & GDK_CONTROL_MASK);
1490     bool const shift = (state & GDK_SHIFT_MASK);
1492     if (alt) {
1494         /* Alt pressed means keep offset: snap the moved distance to the grid.
1495         ** FIXME: this will snap to more than just the grid, nowadays.
1496         */
1498         dxy = m.freeSnap(Snapper::SNAPPOINT_NODE, dxy, NULL).getPoint();
1500     } else if (!shift) {
1502         /* We're snapping to things, possibly with a constraint to horizontal or
1503         ** vertical movement.  Obtain a list of possible translations and then
1504         ** pick the smallest.
1505         */
1507         /* This will be our list of possible translations */
1508         std::list<std::pair<NR::Point, bool> > s;
1510         if (control) {
1512             /* Snap to things, and also constrain to horizontal or vertical movement */
1514             for (unsigned int dim = 0; dim < 2; dim++) {
1515                 s.push_back(m.constrainedSnapTranslation(Inkscape::Snapper::SNAPPOINT_BBOX,
1516                                                          _bbox_points,
1517                                                          it,
1518                                                          Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1519                                                          dxy));
1521                 s.push_back(m.constrainedSnapTranslation(Inkscape::Snapper::SNAPPOINT_NODE,
1522                                                          _snap_points,
1523                                                          it,
1524                                                          Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
1525                                                          dxy));
1526             }
1528         } else {
1530             // Let's leave this timer code here for a while. I'll probably need it in the near future (Diederik van Lierop)
1531             /* GTimeVal starttime;
1532             GTimeVal endtime;
1533                 g_get_current_time(&starttime); */
1535             /* Snap to things with no constraint */
1536                         s.push_back(m.freeSnapTranslation(Inkscape::Snapper::SNAPPOINT_BBOX,
1537                                               _bbox_points, it, dxy));
1538             s.push_back(m.freeSnapTranslation(Inkscape::Snapper::SNAPPOINT_NODE,
1539                                               _snap_points, it, dxy));
1541                 /*g_get_current_time(&endtime);
1542                 double elapsed = ((((double)endtime.tv_sec - starttime.tv_sec) * G_USEC_PER_SEC + (endtime.tv_usec - starttime.tv_usec))) / 1000.0;
1543                 std::cout << "Time spent snapping: " << elapsed << std::endl; */
1544         }
1546         /* Pick one */
1547         NR::Coord best = NR_HUGE;
1548         for (std::list<std::pair<NR::Point, bool> >::const_iterator i = s.begin(); i != s.end(); i++) {
1549             if (i->second) {
1550                 NR::Coord const m = NR::L2(i->first);
1551                 if (m < best) {
1552                     best = m;
1553                     dxy = i->first;
1554                 }
1555             }
1556         }
1557     }
1559     if (control) {
1560         /* Ensure that the horizontal and vertical constraint has been applied */
1561         if (fabs(dxy[NR::X]) > fabs(dxy[NR::Y])) {
1562             dxy[NR::Y] = 0;
1563         } else {
1564             dxy[NR::X] = 0;
1565         }
1566     }
1568     NR::Matrix const move((NR::translate(dxy)));
1569     NR::Point const norm(0, 0);
1570     transform(move, norm);
1572     // status text
1573     GString *xs = SP_PX_TO_METRIC_STRING(dxy[NR::X], _desktop->namedview->getDefaultMetric());
1574     GString *ys = SP_PX_TO_METRIC_STRING(dxy[NR::Y], _desktop->namedview->getDefaultMetric());
1575     _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);
1576     g_string_free(xs, TRUE);
1577     g_string_free(ys, TRUE);
1581 /*
1582   Local Variables:
1583   mode:c++
1584   c-file-style:"stroustrup"
1585   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1586   indent-tabs-mode:nil
1587   fill-column:99
1588   End:
1589 */
1590 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :