#include "config.h"
#include "IntRect.h"
#include "FloatRect.h"
#include "LayoutRect.h"
#include <algorithm>
using std::max;
using std::min;
namespace WebCore {
IntRect::IntRect(const FloatRect& r)
: m_location(clampToInteger(r.x()), clampToInteger(r.y()))
, m_size(clampToInteger(r.width()), clampToInteger(r.height()))
{
}
IntRect::IntRect(const LayoutRect& r)
: m_location(r.x(), r.y())
, m_size(r.width(), r.height())
{
}
bool IntRect::intersects(const IntRect& other) const
{
return !isEmpty() && !other.isEmpty()
&& x() < other.maxX() && other.x() < maxX()
&& y() < other.maxY() && other.y() < maxY();
}
bool IntRect::contains(const IntRect& other) const
{
return x() <= other.x() && maxX() >= other.maxX()
&& y() <= other.y() && maxY() >= other.maxY();
}
void IntRect::intersect(const IntRect& other)
{
int l = max(x(), other.x());
int t = max(y(), other.y());
int r = min(maxX(), other.maxX());
int b = min(maxY(), other.maxY());
if (l >= r || t >= b) {
l = 0;
t = 0;
r = 0;
b = 0;
}
m_location.setX(l);
m_location.setY(t);
m_size.setWidth(r - l);
m_size.setHeight(b - t);
}
void IntRect::unite(const IntRect& other)
{
if (other.isEmpty())
return;
if (isEmpty()) {
*this = other;
return;
}
int l = min(x(), other.x());
int t = min(y(), other.y());
int r = max(maxX(), other.maxX());
int b = max(maxY(), other.maxY());
m_location.setX(l);
m_location.setY(t);
m_size.setWidth(r - l);
m_size.setHeight(b - t);
}
void IntRect::uniteIfNonZero(const IntRect& other)
{
if (!other.width() && !other.height())
return;
if (!width() && !height()) {
*this = other;
return;
}
int left = min(x(), other.x());
int top = min(y(), other.y());
int right = max(maxX(), other.maxX());
int bottom = max(maxY(), other.maxY());
m_location.setX(left);
m_location.setY(top);
m_size.setWidth(right - left);
m_size.setHeight(bottom - top);
}
void IntRect::scale(float s)
{
m_location.setX((int)(x() * s));
m_location.setY((int)(y() * s));
m_size.setWidth((int)(width() * s));
m_size.setHeight((int)(height() * s));
}
static inline int distanceToInterval(int pos, int start, int end)
{
if (pos < start)
return start - pos;
if (pos > end)
return end - pos;
return 0;
}
IntSize IntRect::differenceToPoint(const IntPoint& point) const
{
int xdistance = distanceToInterval(point.x(), x(), maxX());
int ydistance = distanceToInterval(point.y(), y(), maxY());
return IntSize(xdistance, ydistance);
}
IntRect unionRect(const Vector<IntRect>& rects)
{
IntRect result;
size_t count = rects.size();
for (size_t i = 0; i < count; ++i)
result.unite(rects[i]);
return result;
}
}