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