Code

First GSoC node tool commit to Bazaar
[inkscape.git] / src / ui / dialog / align-and-distribute.cpp
1 /** @file
2  * @brief Align and Distribute dialog - implementation
3  */
4 /* Authors:
5  *   Bryce W. Harrington <bryce@bryceharrington.org>
6  *   Aubanel MONNIER <aubi@libertysurf.fr>
7  *   Frank Felfe <innerspace@iname.com>
8  *   Lauris Kaplinski <lauris@kaplinski.com>
9  *   Tim Dwyer <tgdwyer@gmail.com>
10  *
11  * Copyright (C) 1999-2004, 2005 Authors
12  *
13  * Released under GNU GPL.  Read the file 'COPYING' for more information.
14  */
17 #ifdef HAVE_CONFIG_H
18 # include <config.h>
19 #endif
21 #include <gtkmm/spinbutton.h>
23 #include "desktop-handles.h"
24 #include "unclump.h"
25 #include "document.h"
26 #include "enums.h"
27 #include "graphlayout/graphlayout.h"
28 #include "inkscape.h"
29 #include "macros.h"
30 #include "preferences.h"
31 #include "removeoverlap/removeoverlap.h"
32 #include "selection.h"
33 #include "sp-flowtext.h"
34 #include "sp-item-transform.h"
35 #include "sp-text.h"
36 #include "text-editing.h"
37 #include "tools-switch.h"
38 #include "ui/icon-names.h"
39 #include "ui/tool/node-tool.h"
40 #include "ui/tool/multi-path-manipulator.h"
41 #include "util/glib-list-iterators.h"
42 #include "verbs.h"
43 #include "widgets/icon.h"
45 #include "align-and-distribute.h"
47 namespace Inkscape {
48 namespace UI {
49 namespace Dialog {
51 /////////helper classes//////////////////////////////////
53 class Action {
54 public :
55     Action(const Glib::ustring &id,
56            const Glib::ustring &tiptext,
57            guint row, guint column,
58            Gtk::Table &parent,
59            Gtk::Tooltips &tooltips,
60            AlignAndDistribute &dialog):
61         _dialog(dialog),
62         _id(id),
63         _parent(parent)
64     {
65         Gtk::Widget*  pIcon = Gtk::manage( sp_icon_get_icon( _id, Inkscape::ICON_SIZE_LARGE_TOOLBAR) );
66         Gtk::Button * pButton = Gtk::manage(new Gtk::Button());
67         pButton->set_relief(Gtk::RELIEF_NONE);
68         pIcon->show();
69         pButton->add(*pIcon);
70         pButton->show();
72         pButton->signal_clicked()
73             .connect(sigc::mem_fun(*this, &Action::on_button_click));
74         tooltips.set_tip(*pButton, tiptext);
75         parent.attach(*pButton, column, column+1, row, row+1, Gtk::FILL, Gtk::FILL);
76     }
77     virtual ~Action(){}
79     AlignAndDistribute &_dialog;
81 private :
82     virtual void on_button_click(){}
84     Glib::ustring _id;
85     Gtk::Table &_parent;
86 };
89 class ActionAlign : public Action {
90 public :
91     struct Coeffs {
92        double mx0, mx1, my0, my1;
93        double sx0, sx1, sy0, sy1;
94     };
95     ActionAlign(const Glib::ustring &id,
96                 const Glib::ustring &tiptext,
97                 guint row, guint column,
98                 AlignAndDistribute &dialog,
99                 guint coeffIndex):
100         Action(id, tiptext, row, column,
101                dialog.align_table(), dialog.tooltips(), dialog),
102         _index(coeffIndex),
103         _dialog(dialog)
104     {}
106 private :
108     virtual void on_button_click() {
109         //Retreive selected objects
110         SPDesktop *desktop = _dialog.getDesktop();
111         if (!desktop) return;
113         Inkscape::Selection *selection = sp_desktop_selection(desktop);
114         if (!selection) return;
116         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
117         bool sel_as_group = prefs->getBool("/dialogs/align/sel-as-groups");
119         using Inkscape::Util::GSListConstIterator;
120         std::list<SPItem *> selected;
121         selected.insert<GSListConstIterator<SPItem *> >(selected.end(), selection->itemList(), NULL);
122         if (selected.empty()) return;
124         Geom::Point mp; //Anchor point
125         AlignAndDistribute::AlignTarget target = _dialog.getAlignTarget();
126         const Coeffs &a= _allCoeffs[_index];
127         switch (target)
128         {
129         case AlignAndDistribute::LAST:
130         case AlignAndDistribute::FIRST:
131         case AlignAndDistribute::BIGGEST:
132         case AlignAndDistribute::SMALLEST:
133         {
134             //Check 2 or more selected objects
135             std::list<SPItem *>::iterator second(selected.begin());
136             ++second;
137             if (second == selected.end())
138                 return;
139             //Find the master (anchor on which the other objects are aligned)
140             std::list<SPItem *>::iterator master(
141                 _dialog.find_master (
142                     selected,
143                     (a.mx0 != 0.0) ||
144                     (a.mx1 != 0.0) )
145                 );
146             //remove the master from the selection
147             SPItem * thing = *master;
148             // TODO: either uncomment or remove the following commented lines, depending on which
149             //       behaviour of moving objects makes most sense; also cf. discussion at
150             //       https://bugs.launchpad.net/inkscape/+bug/255933
151             /*if (!sel_as_group) { */
152                 selected.erase(master);
153             /*}*/
154             //Compute the anchor point
155             Geom::OptRect b = sp_item_bbox_desktop (thing);
156             if (b) {
157                 mp = Geom::Point(a.mx0 * b->min()[Geom::X] + a.mx1 * b->max()[Geom::X],
158                                a.my0 * b->min()[Geom::Y] + a.my1 * b->max()[Geom::Y]);
159             } else {
160                 return;
161             }
162             break;
163         }
165         case AlignAndDistribute::PAGE:
166             mp = Geom::Point(a.mx1 * sp_document_width(sp_desktop_document(desktop)),
167                            a.my1 * sp_document_height(sp_desktop_document(desktop)));
168             break;
170         case AlignAndDistribute::DRAWING:
171         {
172             Geom::OptRect b = sp_item_bbox_desktop
173                 ( (SPItem *) sp_document_root (sp_desktop_document (desktop)) );
174             if (b) {
175                 mp = Geom::Point(a.mx0 * b->min()[Geom::X] + a.mx1 * b->max()[Geom::X],
176                                a.my0 * b->min()[Geom::Y] + a.my1 * b->max()[Geom::Y]);
177             } else {
178                 return;
179             }
180             break;
181         }
183         case AlignAndDistribute::SELECTION:
184         {
185             Geom::OptRect b =  selection->bounds();
186             if (b) {
187                 mp = Geom::Point(a.mx0 * b->min()[Geom::X] + a.mx1 * b->max()[Geom::X],
188                                a.my0 * b->min()[Geom::Y] + a.my1 * b->max()[Geom::Y]);
189             } else {
190                 return;
191             }
192             break;
193         }
195         default:
196             g_assert_not_reached ();
197             break;
198         };  // end of switch
200         // Top hack: temporarily set clone compensation to unmoved, so that we can align/distribute
201         // clones with their original (and the move of the original does not disturb the
202         // clones). The only problem with this is that if there are outside-of-selection clones of
203         // a selected original, they will be unmoved too, possibly contrary to user's
204         // expecation. However this is a minor point compared to making align/distribute always
205         // work as expected, and "unmoved" is the default option anyway.
206         int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
207         prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
209         bool changed = false;
210         Geom::OptRect b;
211         if (sel_as_group)
212             b = selection->bounds();
214         //Move each item in the selected list separately
215         for (std::list<SPItem *>::iterator it(selected.begin());
216              it != selected.end();
217              it++)
218         {
219             sp_document_ensure_up_to_date(sp_desktop_document (desktop));
220             if (!sel_as_group)
221                 b = sp_item_bbox_desktop (*it);
222             if (b) {
223                 Geom::Point const sp(a.sx0 * b->min()[Geom::X] + a.sx1 * b->max()[Geom::X],
224                                      a.sy0 * b->min()[Geom::Y] + a.sy1 * b->max()[Geom::Y]);
225                 Geom::Point const mp_rel( mp - sp );
226                 if (LInfty(mp_rel) > 1e-9) {
227                     sp_item_move_rel(*it, Geom::Translate(mp_rel));
228                     changed = true;
229                 }
230             }
231         }
233         // restore compensation setting
234         prefs->setInt("/options/clonecompensation/value", saved_compensation);
236         if (changed) {
237             sp_document_done ( sp_desktop_document (desktop) , SP_VERB_DIALOG_ALIGN_DISTRIBUTE,
238                                _("Align"));
239         }
242     }
243     guint _index;
244     AlignAndDistribute &_dialog;
246     static const Coeffs _allCoeffs[10];
248 };
249 ActionAlign::Coeffs const ActionAlign::_allCoeffs[10] = {
250     {1., 0., 0., 0., 0., 1., 0., 0.},
251     {1., 0., 0., 0., 1., 0., 0., 0.},
252     {.5, .5, 0., 0., .5, .5, 0., 0.},
253     {0., 1., 0., 0., 0., 1., 0., 0.},
254     {0., 1., 0., 0., 1., 0., 0., 0.},
255     {0., 0., 0., 1., 0., 0., 1., 0.},
256     {0., 0., 0., 1., 0., 0., 0., 1.},
257     {0., 0., .5, .5, 0., 0., .5, .5},
258     {0., 0., 1., 0., 0., 0., 1., 0.},
259     {0., 0., 1., 0., 0., 0., 0., 1.}
260 };
262 BBoxSort::BBoxSort(SPItem *pItem, Geom::Rect bounds, Geom::Dim2 orientation, double kBegin, double kEnd) :
263         item(pItem),
264         bbox (bounds)
266         anchor = kBegin * bbox.min()[orientation] + kEnd * bbox.max()[orientation];
268 BBoxSort::BBoxSort(const BBoxSort &rhs) :
269         //NOTE :  this copy ctor is called O(sort) when sorting the vector
270         //this is bad. The vector should be a vector of pointers.
271         //But I'll wait the bohem GC before doing that
272         item(rhs.item), anchor(rhs.anchor), bbox(rhs.bbox) 
276 bool operator< (const BBoxSort &a, const BBoxSort &b)
278     return (a.anchor < b.anchor);
281 class ActionDistribute : public Action {
282 public :
283     ActionDistribute(const Glib::ustring &id,
284                      const Glib::ustring &tiptext,
285                      guint row, guint column,
286                      AlignAndDistribute &dialog,
287                      bool onInterSpace,
288                      Geom::Dim2 orientation,
289                      double kBegin, double kEnd
290         ):
291         Action(id, tiptext, row, column,
292                dialog.distribute_table(), dialog.tooltips(), dialog),
293         _dialog(dialog),
294         _onInterSpace(onInterSpace),
295         _orientation(orientation),
296         _kBegin(kBegin),
297         _kEnd( kEnd)
298     {}
300 private :
301     virtual void on_button_click() {
302         //Retreive selected objects
303         SPDesktop *desktop = _dialog.getDesktop();
304         if (!desktop) return;
306         Inkscape::Selection *selection = sp_desktop_selection(desktop);
307         if (!selection) return;
309         using Inkscape::Util::GSListConstIterator;
310         std::list<SPItem *> selected;
311         selected.insert<GSListConstIterator<SPItem *> >(selected.end(), selection->itemList(), NULL);
312         if (selected.empty()) return;
314         //Check 2 or more selected objects
315         std::list<SPItem *>::iterator second(selected.begin());
316         ++second;
317         if (second == selected.end()) return;
320         std::vector< BBoxSort  > sorted;
321         for (std::list<SPItem *>::iterator it(selected.begin());
322             it != selected.end();
323             ++it)
324         {
325             Geom::OptRect bbox = sp_item_bbox_desktop(*it);
326             if (bbox) {
327                 sorted.push_back(BBoxSort(*it, *bbox, _orientation, _kBegin, _kEnd));
328             }
329         }
330         //sort bbox by anchors
331         std::sort(sorted.begin(), sorted.end());
333         // see comment in ActionAlign above
334         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
335         int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
336         prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
338         unsigned int len = sorted.size();
339         bool changed = false;
340         if (_onInterSpace)
341         {
342             //overall bboxes span
343             float dist = (sorted.back().bbox.max()[_orientation] -
344                           sorted.front().bbox.min()[_orientation]);
345             //space eaten by bboxes
346             float span = 0;
347             for (unsigned int i = 0; i < len; i++)
348             {
349                 span += sorted[i].bbox[_orientation].extent();
350             }
351             //new distance between each bbox
352             float step = (dist - span) / (len - 1);
353             float pos = sorted.front().bbox.min()[_orientation];
354             for ( std::vector<BBoxSort> ::iterator it (sorted.begin());
355                   it < sorted.end();
356                   it ++ )
357             {
358                 if (!NR_DF_TEST_CLOSE (pos, it->bbox.min()[_orientation], 1e-6)) {
359                     Geom::Point t(0.0, 0.0);
360                     t[_orientation] = pos - it->bbox.min()[_orientation];
361                     sp_item_move_rel(it->item, Geom::Translate(t));
362                     changed = true;
363                 }
364                 pos += it->bbox[_orientation].extent();
365                 pos += step;
366             }
367         }
368         else
369         {
370             //overall anchor span
371             float dist = sorted.back().anchor - sorted.front().anchor;
372             //distance between anchors
373             float step = dist / (len - 1);
375             for ( unsigned int i = 0; i < len ; i ++ )
376             {
377                 BBoxSort & it(sorted[i]);
378                 //new anchor position
379                 float pos = sorted.front().anchor + i * step;
380                 //Don't move if we are really close
381                 if (!NR_DF_TEST_CLOSE (pos, it.anchor, 1e-6)) {
382                     //Compute translation
383                     Geom::Point t(0.0, 0.0);
384                     t[_orientation] = pos - it.anchor;
385                     //translate
386                     sp_item_move_rel(it.item, Geom::Translate(t));
387                     changed = true;
388                 }
389             }
390         }
392         // restore compensation setting
393         prefs->setInt("/options/clonecompensation/value", saved_compensation);
395         if (changed) {
396             sp_document_done ( sp_desktop_document (desktop), SP_VERB_DIALOG_ALIGN_DISTRIBUTE,
397                                _("Distribute"));
398         }
399     }
400     guint _index;
401     AlignAndDistribute &_dialog;
402     bool _onInterSpace;
403     Geom::Dim2 _orientation;
405     double _kBegin;
406     double _kEnd;
408 };
411 class ActionNode : public Action {
412 public :
413     ActionNode(const Glib::ustring &id,
414                const Glib::ustring &tiptext,
415                guint column,
416                AlignAndDistribute &dialog,
417                Geom::Dim2 orientation, bool distribute):
418         Action(id, tiptext, 0, column,
419                dialog.nodes_table(), dialog.tooltips(), dialog),
420         _orientation(orientation),
421         _distribute(distribute)
422     {}
424 private :
425     Geom::Dim2 _orientation;
426     bool _distribute;
427     virtual void on_button_click()
428     {
430         if (!_dialog.getDesktop()) return;
431         SPEventContext *event_context = sp_desktop_event_context(_dialog.getDesktop());
432         if (!INK_IS_NODE_TOOL (event_context)) return;
433         InkNodeTool *nt = INK_NODE_TOOL(event_context);
435         if (_distribute)
436             nt->_multipath->distributeNodes(_orientation);
437         else
438             nt->_multipath->alignNodes(_orientation);
440     }
441 };
443 class ActionRemoveOverlaps : public Action {
444 private:
445     Gtk::Label removeOverlapXGapLabel;
446     Gtk::Label removeOverlapYGapLabel;
447     Gtk::SpinButton removeOverlapXGap;
448     Gtk::SpinButton removeOverlapYGap;
450 public:
451     ActionRemoveOverlaps(Glib::ustring const &id,
452                          Glib::ustring const &tiptext,
453                          guint row,
454                          guint column,
455                          AlignAndDistribute &dialog) :
456         Action(id, tiptext, row, column + 4,
457                dialog.removeOverlap_table(), dialog.tooltips(), dialog)
458     {
459         dialog.removeOverlap_table().set_col_spacings(3);
461         removeOverlapXGap.set_digits(1);
462         removeOverlapXGap.set_size_request(60, -1);
463         removeOverlapXGap.set_increments(1.0, 0);
464         removeOverlapXGap.set_range(-1000.0, 1000.0);
465         removeOverlapXGap.set_value(0);
466         dialog.tooltips().set_tip(removeOverlapXGap,
467                                   _("Minimum horizontal gap (in px units) between bounding boxes"));
468         //TRANSLATORS: only translate "string" in "context|string".
469         // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
470         // "H:" stands for horizontal gap
471         removeOverlapXGapLabel.set_label(Q_("gap|H:"));
473         removeOverlapYGap.set_digits(1);
474         removeOverlapYGap.set_size_request(60, -1);
475         removeOverlapYGap.set_increments(1.0, 0);
476         removeOverlapYGap.set_range(-1000.0, 1000.0);
477         removeOverlapYGap.set_value(0);
478         dialog.tooltips().set_tip(removeOverlapYGap,
479                                   _("Minimum vertical gap (in px units) between bounding boxes"));
480         /* TRANSLATORS: Vertical gap */
481         removeOverlapYGapLabel.set_label(_("V:"));
483         dialog.removeOverlap_table().attach(removeOverlapXGapLabel, column, column+1, row, row+1, Gtk::FILL, Gtk::FILL);
484         dialog.removeOverlap_table().attach(removeOverlapXGap, column+1, column+2, row, row+1, Gtk::FILL, Gtk::FILL);
485         dialog.removeOverlap_table().attach(removeOverlapYGapLabel, column+2, column+3, row, row+1, Gtk::FILL, Gtk::FILL);
486         dialog.removeOverlap_table().attach(removeOverlapYGap, column+3, column+4, row, row+1, Gtk::FILL, Gtk::FILL);
488     }
490 private :
491     virtual void on_button_click()
492     {
493         if (!_dialog.getDesktop()) return;
495         // see comment in ActionAlign above
496         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
497         int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
498         prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
500         // xGap and yGap are the minimum space required between bounding rectangles.
501         double const xGap = removeOverlapXGap.get_value();
502         double const yGap = removeOverlapYGap.get_value();
503         removeoverlap(sp_desktop_selection(_dialog.getDesktop())->itemList(),
504                       xGap, yGap);
506         // restore compensation setting
507         prefs->setInt("/options/clonecompensation/value", saved_compensation);
509         sp_document_done(sp_desktop_document(_dialog.getDesktop()), SP_VERB_DIALOG_ALIGN_DISTRIBUTE,
510                          _("Remove overlaps"));
511     }
512 };
514 class ActionGraphLayout : public Action {
515 public:
516     ActionGraphLayout(Glib::ustring const &id,
517                          Glib::ustring const &tiptext,
518                          guint row,
519                          guint column,
520                          AlignAndDistribute &dialog) :
521         Action(id, tiptext, row, column + 4,
522                dialog.graphLayout_table(), dialog.tooltips(), dialog)
523     {}
525 private :
526     virtual void on_button_click()
527     {
528         if (!_dialog.getDesktop()) return;
530         // see comment in ActionAlign above
531         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
532         int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
533         prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
535         graphlayout(sp_desktop_selection(_dialog.getDesktop())->itemList());
537         // restore compensation setting
538         prefs->setInt("/options/clonecompensation/value", saved_compensation);
540         sp_document_done(sp_desktop_document(_dialog.getDesktop()), SP_VERB_DIALOG_ALIGN_DISTRIBUTE,
541                          _("Arrange connector network"));
542     }
543 };
545 class ActionUnclump : public Action {
546 public :
547     ActionUnclump(const Glib::ustring &id,
548                const Glib::ustring &tiptext,
549                guint row,
550                guint column,
551                AlignAndDistribute &dialog):
552         Action(id, tiptext, row, column,
553                dialog.distribute_table(), dialog.tooltips(), dialog)
554     {}
556 private :
557     virtual void on_button_click()
558     {
559         if (!_dialog.getDesktop()) return;
561         // see comment in ActionAlign above
562         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
563         int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
564         prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
566         unclump ((GSList *) sp_desktop_selection(_dialog.getDesktop())->itemList());
568         // restore compensation setting
569         prefs->setInt("/options/clonecompensation/value", saved_compensation);
571         sp_document_done (sp_desktop_document (_dialog.getDesktop()), SP_VERB_DIALOG_ALIGN_DISTRIBUTE,
572                           _("Unclump"));
573     }
574 };
576 class ActionRandomize : public Action {
577 public :
578     ActionRandomize(const Glib::ustring &id,
579                const Glib::ustring &tiptext,
580                guint row,
581                guint column,
582                AlignAndDistribute &dialog):
583         Action(id, tiptext, row, column,
584                dialog.distribute_table(), dialog.tooltips(), dialog)
585     {}
587 private :
588     virtual void on_button_click()
589     {
590         SPDesktop *desktop = _dialog.getDesktop();
591         if (!desktop) return;
593         Inkscape::Selection *selection = sp_desktop_selection(desktop);
594         if (!selection) return;
596         using Inkscape::Util::GSListConstIterator;
597         std::list<SPItem *> selected;
598         selected.insert<GSListConstIterator<SPItem *> >(selected.end(), selection->itemList(), NULL);
599         if (selected.empty()) return;
601         //Check 2 or more selected objects
602         if (selected.size() < 2) return;
604         Geom::OptRect sel_bbox = selection->bounds();
605         if (!sel_bbox) {
606             return;
607         }
609         // This bbox is cached between calls to randomize, so that there's no growth nor shrink
610         // nor drift on sequential randomizations. Discard cache on global (or better active
611         // desktop's) selection_change signal.
612         if (!_dialog.randomize_bbox) {
613             _dialog.randomize_bbox = *sel_bbox;
614         }
616         // see comment in ActionAlign above
617         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
618         int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
619         prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
621         for (std::list<SPItem *>::iterator it(selected.begin());
622             it != selected.end();
623             ++it)
624         {
625             sp_document_ensure_up_to_date(sp_desktop_document (desktop));
626             Geom::OptRect item_box = sp_item_bbox_desktop (*it);
627             if (item_box) {
628                 // find new center, staying within bbox
629                 double x = _dialog.randomize_bbox->min()[Geom::X] + (*item_box)[Geom::X].extent() /2 +
630                     g_random_double_range (0, (*_dialog.randomize_bbox)[Geom::X].extent() - (*item_box)[Geom::X].extent());
631                 double y = _dialog.randomize_bbox->min()[Geom::Y] + (*item_box)[Geom::Y].extent()/2 +
632                     g_random_double_range (0, (*_dialog.randomize_bbox)[Geom::Y].extent() - (*item_box)[Geom::Y].extent());
633                 // displacement is the new center minus old:
634                 Geom::Point t = Geom::Point (x, y) - 0.5*(item_box->max() + item_box->min());
635                 sp_item_move_rel(*it, Geom::Translate(t));
636             }
637         }
639         // restore compensation setting
640         prefs->setInt("/options/clonecompensation/value", saved_compensation);
642         sp_document_done (sp_desktop_document (desktop), SP_VERB_DIALOG_ALIGN_DISTRIBUTE,
643                           _("Randomize positions"));
644     }
645 };
647 struct Baselines
649     SPItem *_item;
650     Geom::Point _base;
651     Geom::Dim2 _orientation;
652     Baselines(SPItem *item, Geom::Point base, Geom::Dim2 orientation) :
653         _item (item),
654         _base (base),
655         _orientation (orientation)
656     {}
657 };
659 bool operator< (const Baselines &a, const Baselines &b)
661     return (a._base[a._orientation] < b._base[b._orientation]);
664 class ActionBaseline : public Action {
665 public :
666     ActionBaseline(const Glib::ustring &id,
667                const Glib::ustring &tiptext,
668                guint row,
669                guint column,
670                AlignAndDistribute &dialog,
671                Gtk::Table &table,
672                Geom::Dim2 orientation, bool distribute):
673         Action(id, tiptext, row, column,
674                table, dialog.tooltips(), dialog),
675         _orientation(orientation),
676         _distribute(distribute)
677     {}
679 private :
680     Geom::Dim2 _orientation;
681     bool _distribute;
682     virtual void on_button_click()
683     {
684         SPDesktop *desktop = _dialog.getDesktop();
685         if (!desktop) return;
687         Inkscape::Selection *selection = sp_desktop_selection(desktop);
688         if (!selection) return;
690         using Inkscape::Util::GSListConstIterator;
691         std::list<SPItem *> selected;
692         selected.insert<GSListConstIterator<SPItem *> >(selected.end(), selection->itemList(), NULL);
693         if (selected.empty()) return;
695         //Check 2 or more selected objects
696         if (selected.size() < 2) return;
698         Geom::Point b_min = Geom::Point (HUGE_VAL, HUGE_VAL);
699         Geom::Point b_max = Geom::Point (-HUGE_VAL, -HUGE_VAL);
701         std::vector<Baselines> sorted;
703         for (std::list<SPItem *>::iterator it(selected.begin());
704             it != selected.end();
705             ++it)
706         {
707             if (SP_IS_TEXT (*it) || SP_IS_FLOWTEXT (*it)) {
708                 Inkscape::Text::Layout const *layout = te_get_layout(*it);
709                 Geom::Point base = layout->characterAnchorPoint(layout->begin()) * sp_item_i2d_affine(*it);
710                 if (base[Geom::X] < b_min[Geom::X]) b_min[Geom::X] = base[Geom::X];
711                 if (base[Geom::Y] < b_min[Geom::Y]) b_min[Geom::Y] = base[Geom::Y];
712                 if (base[Geom::X] > b_max[Geom::X]) b_max[Geom::X] = base[Geom::X];
713                 if (base[Geom::Y] > b_max[Geom::Y]) b_max[Geom::Y] = base[Geom::Y];
715                 Baselines b (*it, base, _orientation);
716                 sorted.push_back(b);
717             }
718         }
720         if (sorted.size() <= 1) return;
722         //sort baselines
723         std::sort(sorted.begin(), sorted.end());
725         bool changed = false;
727         if (_distribute) {
728             double step = (b_max[_orientation] - b_min[_orientation])/(sorted.size() - 1);
729             for (unsigned int i = 0; i < sorted.size(); i++) {
730                 SPItem *item = sorted[i]._item;
731                 Geom::Point base = sorted[i]._base;
732                 Geom::Point t(0.0, 0.0);
733                 t[_orientation] = b_min[_orientation] + step * i - base[_orientation];
734                 sp_item_move_rel(item, Geom::Translate(t));
735                 changed = true;
736             }
738             if (changed) {
739                 sp_document_done (sp_desktop_document (desktop), SP_VERB_DIALOG_ALIGN_DISTRIBUTE,
740                                   _("Distribute text baselines"));
741             }
743         } else {
744             for (std::list<SPItem *>::iterator it(selected.begin());
745                  it != selected.end();
746                  ++it)
747             {
748                 if (SP_IS_TEXT (*it) || SP_IS_FLOWTEXT (*it)) {
749                     Inkscape::Text::Layout const *layout = te_get_layout(*it);
750                     Geom::Point base = layout->characterAnchorPoint(layout->begin()) * sp_item_i2d_affine(*it);
751                     Geom::Point t(0.0, 0.0);
752                     t[_orientation] = b_min[_orientation] - base[_orientation];
753                     sp_item_move_rel(*it, Geom::Translate(t));
754                     changed = true;
755                 }
756             }
758             if (changed) {
759                 sp_document_done (sp_desktop_document (desktop), SP_VERB_DIALOG_ALIGN_DISTRIBUTE,
760                                   _("Align text baselines"));
761             }
762         }
763     }
764 };
768 void on_tool_changed(Inkscape::Application */*inkscape*/, SPEventContext */*context*/, AlignAndDistribute *daad)
770     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
771     if (desktop && sp_desktop_event_context(desktop))
772         daad->setMode(tools_active(desktop) == TOOLS_NODES);
775 void on_selection_changed(Inkscape::Application */*inkscape*/, Inkscape::Selection */*selection*/, AlignAndDistribute *daad)
777     daad->randomize_bbox = Geom::OptRect();
780 /////////////////////////////////////////////////////////
785 AlignAndDistribute::AlignAndDistribute()
786     : UI::Widget::Panel ("", "/dialogs/align", SP_VERB_DIALOG_ALIGN_DISTRIBUTE),
787       randomize_bbox(),
788       _alignFrame(_("Align")),
789       _distributeFrame(_("Distribute")),
790       _removeOverlapFrame(_("Remove overlaps")),
791       _graphLayoutFrame(_("Connector network layout")),
792       _nodesFrame(_("Nodes")),
793       _alignTable(2, 6, true),
794       _distributeTable(3, 6, true),
795       _removeOverlapTable(1, 5, false),
796       _graphLayoutTable(1, 5, false),
797       _nodesTable(1, 4, true),
798       _anchorLabel(_("Relative to: ")),
799       _selgrpLabel(_("Treat selection as group: "))
801     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
803     //Instanciate the align buttons
804     addAlignButton(INKSCAPE_ICON_ALIGN_HORIZONTAL_RIGHT_TO_ANCHOR,
805                    _("Align right edges of objects to the left edge of the anchor"),
806                    0, 0);
807     addAlignButton(INKSCAPE_ICON_ALIGN_HORIZONTAL_LEFT,
808                    _("Align left edges"),
809                    0, 1);
810     addAlignButton(INKSCAPE_ICON_ALIGN_HORIZONTAL_CENTER,
811                    _("Center objects horizontally"),
812                    0, 2);
813     addAlignButton(INKSCAPE_ICON_ALIGN_HORIZONTAL_RIGHT,
814                    _("Align right sides"),
815                    0, 3);
816     addAlignButton(INKSCAPE_ICON_ALIGN_HORIZONTAL_LEFT_TO_ANCHOR,
817                    _("Align left edges of objects to the right edge of the anchor"),
818                    0, 4);
819     addAlignButton(INKSCAPE_ICON_ALIGN_VERTICAL_BOTTOM_TO_ANCHOR,
820                    _("Align bottom edges of objects to the top edge of the anchor"),
821                    1, 0);
822     addAlignButton(INKSCAPE_ICON_ALIGN_VERTICAL_TOP,
823                    _("Align top edges"),
824                    1, 1);
825     addAlignButton(INKSCAPE_ICON_ALIGN_VERTICAL_CENTER,
826                    _("Center on horizontal axis"),
827                    1, 2);
828     addAlignButton(INKSCAPE_ICON_ALIGN_VERTICAL_BOTTOM,
829                    _("Align bottom edges"),
830                    1, 3);
831     addAlignButton(INKSCAPE_ICON_ALIGN_VERTICAL_TOP_TO_ANCHOR,
832                    _("Align top edges of objects to the bottom edge of the anchor"),
833                    1, 4);
835     //Baseline aligns
836     addBaselineButton(INKSCAPE_ICON_ALIGN_HORIZONTAL_BASELINE,
837                    _("Align baseline anchors of texts horizontally"),
838                       0, 5, this->align_table(), Geom::X, false);
839     addBaselineButton(INKSCAPE_ICON_ALIGN_VERTICAL_BASELINE,
840                    _("Align baselines of texts"),
841                      1, 5, this->align_table(), Geom::Y, false);
843     //The distribute buttons
844     addDistributeButton(INKSCAPE_ICON_DISTRIBUTE_HORIZONTAL_GAPS,
845                         _("Make horizontal gaps between objects equal"),
846                         0, 4, true, Geom::X, .5, .5);
848     addDistributeButton(INKSCAPE_ICON_DISTRIBUTE_HORIZONTAL_LEFT,
849                         _("Distribute left edges equidistantly"),
850                         0, 1, false, Geom::X, 1., 0.);
851     addDistributeButton(INKSCAPE_ICON_DISTRIBUTE_HORIZONTAL_CENTER,
852                         _("Distribute centers equidistantly horizontally"),
853                         0, 2, false, Geom::X, .5, .5);
854     addDistributeButton(INKSCAPE_ICON_DISTRIBUTE_HORIZONTAL_RIGHT,
855                         _("Distribute right edges equidistantly"),
856                         0, 3, false, Geom::X, 0., 1.);
858     addDistributeButton(INKSCAPE_ICON_DISTRIBUTE_VERTICAL_GAPS,
859                         _("Make vertical gaps between objects equal"),
860                         1, 4, true, Geom::Y, .5, .5);
862     addDistributeButton(INKSCAPE_ICON_DISTRIBUTE_VERTICAL_TOP,
863                         _("Distribute top edges equidistantly"),
864                         1, 1, false, Geom::Y, 0, 1);
865     addDistributeButton(INKSCAPE_ICON_DISTRIBUTE_VERTICAL_CENTER,
866                         _("Distribute centers equidistantly vertically"),
867                         1, 2, false, Geom::Y, .5, .5);
868     addDistributeButton(INKSCAPE_ICON_DISTRIBUTE_VERTICAL_BOTTOM,
869                         _("Distribute bottom edges equidistantly"),
870                         1, 3, false, Geom::Y, 1., 0.);
872     //Baseline distribs
873     addBaselineButton(INKSCAPE_ICON_DISTRIBUTE_HORIZONTAL_BASELINE,
874                    _("Distribute baseline anchors of texts horizontally"),
875                       0, 5, this->distribute_table(), Geom::X, true);
876     addBaselineButton(INKSCAPE_ICON_DISTRIBUTE_VERTICAL_BASELINE,
877                    _("Distribute baselines of texts vertically"),
878                      1, 5, this->distribute_table(), Geom::Y, true);
880     //Randomize & Unclump
881     addRandomizeButton(INKSCAPE_ICON_DISTRIBUTE_RANDOMIZE,
882                         _("Randomize centers in both dimensions"),
883                         2, 2);
884     addUnclumpButton(INKSCAPE_ICON_DISTRIBUTE_UNCLUMP,
885                         _("Unclump objects: try to equalize edge-to-edge distances"),
886                         2, 4);
888     //Remove overlaps
889     addRemoveOverlapsButton(INKSCAPE_ICON_DISTRIBUTE_REMOVE_OVERLAPS,
890                             _("Move objects as little as possible so that their bounding boxes do not overlap"),
891                             0, 0);
892     //Graph Layout
893     addGraphLayoutButton(INKSCAPE_ICON_DISTRIBUTE_GRAPH,
894                             _("Nicely arrange selected connector network"),
895                             0, 0);
897     //Node Mode buttons
898     // NOTE: "align nodes vertically" means "move nodes vertically until they align on a common
899     // _horizontal_ line". This is analogous to what the "align-vertical-center" icon means.
900     // There is no doubt some ambiguity. For this reason the descriptions are different.
901     addNodeButton(INKSCAPE_ICON_ALIGN_VERTICAL_NODES,
902                   _("Align selected nodes to a common horizontal line"),
903                   0, Geom::X, false);
904     addNodeButton(INKSCAPE_ICON_ALIGN_HORIZONTAL_NODES,
905                   _("Align selected nodes to a common vertical line"),
906                   1, Geom::Y, false);
907     addNodeButton(INKSCAPE_ICON_DISTRIBUTE_HORIZONTAL_NODE,
908                   _("Distribute selected nodes horizontally"),
909                   2, Geom::X, true);
910     addNodeButton(INKSCAPE_ICON_DISTRIBUTE_VERTICAL_NODE,
911                   _("Distribute selected nodes vertically"),
912                   3, Geom::Y, true);
914     //Rest of the widgetry
916     _combo.append_text(_("Last selected"));
917     _combo.append_text(_("First selected"));
918     _combo.append_text(_("Biggest object"));
919     _combo.append_text(_("Smallest object"));
920     _combo.append_text(_("Page"));
921     _combo.append_text(_("Drawing"));
922     _combo.append_text(_("Selection"));
924     _combo.set_active(prefs->getInt("/dialogs/align/align-to", 6));
925     _combo.signal_changed().connect(sigc::mem_fun(*this, &AlignAndDistribute::on_ref_change));
927     _anchorBox.pack_start(_anchorLabel);
928     _anchorBox.pack_start(_combo);
930     _selgrpBox.pack_start(_selgrpLabel);
931     _selgrpBox.pack_start(_selgrp);
932     _selgrp.set_active(prefs->getBool("/dialogs/align/sel-as-groups"));
933     _selgrp.signal_toggled().connect(sigc::mem_fun(*this, &AlignAndDistribute::on_selgrp_toggled));
935     _alignBox.pack_start(_anchorBox);
936     _alignBox.pack_start(_selgrpBox);
937     _alignBox.pack_start(_alignTable);
939     _alignFrame.add(_alignBox);
940     _distributeFrame.add(_distributeTable);
941     _removeOverlapFrame.add(_removeOverlapTable);
942     _graphLayoutFrame.add(_graphLayoutTable);
943     _nodesFrame.add(_nodesTable);
945     Gtk::Box *contents = _getContents();
946     contents->set_spacing(4);
948     // Notebook for individual transformations
950     contents->pack_start(_alignFrame, true, true);
951     contents->pack_start(_distributeFrame, true, true);
952     contents->pack_start(_removeOverlapFrame, true, true);
953     contents->pack_start(_graphLayoutFrame, true, true);
954     contents->pack_start(_nodesFrame, true, true);
956     //Connect to the global tool change signal
957     g_signal_connect (G_OBJECT (INKSCAPE), "set_eventcontext", G_CALLBACK (on_tool_changed), this);
959     // Connect to the global selection change, to invalidate cached randomize_bbox
960     g_signal_connect (G_OBJECT (INKSCAPE), "change_selection", G_CALLBACK (on_selection_changed), this);
961     randomize_bbox = Geom::OptRect();
963     show_all_children();
965     on_tool_changed (NULL, NULL, this); // set current mode
968 AlignAndDistribute::~AlignAndDistribute()
970     sp_signal_disconnect_by_data (G_OBJECT (INKSCAPE), this);
972     for (std::list<Action *>::iterator it = _actionList.begin();
973          it != _actionList.end();
974          it ++)
975         delete *it;
978 void AlignAndDistribute::on_ref_change(){
979     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
980     prefs->setInt("/dialogs/align/align-to", _combo.get_active_row_number());
982     //Make blink the master
985 void AlignAndDistribute::on_selgrp_toggled(){
986     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
987     prefs->setInt("/dialogs/align/sel-as-groups", _selgrp.get_active());
989     //Make blink the master
995 void AlignAndDistribute::setMode(bool nodeEdit)
997     //Act on widgets used in node mode
998     void ( Gtk::Widget::*mNode) ()  = nodeEdit ?
999         &Gtk::Widget::show_all : &Gtk::Widget::hide_all;
1001     //Act on widgets used in selection mode
1002   void ( Gtk::Widget::*mSel) ()  = nodeEdit ?
1003       &Gtk::Widget::hide_all : &Gtk::Widget::show_all;
1006     ((_alignFrame).*(mSel))();
1007     ((_distributeFrame).*(mSel))();
1008     ((_removeOverlapFrame).*(mSel))();
1009     ((_graphLayoutFrame).*(mSel))();
1010     ((_nodesFrame).*(mNode))();
1013 void AlignAndDistribute::addAlignButton(const Glib::ustring &id, const Glib::ustring tiptext,
1014                                  guint row, guint col)
1016     _actionList.push_back(
1017         new ActionAlign(
1018             id, tiptext, row, col,
1019             *this , col + row * 5));
1021 void AlignAndDistribute::addDistributeButton(const Glib::ustring &id, const Glib::ustring tiptext,
1022                                       guint row, guint col, bool onInterSpace,
1023                                       Geom::Dim2 orientation, float kBegin, float kEnd)
1025     _actionList.push_back(
1026         new ActionDistribute(
1027             id, tiptext, row, col, *this ,
1028             onInterSpace, orientation,
1029             kBegin, kEnd
1030             )
1031         );
1034 void AlignAndDistribute::addNodeButton(const Glib::ustring &id, const Glib::ustring tiptext,
1035                    guint col, Geom::Dim2 orientation, bool distribute)
1037     _actionList.push_back(
1038         new ActionNode(
1039             id, tiptext, col,
1040             *this, orientation, distribute));
1043 void AlignAndDistribute::addRemoveOverlapsButton(const Glib::ustring &id, const Glib::ustring tiptext,
1044                                       guint row, guint col)
1046     _actionList.push_back(
1047         new ActionRemoveOverlaps(
1048             id, tiptext, row, col, *this)
1049         );
1052 void AlignAndDistribute::addGraphLayoutButton(const Glib::ustring &id, const Glib::ustring tiptext,
1053                                       guint row, guint col)
1055     _actionList.push_back(
1056         new ActionGraphLayout(
1057             id, tiptext, row, col, *this)
1058         );
1061 void AlignAndDistribute::addUnclumpButton(const Glib::ustring &id, const Glib::ustring tiptext,
1062                                       guint row, guint col)
1064     _actionList.push_back(
1065         new ActionUnclump(
1066             id, tiptext, row, col, *this)
1067         );
1070 void AlignAndDistribute::addRandomizeButton(const Glib::ustring &id, const Glib::ustring tiptext,
1071                                       guint row, guint col)
1073     _actionList.push_back(
1074         new ActionRandomize(
1075             id, tiptext, row, col, *this)
1076         );
1079 void AlignAndDistribute::addBaselineButton(const Glib::ustring &id, const Glib::ustring tiptext,
1080                                     guint row, guint col, Gtk::Table &table, Geom::Dim2 orientation, bool distribute)
1082     _actionList.push_back(
1083         new ActionBaseline(
1084             id, tiptext, row, col,
1085             *this, table, orientation, distribute));
1091 std::list<SPItem *>::iterator AlignAndDistribute::find_master( std::list<SPItem *> &list, bool horizontal){
1092     std::list<SPItem *>::iterator master = list.end();
1093     switch (getAlignTarget()) {
1094     case LAST:
1095         return list.begin();
1096         break;
1098     case FIRST:
1099         return --(list.end());
1100         break;
1102     case BIGGEST:
1103     {
1104         gdouble max = -1e18;
1105         for (std::list<SPItem *>::iterator it = list.begin(); it != list.end(); it++) {
1106             Geom::OptRect b = sp_item_bbox_desktop (*it);
1107             if (b) {
1108                 gdouble dim = (*b)[horizontal ? Geom::X : Geom::Y].extent();
1109                 if (dim > max) {
1110                     max = dim;
1111                     master = it;
1112                 }
1113             }
1114         }
1115         return master;
1116         break;
1117     }
1119     case SMALLEST:
1120     {
1121         gdouble max = 1e18;
1122         for (std::list<SPItem *>::iterator it = list.begin(); it != list.end(); it++) {
1123             Geom::OptRect b = sp_item_bbox_desktop (*it);
1124             if (b) {
1125                 gdouble dim = (*b)[horizontal ? Geom::X : Geom::Y].extent();
1126                 if (dim < max) {
1127                     max = dim;
1128                     master = it;
1129                 }
1130             }
1131         }
1132         return master;
1133         break;
1134     }
1136     default:
1137         g_assert_not_reached ();
1138         break;
1140     } // end of switch statement
1141     return master;
1144 AlignAndDistribute::AlignTarget AlignAndDistribute::getAlignTarget()const {
1145     return AlignTarget(_combo.get_active_row_number());
1150 } // namespace Dialog
1151 } // namespace UI
1152 } // namespace Inkscape
1154 /*
1155   Local Variables:
1156   mode:c++
1157   c-file-style:"stroustrup"
1158   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1159   indent-tabs-mode:nil
1160   fill-column:99
1161   End:
1162 */
1163 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :