1 /** \file
2 * Interface between Inkscape code (SPItem) and remove-overlaps function.
3 */
4 /*
5 * Authors:
6 * Tim Dwyer <tgdwyer@gmail.com>
7 *
8 * Copyright (C) 2005 Authors
9 *
10 * Released under GNU LGPL. Read the file 'COPYING' for more information.
11 */
12 #include "util/glib-list-iterators.h"
13 #include "sp-item.h"
14 #include "sp-item-transform.h"
15 #include "libvpsc/generate-constraints.h"
16 #include "libvpsc/remove_rectangle_overlap.h"
17 #include <utility>
19 using vpsc::Rectangle;
21 namespace {
22 struct Record {
23 SPItem *item;
24 Geom::Point midpoint;
25 Rectangle *vspc_rect;
27 Record() {}
28 Record(SPItem *i, Geom::Point m, Rectangle *r)
29 : item(i), midpoint(m), vspc_rect(r) {}
30 };
31 }
33 /**
34 * Takes a list of inkscape items and moves them as little as possible
35 * such that rectangular bounding boxes are separated by at least xGap
36 * horizontally and yGap vertically
37 */
38 void removeoverlap(GSList const *const items, double const xGap, double const yGap) {
39 using Inkscape::Util::GSListConstIterator;
40 std::list<SPItem *> selected;
41 selected.insert<GSListConstIterator<SPItem *> >(selected.end(), items, NULL);
42 std::vector<Record> records;
43 std::vector<Rectangle *> rs;
45 Geom::Point const gap(xGap, yGap);
46 for (std::list<SPItem *>::iterator it(selected.begin());
47 it != selected.end();
48 ++it)
49 {
50 using Geom::X; using Geom::Y;
51 Geom::OptRect item_box(sp_item_bbox_desktop(*it));
52 if (item_box) {
53 Geom::Point min(item_box->min() - .5*gap);
54 Geom::Point max(item_box->max() + .5*gap);
55 // A negative gap is allowed, but will lead to problems when the gap is larger than
56 // the bounding box (in either X or Y direction, or both); min will have become max
57 // now, which cannot be handled by Rectangle() which is called below. And how will
58 // removeRectangleOverlap handle such a case?
59 // That's why we will enforce some boundaries on min and max here:
60 if (max[X] < min[X]) {
61 min[X] = max[X] = (min[X] + max[X])/2;
62 }
63 if (max[Y] < min[Y]) {
64 min[Y] = max[Y] = (min[Y] + max[Y])/2;
65 }
66 Rectangle *vspc_rect = new Rectangle(min[X], max[X], min[Y], max[Y]);
67 records.push_back(Record(*it, item_box->midpoint(), vspc_rect));
68 rs.push_back(vspc_rect);
69 }
70 }
71 if (!rs.empty()) {
72 removeRectangleOverlap(rs.size(), &rs[0], 0.0, 0.0);
73 }
74 for ( std::vector<Record>::iterator it = records.begin();
75 it != records.end();
76 ++it )
77 {
78 Geom::Point const curr = it->midpoint;
79 Geom::Point const dest(it->vspc_rect->getCentreX(),
80 it->vspc_rect->getCentreY());
81 sp_item_move_rel(it->item, Geom::Translate(dest - curr));
82 delete it->vspc_rect;
83 }
84 }