~centralelyon2010/inkscape/imagelinks2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/** \file
 * Interface between Inkscape code (SPItem) and remove-overlaps function.
 */
/*
* Authors:
*   Tim Dwyer <tgdwyer@gmail.com>
 *   Abhishek Sharma
*
* Copyright (C) 2005 Authors
*
* Released under GNU LGPL.  Read the file 'COPYING' for more information.
*/
#include <utility>
#include <2geom/transforms.h>
#include "util/glib-list-iterators.h"
#include "sp-item.h"
#include "sp-item-transform.h"
#include "libvpsc/generate-constraints.h"
#include "libvpsc/remove_rectangle_overlap.h"

using vpsc::Rectangle;

namespace {
	struct Record {
		SPItem *item;
		Geom::Point midpoint;
		Rectangle *vspc_rect;

		Record() {}
		Record(SPItem *i, Geom::Point m, Rectangle *r)
		: item(i), midpoint(m), vspc_rect(r) {}
	};
}

/**
* Takes a list of inkscape items and moves them as little as possible
* such that rectangular bounding boxes are separated by at least xGap
* horizontally and yGap vertically
*/
void removeoverlap(GSList const *const items, double const xGap, double const yGap) {
	using Inkscape::Util::GSListConstIterator;
	std::list<SPItem *> selected;
	selected.insert<GSListConstIterator<SPItem *> >(selected.end(), items, NULL);
	std::vector<Record> records;
	std::vector<Rectangle *> rs;

	Geom::Point const gap(xGap, yGap);
	for (std::list<SPItem *>::iterator it(selected.begin());
		it != selected.end();
		++it)
	{
		using Geom::X; using Geom::Y;
		Geom::OptRect item_box((*it)->desktopVisualBounds());
		if (item_box) {
			Geom::Point min(item_box->min() - .5*gap);
			Geom::Point max(item_box->max() + .5*gap);
			// A negative gap is allowed, but will lead to problems when the gap is larger than
			// the bounding box (in either X or Y direction, or both); min will have become max
			// now, which cannot be handled by Rectangle() which is called below. And how will
			// removeRectangleOverlap handle such a case?
			// That's why we will enforce some boundaries on min and max here:
			if (max[X] < min[X]) {
				min[X] = max[X] = (min[X] + max[X])/2;
			}
			if (max[Y] < min[Y]) {
				min[Y] = max[Y] = (min[Y] + max[Y])/2;
			}
			Rectangle *vspc_rect = new Rectangle(min[X], max[X], min[Y], max[Y]);
			records.push_back(Record(*it, item_box->midpoint(), vspc_rect));
			rs.push_back(vspc_rect);
		}
	}
	if (!rs.empty()) {
		removeRectangleOverlap(rs.size(), &rs[0], 0.0, 0.0);
	}
	for ( std::vector<Record>::iterator it = records.begin();
	      it != records.end();
	      ++it )
	{
		Geom::Point const curr = it->midpoint;
		Geom::Point const dest(it->vspc_rect->getCentreX(),
				     it->vspc_rect->getCentreY());
		sp_item_move_rel(it->item, Geom::Translate(dest - curr));
		delete it->vspc_rect;
	}
}