<commit_before>#include "line.h"
#include <QtGui/QPainter>
#include <QtGui/QStyle>
#include <QtGui/QStyleOptionGraphicsItem>

const int step = 3;

Line::Line(qreal x1, qreal y1, qreal x2, qreal y2, Item* parent)
	:Item(parent)
{
	mNeedScalingRect = false;
	mPen.setColor(Qt::green);
	mDomElementType = pictureType;
	mX1 = x1;
	mY1 = y1;
	mX2 = x2;
	mY2 = y2;
}

Line::Line(Line const &other)
	:Item()
{
	mNeedScalingRect = other.mNeedScalingRect ;
	mPen = other.mPen;
	mBrush = other.mBrush;
	mDomElementType = pictureType;
	mX1 = other.mX1;
	mX2 = other.mX2;
	mY1 = other.mY1;
	mY2 = other.mY2;
	mListScalePoint = other.mListScalePoint;
	setPos(other.x(), other.y());
}

Item* Line::clone()
{
	Line* item = new Line(*this);
	return item;
}

QRectF Line::boundingRect() const
{
	return (QRectF(qMin(mX1, mX2) - mPen.width(), qMin(mY1, mY2) - mPen.width(), abs(mX2 - mX1) + mPen.width(), abs(mY2 - mY1) + mPen.width()).adjusted(-drift, -drift, drift, drift));
}

QRectF Line::realBoundingRect() const
{
	return mapToScene(boundingRect().adjusted(drift + mPen.width(), drift + mPen.width(), -drift, -drift)).boundingRect();
}

void Line::drawItem(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
	Q_UNUSED(option);
	Q_UNUSED(widget);
	painter->drawLine(mX1, mY1, mX2, mY2);
}

void Line::drawExtractionForItem(QPainter* painter)
{
	painter->drawPoint(mX1, mY1);
	painter->drawPoint(mX2, mY2);

	setPenBrushDriftRect(painter);
	painter->drawPath(shape());
	drawFieldForResizeItem(painter);

	painter->setPen(QPen(Qt::red));
	painter->setBrush(QBrush(Qt::SolidPattern));
	drawScalingRects(painter);
}

void Line::drawFieldForResizeItem(QPainter* painter)
{
	painter->drawEllipse(QPointF(mX1, mY1), resizeDrift, resizeDrift);
	painter->drawEllipse(QPointF(mX2, mY2), resizeDrift, resizeDrift);
}

void Line::drawScalingRects(QPainter* painter)
{
	QBrush brush(Qt::SolidPattern);
	if(mX2 > mX1) {
		if (mY2 > mY1) {
			brush.setColor(mListScalePoint.at(4).second);
			painter->setBrush(brush);
			painter->drawRect(mX1 - scalingRect - step, mY1 - step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(0).second);
			painter->setBrush(brush);
			painter->drawRect(mX1 - step, mY1 - scalingRect - step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(3).second);
			painter->setBrush(brush);
			painter->drawRect(mX2 - scalingRect + step, mY2 + step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(7).second);
			painter->setBrush(brush);
			painter->drawRect(mX2 + step, mY2 - scalingRect + step, scalingRect, scalingRect);
		}
		else {
			brush.setColor(mListScalePoint.at(2).second);
			painter->setBrush(brush);
			painter->drawRect(mX1 - step, mY1 + step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(6).second);
			painter->setBrush(brush);
			painter->drawRect(mX1  - scalingRect - step, mY1 - scalingRect + step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(1).second);
			painter->setBrush(brush);
			painter->drawRect(mX2 - scalingRect + step, mY2 - scalingRect - step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(5).second);
			painter->setBrush(brush);
			painter->drawRect(mX2 + step, mY2 - step, scalingRect, scalingRect);
		}
	} else {
		if (mY2 > mY1) {
			brush.setColor(mListScalePoint.at(5).second);
			painter->setBrush(brush);
			painter->drawRect(mX1 + step, mY1 - step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(1).second);
			painter->setBrush(brush);
			painter->drawRect(mX1  - scalingRect + step, mY1 - scalingRect - step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(6).second);
			painter->setBrush(brush);
			painter->drawRect(mX2 - scalingRect - step, mY2 - scalingRect + step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(2).second);
			painter->setBrush(brush);
			painter->drawRect(mX2 - step, mY2 + step, scalingRect, scalingRect);
		}
		else {
			brush.setColor(mListScalePoint.at(4).second);
			painter->setBrush(brush);
			painter->drawRect(mX2 - scalingRect - step, mY2 - step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(0).second);
			painter->setBrush(brush);
			painter->drawRect(mX2 - step, mY2 - scalingRect - step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(3).second);
			painter->setBrush(brush);
			painter->drawRect(mX1 - scalingRect + step, mY1 + step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(7).second);
			painter->setBrush(brush);
			painter->drawRect(mX1 + step, mY1 - scalingRect + step, scalingRect, scalingRect);
		}
	}
}

QLineF Line::line() const
{
	return QLineF(mX1, mY1, mX2, mY2);
}

QPainterPath Line::shape() const
{
	QPainterPath path;
	path.setFillRule(Qt::WindingFill);

	QPainterPathStroker ps;
	ps.setWidth(drift);

	path.moveTo(mX1, mY1);
	path.lineTo(mX2, mY2);
	path = ps.createStroke(path);

	return path;
}

void Line::changeScalingPointState(qreal x, qreal y)
{
	qreal x1= (boundingRect().adjusted(drift, drift, -drift, -drift)).left();
	qreal x2 = (boundingRect().adjusted(drift, drift, -drift, -drift)).right();
	qreal y1 = (boundingRect().adjusted(drift, drift, -drift, -drift)).top();
	qreal y2 = (boundingRect().adjusted(drift, drift, -drift, -drift)).bottom();
	int correction = step;
	calcForChangeScalingState(QPointF(x, y), QPointF(x1, y1), QPointF(x2, y2), correction);
	if (mScalingState == topRightX || mScalingState == topRightY || mScalingState == bottomLeftX || mScalingState == bottomLeftY)
		mDragState = None;
}

void Line::resizeItem(QGraphicsSceneMouseEvent *event)
{
	if (mDragState == TopLeft || mDragState == BottomRight)
		Item::resizeItem(event);
}

void Line::reshapeRectWithShift()
{
	qreal differenceX = abs(mX2 - mX1);
	qreal differenceY = abs(mY2 - mY1);
	qreal size = qMax(differenceX, differenceY);
	if (differenceX > differenceY) {
		if(mX2 > mX1)
			setX2andY2(mX1 + size, mY1);
		else
			setX2andY2(mX1 - size, mY1);
	} else {
		if(mY2 > mY1)
			setX2andY2(mX1, mY1 + size);
		else
			setX2andY2(mX1, mY1 - size);
	}
}

QPair<QPair<QString, QString>, QPair<QString, QString> > Line::setXandYBefore(QRectF const &rect)
{
	QString x1 = "";
	QString y1 = "";
	QString y2 = "";
	QString x2 = "";
	if (mX2 > mX1) {
		if (mY2 > mY1) {
			y1 = setScaleForDoc(4, rect);
			x1 = setScaleForDoc(0, rect);
			y2 = setScaleForDoc(7, rect);
			x2 = setScaleForDoc(3, rect);
		} else {
			y1 = setScaleForDoc(6, rect);
			x1 = setScaleForDoc(2, rect);
			y2 = setScaleForDoc(5, rect);
			x2 = setScaleForDoc(1, rect);
		}
	} else {
		if (mY2 > mY1) {
			y1 = setScaleForDoc(5, rect);
			x1 = setScaleForDoc(1, rect);
			y2 = setScaleForDoc(6, rect);
			x2 = setScaleForDoc(2, rect);
		} else {
			y1 = setScaleForDoc(7, rect);
			x1 = setScaleForDoc(3, rect);
			y2 = setScaleForDoc(4, rect);
			x2 = setScaleForDoc(0, rect);
		}
	}
	return QPair<QPair<QString, QString>, QPair<QString, QString> >(QPair<QString, QString>(x1, y1), QPair<QString, QString>(x2, y2));
}

void Line::setXandY(QDomElement& dom, QPair<QPair<QString, QString>, QPair<QString, QString> > pair)
{
	dom.setAttribute("y1", pair.first.second);
	dom.setAttribute("x1", pair.first.first);
	dom.setAttribute("y2", pair.second.second);
	dom.setAttribute("x2", pair.second.first);
}

QPair<QDomElement, Item::DomElementTypes> Line::generateItem(QDomDocument &document, QPoint const &topLeftPicture)
{
	qreal const x1 = scenePos().x() + line().x1() - topLeftPicture.x();
	qreal const y1 = scenePos().y() + line().y1() - topLeftPicture.y();
	qreal const x2 = scenePos().x() + line().x2() - topLeftPicture.x();
	qreal const y2 = scenePos().y() + line().y2() - topLeftPicture.y();

	QDomElement line = setPenBrushToDoc(document, "line");
	setXandY(line, setXandYBefore(QRectF(x1, y1, x2 - x1, y2 - y1).normalized()));

	return QPair<QDomElement, Item::DomElementTypes>(line, mDomElementType);
}
<commit_msg>при удерживании Shift рисуются также и диоганальные линии в ShapeEditor<commit_after>#include "line.h"
#include <QtGui/QPainter>
#include <QtGui/QStyle>
#include <QtGui/QStyleOptionGraphicsItem>

const int step = 3;

Line::Line(qreal x1, qreal y1, qreal x2, qreal y2, Item* parent)
	:Item(parent)
{
	mNeedScalingRect = false;
	mPen.setColor(Qt::green);
	mDomElementType = pictureType;
	mX1 = x1;
	mY1 = y1;
	mX2 = x2;
	mY2 = y2;
}

Line::Line(Line const &other)
	:Item()
{
	mNeedScalingRect = other.mNeedScalingRect ;
	mPen = other.mPen;
	mBrush = other.mBrush;
	mDomElementType = pictureType;
	mX1 = other.mX1;
	mX2 = other.mX2;
	mY1 = other.mY1;
	mY2 = other.mY2;
	mListScalePoint = other.mListScalePoint;
	setPos(other.x(), other.y());
}

Item* Line::clone()
{
	Line* item = new Line(*this);
	return item;
}

QRectF Line::boundingRect() const
{
	return (QRectF(qMin(mX1, mX2) - mPen.width(), qMin(mY1, mY2) - mPen.width(), abs(mX2 - mX1) + mPen.width(), abs(mY2 - mY1) + mPen.width()).adjusted(-drift, -drift, drift, drift));
}

QRectF Line::realBoundingRect() const
{
	return mapToScene(boundingRect().adjusted(drift + mPen.width(), drift + mPen.width(), -drift, -drift)).boundingRect();
}

void Line::drawItem(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
	Q_UNUSED(option);
	Q_UNUSED(widget);
	painter->drawLine(mX1, mY1, mX2, mY2);
}

void Line::drawExtractionForItem(QPainter* painter)
{
	painter->drawPoint(mX1, mY1);
	painter->drawPoint(mX2, mY2);

	setPenBrushDriftRect(painter);
	painter->drawPath(shape());
	drawFieldForResizeItem(painter);

	painter->setPen(QPen(Qt::red));
	painter->setBrush(QBrush(Qt::SolidPattern));
	drawScalingRects(painter);
}

void Line::drawFieldForResizeItem(QPainter* painter)
{
	painter->drawEllipse(QPointF(mX1, mY1), resizeDrift, resizeDrift);
	painter->drawEllipse(QPointF(mX2, mY2), resizeDrift, resizeDrift);
}

void Line::drawScalingRects(QPainter* painter)
{
	QBrush brush(Qt::SolidPattern);
	if(mX2 > mX1) {
		if (mY2 > mY1) {
			brush.setColor(mListScalePoint.at(4).second);
			painter->setBrush(brush);
			painter->drawRect(mX1 - scalingRect - step, mY1 - step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(0).second);
			painter->setBrush(brush);
			painter->drawRect(mX1 - step, mY1 - scalingRect - step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(3).second);
			painter->setBrush(brush);
			painter->drawRect(mX2 - scalingRect + step, mY2 + step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(7).second);
			painter->setBrush(brush);
			painter->drawRect(mX2 + step, mY2 - scalingRect + step, scalingRect, scalingRect);
		}
		else {
			brush.setColor(mListScalePoint.at(2).second);
			painter->setBrush(brush);
			painter->drawRect(mX1 - step, mY1 + step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(6).second);
			painter->setBrush(brush);
			painter->drawRect(mX1  - scalingRect - step, mY1 - scalingRect + step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(1).second);
			painter->setBrush(brush);
			painter->drawRect(mX2 - scalingRect + step, mY2 - scalingRect - step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(5).second);
			painter->setBrush(brush);
			painter->drawRect(mX2 + step, mY2 - step, scalingRect, scalingRect);
		}
	} else {
		if (mY2 > mY1) {
			brush.setColor(mListScalePoint.at(5).second);
			painter->setBrush(brush);
			painter->drawRect(mX1 + step, mY1 - step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(1).second);
			painter->setBrush(brush);
			painter->drawRect(mX1  - scalingRect + step, mY1 - scalingRect - step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(6).second);
			painter->setBrush(brush);
			painter->drawRect(mX2 - scalingRect - step, mY2 - scalingRect + step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(2).second);
			painter->setBrush(brush);
			painter->drawRect(mX2 - step, mY2 + step, scalingRect, scalingRect);
		}
		else {
			brush.setColor(mListScalePoint.at(4).second);
			painter->setBrush(brush);
			painter->drawRect(mX2 - scalingRect - step, mY2 - step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(0).second);
			painter->setBrush(brush);
			painter->drawRect(mX2 - step, mY2 - scalingRect - step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(3).second);
			painter->setBrush(brush);
			painter->drawRect(mX1 - scalingRect + step, mY1 + step, scalingRect, scalingRect);

			brush.setColor(mListScalePoint.at(7).second);
			painter->setBrush(brush);
			painter->drawRect(mX1 + step, mY1 - scalingRect + step, scalingRect, scalingRect);
		}
	}
}

QLineF Line::line() const
{
	return QLineF(mX1, mY1, mX2, mY2);
}

QPainterPath Line::shape() const
{
	QPainterPath path;
	path.setFillRule(Qt::WindingFill);

	QPainterPathStroker ps;
	ps.setWidth(drift);

	path.moveTo(mX1, mY1);
	path.lineTo(mX2, mY2);
	path = ps.createStroke(path);

	return path;
}

void Line::changeScalingPointState(qreal x, qreal y)
{
	qreal x1= (boundingRect().adjusted(drift, drift, -drift, -drift)).left();
	qreal x2 = (boundingRect().adjusted(drift, drift, -drift, -drift)).right();
	qreal y1 = (boundingRect().adjusted(drift, drift, -drift, -drift)).top();
	qreal y2 = (boundingRect().adjusted(drift, drift, -drift, -drift)).bottom();
	int correction = step;
	calcForChangeScalingState(QPointF(x, y), QPointF(x1, y1), QPointF(x2, y2), correction);
	if (mScalingState == topRightX || mScalingState == topRightY || mScalingState == bottomLeftX || mScalingState == bottomLeftY)
		mDragState = None;
}

void Line::resizeItem(QGraphicsSceneMouseEvent *event)
{
	if (mDragState == TopLeft || mDragState == BottomRight)
		Item::resizeItem(event);
}

void Line::reshapeRectWithShift()
{
	qreal differenceX = abs(mX2 - mX1);
	qreal differenceY = abs(mY2 - mY1);
	qreal differenceXY = abs(differenceX - differenceY);
	qreal size = qMax(differenceX, differenceY);
	const int delta = size / 2;
	if (differenceXY > delta) {
		if (differenceX > differenceY) {
			if(mX2 > mX1)
				setX2andY2(mX1 + size, mY1);
			else
				setX2andY2(mX1 - size, mY1);
		} else {
			if(mY2 > mY1)
				setX2andY2(mX1, mY1 + size);
			else
				setX2andY2(mX1, mY1 - size);
		}
	} else
		Item::reshapeRectWithShift();
}

QPair<QPair<QString, QString>, QPair<QString, QString> > Line::setXandYBefore(QRectF const &rect)
{
	QString x1 = "";
	QString y1 = "";
	QString y2 = "";
	QString x2 = "";
	if (mX2 > mX1) {
		if (mY2 > mY1) {
			y1 = setScaleForDoc(4, rect);
			x1 = setScaleForDoc(0, rect);
			y2 = setScaleForDoc(7, rect);
			x2 = setScaleForDoc(3, rect);
		} else {
			y1 = setScaleForDoc(6, rect);
			x1 = setScaleForDoc(2, rect);
			y2 = setScaleForDoc(5, rect);
			x2 = setScaleForDoc(1, rect);
		}
	} else {
		if (mY2 > mY1) {
			y1 = setScaleForDoc(5, rect);
			x1 = setScaleForDoc(1, rect);
			y2 = setScaleForDoc(6, rect);
			x2 = setScaleForDoc(2, rect);
		} else {
			y1 = setScaleForDoc(7, rect);
			x1 = setScaleForDoc(3, rect);
			y2 = setScaleForDoc(4, rect);
			x2 = setScaleForDoc(0, rect);
		}
	}
	return QPair<QPair<QString, QString>, QPair<QString, QString> >(QPair<QString, QString>(x1, y1), QPair<QString, QString>(x2, y2));
}

void Line::setXandY(QDomElement& dom, QPair<QPair<QString, QString>, QPair<QString, QString> > pair)
{
	dom.setAttribute("y1", pair.first.second);
	dom.setAttribute("x1", pair.first.first);
	dom.setAttribute("y2", pair.second.second);
	dom.setAttribute("x2", pair.second.first);
}

QPair<QDomElement, Item::DomElementTypes> Line::generateItem(QDomDocument &document, QPoint const &topLeftPicture)
{
	qreal const x1 = scenePos().x() + line().x1() - topLeftPicture.x();
	qreal const y1 = scenePos().y() + line().y1() - topLeftPicture.y();
	qreal const x2 = scenePos().x() + line().x2() - topLeftPicture.x();
	qreal const y2 = scenePos().y() + line().y2() - topLeftPicture.y();

	QDomElement line = setPenBrushToDoc(document, "line");
	setXandY(line, setXandYBefore(QRectF(x1, y1, x2 - x1, y2 - y1).normalized()));

	return QPair<QDomElement, Item::DomElementTypes>(line, mDomElementType);
}
<|endoftext|>


<commit_before>// -*- mode: c++; coding: utf-8 -*-
#pragma once
#ifndef WTL_ITERTOOLS_HPP_
#define WTL_ITERTOOLS_HPP_

#include <vector>
#include <type_traits>
#include <limits>
#include <cmath>

#include <boost/coroutine2/coroutine.hpp>
#include <boost/multiprecision/cpp_int.hpp>

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace wtl { namespace itertools {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

template <class value_type>
class Product {
    typedef boost::coroutines2::coroutine<value_type> coro_t;
    Product() = delete;
  public:
    explicit Product(const std::vector<value_type>& columns):
        columns_(columns),
        value_(columns_.size()),
        col_(columns_.size()) {}

    typename coro_t::pull_type operator()(void) {
        return typename coro_t::pull_type([this](typename coro_t::push_type& yield){source(yield);});
    }

    boost::multiprecision::cpp_int count() const {return cnt_;}
    boost::multiprecision::cpp_int count_max() const {
        boost::multiprecision::cpp_int i = 1;
        for (const auto& c: columns_) {i *= c.size();}
        return i;
    }

  private:
    void source(typename coro_t::push_type& yield) {
        if (--col_ > 0) {
            const size_type n = columns_[col_].size();
            for (size_type i=0; i<n; ++i) {
                value_[col_] = columns_[col_][i];
                source(yield);
            }
            ++col_;
        } else {
            const size_type n = columns_[col_].size();
            for (size_type i=0; i<n; ++i) {
                value_[col_] = columns_[col_][i];
                ++cnt_;
                yield(value_type(value_));
            }
            ++col_;
        }
    }

    const std::vector<value_type> columns_;
    value_type value_;
    size_t col_;
    boost::multiprecision::cpp_int cnt_ = 0;
    typedef typename std::remove_const<decltype(value_.size())>::type size_type;
};

template <class value_type>
Product<value_type> product(const std::vector<value_type>& columns) {
    return Product<value_type>(columns);
}

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

template <class value_type>
class Simplex {
    typedef boost::coroutines2::coroutine<value_type> coro_t;
    Simplex() = delete;
  public:
    explicit Simplex(const std::vector<value_type>& columns, const double sum=1.0):
        product_(columns), sum_(sum) {}

    typename coro_t::pull_type operator()(void) {
        return typename coro_t::pull_type([this](typename coro_t::push_type& yield){source(yield);});
    }

    boost::multiprecision::cpp_int count() const {return cnt_;}
    boost::multiprecision::cpp_int count_all() const {return product_.count();}
    boost::multiprecision::cpp_int count_max() const {return product_.count_max();}

  private:
    bool equals(double x) const {
        return std::fabs(x -= sum_) < std::numeric_limits<double>::epsilon();
    }

    void source(typename coro_t::push_type& yield) {
        for (const auto& v: product_()) {
            if (equals(v.sum())) {
                ++cnt_;
                yield(v);
            }
        }
    }
    Product<value_type> product_;
    const double sum_;
    boost::multiprecision::cpp_int cnt_ = 0;
};

template <class value_type>
Simplex<value_type> simplex(const std::vector<value_type>& columns, const double sum=1.0) {
    return Simplex<value_type>(columns, sum);
}

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
}} // namespace wtl::itertools
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

#endif // WTL_ITERTOOLS_HPP_
<commit_msg>Add start option to Product::operator()<commit_after>// -*- mode: c++; coding: utf-8 -*-
#pragma once
#ifndef WTL_ITERTOOLS_HPP_
#define WTL_ITERTOOLS_HPP_

#include <vector>
#include <type_traits>
#include <limits>
#include <cmath>

#include <boost/coroutine2/coroutine.hpp>
#include <boost/multiprecision/cpp_int.hpp>

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace wtl { namespace itertools {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

template <class value_type>
class Product {
  private:
    typedef boost::coroutines2::coroutine<value_type> coro_t;
    const std::vector<value_type> columns_;
    value_type value_;
    typedef typename std::remove_const<decltype(value_.size())>::type size_type;
    size_type col_;
    boost::multiprecision::cpp_int cnt_ = 0;
  public:
    Product() = delete;
    explicit Product(const std::vector<value_type>& columns):
        columns_(columns),
        value_(columns_.size()),
        col_(columns_.size()) {}

    typename coro_t::pull_type operator()(const size_type start=0) {
        return typename coro_t::pull_type([this,start](typename coro_t::push_type& yield){source(yield, start);});
    }

    boost::multiprecision::cpp_int count() const {return cnt_;}
    boost::multiprecision::cpp_int count_max() const {
        boost::multiprecision::cpp_int i = 1;
        for (const auto& c: columns_) {i *= c.size();}
        return i;
    }

  private:
    void source(typename coro_t::push_type& yield, const size_type start) {
        if (--col_ > 0) {
            const size_type n = columns_[col_].size();
            for (size_type i=0; i<n; ++i) {
                value_[col_] = columns_[col_][i];
                source(yield, start);
            }
            ++col_;
        } else {
            const size_type n = columns_[col_].size();
            for (size_type i=0; i<n; ++i) {
                value_[col_] = columns_[col_][i];
                if (cnt_++ >= start) {
                    yield(value_type(value_));
                }
            }
            ++col_;
        }
    }
};

template <class value_type>
Product<value_type> product(const std::vector<value_type>& columns) {
    return Product<value_type>(columns);
}

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

template <class value_type>
class Simplex {
    typedef boost::coroutines2::coroutine<value_type> coro_t;
    Simplex() = delete;
  public:
    explicit Simplex(const std::vector<value_type>& columns, const double sum=1.0):
        product_(columns), sum_(sum) {}

    typename coro_t::pull_type operator()(void) {
        return typename coro_t::pull_type([this](typename coro_t::push_type& yield){source(yield);});
    }

    boost::multiprecision::cpp_int count() const {return cnt_;}
    boost::multiprecision::cpp_int count_all() const {return product_.count();}
    boost::multiprecision::cpp_int count_max() const {return product_.count_max();}

  private:
    bool equals(double x) const {
        return std::fabs(x -= sum_) < std::numeric_limits<double>::epsilon();
    }

    void source(typename coro_t::push_type& yield) {
        for (const auto& v: product_()) {
            if (equals(v.sum())) {
                ++cnt_;
                yield(v);
            }
        }
    }
    Product<value_type> product_;
    const double sum_;
    boost::multiprecision::cpp_int cnt_ = 0;
};

template <class value_type>
Simplex<value_type> simplex(const std::vector<value_type>& columns, const double sum=1.0) {
    return Simplex<value_type>(columns, sum);
}

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
}} // namespace wtl::itertools
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

#endif // WTL_ITERTOOLS_HPP_
<|endoftext|>


<commit_before>//
// Created by Sam on 11/18/2017.
//

#include "../../../build/catch-src/include/catch.hpp"

#include "../../../include/Game/Python/Factory.h"

TEST_CASE("Create factory")
{
    std::shared_ptr<Factory> factory = std::make_shared<Factory>();

    SECTION("Verify creation")
    {
        REQUIRE_FALSE(factory == nullptr);
    }

    SECTION("Verify minimum python version")
    {
        std::string minimumVersion = "2.7";
        bool versionCheck = Version(minimumVersion) < factory->version;
        REQUIRE(versionCheck);
    }

    SECTION("Verify expected python version")
    {
        std::string expectedVersion = "3.6.3";
        bool versionCheck = Version(expectedVersion) == factory->version;

        if (!versionCheck)
        {
            FAIL_CHECK("Unexpected python version, expected " + expectedVersion +
                               " but factory's interpreter is running " + factory->version.toString());
        }
    }
}<commit_msg>Emptying test to try and narrow down sefault issue for future reporting<commit_after>//
// Created by Sam on 11/18/2017.
//

#include "../../../build/catch-src/include/catch.hpp"

#include "../../../include/Game/Python/Factory.h"

TEST_CASE("Create factory")
{
    std::shared_ptr<Factory> factory = std::make_shared<Factory>();
//
//    SECTION("Verify creation")
//    {
//        REQUIRE_FALSE(factory == nullptr);
//    }
//
//    SECTION("Verify minimum python version")
//    {
//        std::string minimumVersion = "2.7";
//        bool versionCheck = Version(minimumVersion) < factory->version;
//        REQUIRE(versionCheck);
//    }
//
//    SECTION("Verify expected python version")
//    {
//        std::string expectedVersion = "3.6.3";
//        bool versionCheck = Version(expectedVersion) == factory->version;
//
//        if (!versionCheck)
//        {
//            FAIL_CHECK("Unexpected python version, expected " + expectedVersion +
//                               " but factory's interpreter is running " + factory->version.toString());
//        }
//    }
}<|endoftext|>


<commit_before>/*
 * Copyright 2013 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkPictureImageFilter.h"

#include "SkCanvas.h"
#include "SkReadBuffer.h"
#include "SkSpecialImage.h"
#include "SkSpecialSurface.h"
#include "SkWriteBuffer.h"
#include "SkValidationUtils.h"

sk_sp<SkImageFilter> SkPictureImageFilter::Make(sk_sp<SkPicture> picture) {
    return sk_sp<SkImageFilter>(new SkPictureImageFilter(std::move(picture)));
}

sk_sp<SkImageFilter> SkPictureImageFilter::Make(sk_sp<SkPicture> picture,
                                                const SkRect& cropRect) {
    return sk_sp<SkImageFilter>(new SkPictureImageFilter(std::move(picture),
                                                         cropRect,
                                                         kDeviceSpace_PictureResolution,
                                                         kLow_SkFilterQuality));
}

sk_sp<SkImageFilter> SkPictureImageFilter::MakeForLocalSpace(sk_sp<SkPicture> picture,
                                                             const SkRect& cropRect,
                                                             SkFilterQuality filterQuality) {
    return sk_sp<SkImageFilter>(new SkPictureImageFilter(std::move(picture),
                                                         cropRect,
                                                         kLocalSpace_PictureResolution,
                                                         filterQuality));
}

SkPictureImageFilter::SkPictureImageFilter(sk_sp<SkPicture> picture)
    : INHERITED(nullptr, 0, nullptr)
    , fPicture(std::move(picture))
    , fCropRect(fPicture ? fPicture->cullRect() : SkRect::MakeEmpty())
    , fPictureResolution(kDeviceSpace_PictureResolution)
    , fFilterQuality(kLow_SkFilterQuality) {
}

SkPictureImageFilter::SkPictureImageFilter(sk_sp<SkPicture> picture, const SkRect& cropRect,
                                           PictureResolution pictureResolution,
                                           SkFilterQuality filterQuality)
    : INHERITED(nullptr, 0, nullptr)
    , fPicture(std::move(picture))
    , fCropRect(cropRect)
    , fPictureResolution(pictureResolution)
    , fFilterQuality(filterQuality) {
}

sk_sp<SkFlattenable> SkPictureImageFilter::CreateProc(SkReadBuffer& buffer) {
    sk_sp<SkPicture> picture;
    SkRect cropRect;

    if (buffer.isCrossProcess() && SkPicture::PictureIOSecurityPrecautionsEnabled()) {
        buffer.validate(!buffer.readBool());
    } else {
        if (buffer.readBool()) {
            picture = SkPicture::MakeFromBuffer(buffer);
        }
    }
    buffer.readRect(&cropRect);
    PictureResolution pictureResolution;
    if (buffer.isVersionLT(SkReadBuffer::kPictureImageFilterResolution_Version)) {
        pictureResolution = kDeviceSpace_PictureResolution;
    } else {
        pictureResolution = (PictureResolution)buffer.readInt();
    }

    if (kLocalSpace_PictureResolution == pictureResolution) {
        //filterLevel is only serialized if pictureResolution is LocalSpace
        SkFilterQuality filterQuality;
        if (buffer.isVersionLT(SkReadBuffer::kPictureImageFilterLevel_Version)) {
            filterQuality = kLow_SkFilterQuality;
        } else {
            filterQuality = (SkFilterQuality)buffer.readInt();
        }
        return MakeForLocalSpace(picture, cropRect, filterQuality);
    }
    return Make(picture, cropRect);
}

void SkPictureImageFilter::flatten(SkWriteBuffer& buffer) const {
    if (buffer.isCrossProcess() && SkPicture::PictureIOSecurityPrecautionsEnabled()) {
        buffer.writeBool(false);
    } else {
        bool hasPicture = (fPicture != nullptr);
        buffer.writeBool(hasPicture);
        if (hasPicture) {
            fPicture->flatten(buffer);
        }
    }
    buffer.writeRect(fCropRect);
    buffer.writeInt(fPictureResolution);
    if (kLocalSpace_PictureResolution == fPictureResolution) {
        buffer.writeInt(fFilterQuality);
    }
}

sk_sp<SkSpecialImage> SkPictureImageFilter::onFilterImage(SkSpecialImage* source,
                                                          const Context& ctx,
                                                          SkIPoint* offset) const {
    if (!fPicture) {
        return nullptr;
    }

    SkRect floatBounds;
    ctx.ctm().mapRect(&floatBounds, fCropRect);
    SkIRect bounds = floatBounds.roundOut();
    if (!bounds.intersect(ctx.clipBounds())) {
        return nullptr;
    }

    SkASSERT(!bounds.isEmpty());

    SkImageInfo info = SkImageInfo::MakeN32(bounds.width(), bounds.height(), kPremul_SkAlphaType);
    sk_sp<SkSpecialSurface> surf(source->makeSurface(info));
    if (!surf) {
        return nullptr;
    }

    SkCanvas* canvas = surf->getCanvas();
    SkASSERT(canvas);

    canvas->clear(0x0);

    if (kDeviceSpace_PictureResolution == fPictureResolution ||
        0 == (ctx.ctm().getType() & ~SkMatrix::kTranslate_Mask)) {
        this->drawPictureAtDeviceResolution(canvas, bounds, ctx);
    } else {
        this->drawPictureAtLocalResolution(source, canvas, bounds, ctx);
    }

    offset->fX = bounds.fLeft;
    offset->fY = bounds.fTop;
    return surf->makeImageSnapshot();
}

void SkPictureImageFilter::drawPictureAtDeviceResolution(SkCanvas* canvas,
                                                         const SkIRect& deviceBounds,
                                                         const Context& ctx) const {
    canvas->translate(-SkIntToScalar(deviceBounds.fLeft), -SkIntToScalar(deviceBounds.fTop));
    canvas->concat(ctx.ctm());
    canvas->drawPicture(fPicture);
}

void SkPictureImageFilter::drawPictureAtLocalResolution(SkSpecialImage* source,
                                                        SkCanvas* canvas,
                                                        const SkIRect& deviceBounds,
                                                        const Context& ctx) const {
    SkMatrix inverseCtm;
    if (!ctx.ctm().invert(&inverseCtm)) {
        return;
    }

    SkRect localBounds = SkRect::Make(ctx.clipBounds());
    inverseCtm.mapRect(&localBounds);
    if (!localBounds.intersect(fCropRect)) {
        return;
    }
    SkIRect localIBounds = localBounds.roundOut();

    sk_sp<SkSpecialImage> localImg;
    {
        const SkImageInfo info = SkImageInfo::MakeN32(localIBounds.width(), localIBounds.height(),
                                                      kPremul_SkAlphaType);

        sk_sp<SkSpecialSurface> localSurface(source->makeSurface(info));
        if (!localSurface) {
            return;
        }

        SkCanvas* localCanvas = localSurface->getCanvas();
        SkASSERT(localCanvas);

        localCanvas->translate(-SkIntToScalar(localIBounds.fLeft),
                               -SkIntToScalar(localIBounds.fTop));
        localCanvas->drawPicture(fPicture);

        localImg = localSurface->makeImageSnapshot();
        SkASSERT(localImg);
    }

    {
        canvas->translate(-SkIntToScalar(deviceBounds.fLeft), -SkIntToScalar(deviceBounds.fTop));
        canvas->concat(ctx.ctm());
        SkPaint paint;
        paint.setFilterQuality(fFilterQuality);

        localImg->draw(canvas,
                       SkIntToScalar(localIBounds.fLeft),
                       SkIntToScalar(localIBounds.fTop),
                       &paint);
    }
}

#ifndef SK_IGNORE_TO_STRING
void SkPictureImageFilter::toString(SkString* str) const {
    str->appendf("SkPictureImageFilter: (");
    str->appendf("crop: (%f,%f,%f,%f) ",
                 fCropRect.fLeft, fCropRect.fTop, fCropRect.fRight, fCropRect.fBottom);
    if (fPicture) {
        str->appendf("picture: (%f,%f,%f,%f)",
                     fPicture->cullRect().fLeft, fPicture->cullRect().fTop,
                     fPicture->cullRect().fRight, fPicture->cullRect().fBottom);
    }
    str->append(")");
}
#endif
<commit_msg>SkPictureImageFilter - clear local canvas before use<commit_after>/*
 * Copyright 2013 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkPictureImageFilter.h"

#include "SkCanvas.h"
#include "SkReadBuffer.h"
#include "SkSpecialImage.h"
#include "SkSpecialSurface.h"
#include "SkWriteBuffer.h"
#include "SkValidationUtils.h"

sk_sp<SkImageFilter> SkPictureImageFilter::Make(sk_sp<SkPicture> picture) {
    return sk_sp<SkImageFilter>(new SkPictureImageFilter(std::move(picture)));
}

sk_sp<SkImageFilter> SkPictureImageFilter::Make(sk_sp<SkPicture> picture,
                                                const SkRect& cropRect) {
    return sk_sp<SkImageFilter>(new SkPictureImageFilter(std::move(picture),
                                                         cropRect,
                                                         kDeviceSpace_PictureResolution,
                                                         kLow_SkFilterQuality));
}

sk_sp<SkImageFilter> SkPictureImageFilter::MakeForLocalSpace(sk_sp<SkPicture> picture,
                                                             const SkRect& cropRect,
                                                             SkFilterQuality filterQuality) {
    return sk_sp<SkImageFilter>(new SkPictureImageFilter(std::move(picture),
                                                         cropRect,
                                                         kLocalSpace_PictureResolution,
                                                         filterQuality));
}

SkPictureImageFilter::SkPictureImageFilter(sk_sp<SkPicture> picture)
    : INHERITED(nullptr, 0, nullptr)
    , fPicture(std::move(picture))
    , fCropRect(fPicture ? fPicture->cullRect() : SkRect::MakeEmpty())
    , fPictureResolution(kDeviceSpace_PictureResolution)
    , fFilterQuality(kLow_SkFilterQuality) {
}

SkPictureImageFilter::SkPictureImageFilter(sk_sp<SkPicture> picture, const SkRect& cropRect,
                                           PictureResolution pictureResolution,
                                           SkFilterQuality filterQuality)
    : INHERITED(nullptr, 0, nullptr)
    , fPicture(std::move(picture))
    , fCropRect(cropRect)
    , fPictureResolution(pictureResolution)
    , fFilterQuality(filterQuality) {
}

sk_sp<SkFlattenable> SkPictureImageFilter::CreateProc(SkReadBuffer& buffer) {
    sk_sp<SkPicture> picture;
    SkRect cropRect;

    if (buffer.isCrossProcess() && SkPicture::PictureIOSecurityPrecautionsEnabled()) {
        buffer.validate(!buffer.readBool());
    } else {
        if (buffer.readBool()) {
            picture = SkPicture::MakeFromBuffer(buffer);
        }
    }
    buffer.readRect(&cropRect);
    PictureResolution pictureResolution;
    if (buffer.isVersionLT(SkReadBuffer::kPictureImageFilterResolution_Version)) {
        pictureResolution = kDeviceSpace_PictureResolution;
    } else {
        pictureResolution = (PictureResolution)buffer.readInt();
    }

    if (kLocalSpace_PictureResolution == pictureResolution) {
        //filterLevel is only serialized if pictureResolution is LocalSpace
        SkFilterQuality filterQuality;
        if (buffer.isVersionLT(SkReadBuffer::kPictureImageFilterLevel_Version)) {
            filterQuality = kLow_SkFilterQuality;
        } else {
            filterQuality = (SkFilterQuality)buffer.readInt();
        }
        return MakeForLocalSpace(picture, cropRect, filterQuality);
    }
    return Make(picture, cropRect);
}

void SkPictureImageFilter::flatten(SkWriteBuffer& buffer) const {
    if (buffer.isCrossProcess() && SkPicture::PictureIOSecurityPrecautionsEnabled()) {
        buffer.writeBool(false);
    } else {
        bool hasPicture = (fPicture != nullptr);
        buffer.writeBool(hasPicture);
        if (hasPicture) {
            fPicture->flatten(buffer);
        }
    }
    buffer.writeRect(fCropRect);
    buffer.writeInt(fPictureResolution);
    if (kLocalSpace_PictureResolution == fPictureResolution) {
        buffer.writeInt(fFilterQuality);
    }
}

sk_sp<SkSpecialImage> SkPictureImageFilter::onFilterImage(SkSpecialImage* source,
                                                          const Context& ctx,
                                                          SkIPoint* offset) const {
    if (!fPicture) {
        return nullptr;
    }

    SkRect floatBounds;
    ctx.ctm().mapRect(&floatBounds, fCropRect);
    SkIRect bounds = floatBounds.roundOut();
    if (!bounds.intersect(ctx.clipBounds())) {
        return nullptr;
    }

    SkASSERT(!bounds.isEmpty());

    SkImageInfo info = SkImageInfo::MakeN32(bounds.width(), bounds.height(), kPremul_SkAlphaType);
    sk_sp<SkSpecialSurface> surf(source->makeSurface(info));
    if (!surf) {
        return nullptr;
    }

    SkCanvas* canvas = surf->getCanvas();
    SkASSERT(canvas);

    canvas->clear(0x0);

    if (kDeviceSpace_PictureResolution == fPictureResolution ||
        0 == (ctx.ctm().getType() & ~SkMatrix::kTranslate_Mask)) {
        this->drawPictureAtDeviceResolution(canvas, bounds, ctx);
    } else {
        this->drawPictureAtLocalResolution(source, canvas, bounds, ctx);
    }

    offset->fX = bounds.fLeft;
    offset->fY = bounds.fTop;
    return surf->makeImageSnapshot();
}

void SkPictureImageFilter::drawPictureAtDeviceResolution(SkCanvas* canvas,
                                                         const SkIRect& deviceBounds,
                                                         const Context& ctx) const {
    canvas->translate(-SkIntToScalar(deviceBounds.fLeft), -SkIntToScalar(deviceBounds.fTop));
    canvas->concat(ctx.ctm());
    canvas->drawPicture(fPicture);
}

void SkPictureImageFilter::drawPictureAtLocalResolution(SkSpecialImage* source,
                                                        SkCanvas* canvas,
                                                        const SkIRect& deviceBounds,
                                                        const Context& ctx) const {
    SkMatrix inverseCtm;
    if (!ctx.ctm().invert(&inverseCtm)) {
        return;
    }

    SkRect localBounds = SkRect::Make(ctx.clipBounds());
    inverseCtm.mapRect(&localBounds);
    if (!localBounds.intersect(fCropRect)) {
        return;
    }
    SkIRect localIBounds = localBounds.roundOut();

    sk_sp<SkSpecialImage> localImg;
    {
        const SkImageInfo info = SkImageInfo::MakeN32(localIBounds.width(), localIBounds.height(),
                                                      kPremul_SkAlphaType);

        sk_sp<SkSpecialSurface> localSurface(source->makeSurface(info));
        if (!localSurface) {
            return;
        }

        SkCanvas* localCanvas = localSurface->getCanvas();
        SkASSERT(localCanvas);

        localCanvas->clear(0x0);

        localCanvas->translate(-SkIntToScalar(localIBounds.fLeft),
                               -SkIntToScalar(localIBounds.fTop));
        localCanvas->drawPicture(fPicture);

        localImg = localSurface->makeImageSnapshot();
        SkASSERT(localImg);
    }

    {
        canvas->translate(-SkIntToScalar(deviceBounds.fLeft), -SkIntToScalar(deviceBounds.fTop));
        canvas->concat(ctx.ctm());
        SkPaint paint;
        paint.setFilterQuality(fFilterQuality);

        localImg->draw(canvas,
                       SkIntToScalar(localIBounds.fLeft),
                       SkIntToScalar(localIBounds.fTop),
                       &paint);
    }
}

#ifndef SK_IGNORE_TO_STRING
void SkPictureImageFilter::toString(SkString* str) const {
    str->appendf("SkPictureImageFilter: (");
    str->appendf("crop: (%f,%f,%f,%f) ",
                 fCropRect.fLeft, fCropRect.fTop, fCropRect.fRight, fCropRect.fBottom);
    if (fPicture) {
        str->appendf("picture: (%f,%f,%f,%f)",
                     fPicture->cullRect().fLeft, fPicture->cullRect().fTop,
                     fPicture->cullRect().fRight, fPicture->cullRect().fBottom);
    }
    str->append(")");
}
#endif
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (ivan.frade@nokia.com)
**
** This file is part of the test suite of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at ivan.frade@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>
#include <QtSparql/QtSparql>

#include "private/qsparqlconnection_p.h"
#include "private/qsparqldriver_p.h"
//const QString qtest(qTableName( "qtest", __FILE__ )); // FIXME: what's this

//TESTED_FILES=

class MockDriver;

class MockResult : public QSparqlResult
{
    Q_OBJECT
    public:
    MockResult(const MockDriver* d);
    int size() const
    {
        return size_;
    }

    QSparqlResultRow current() const
    {
        return QSparqlResultRow();
    }

    QSparqlBinding binding(int) const
    {
        return QSparqlBinding();
    }

    QVariant value(int) const
    {
        return QVariant();
    }
public:
    static int size_;
};

class MockDriver : public QSparqlDriver
{
    Q_OBJECT
    public:
    MockDriver()
    {
    }
    ~MockDriver()
    {
    }
    bool open(const QSparqlConnectionOptions&)
    {
        ++openCount;
        setOpen(openRetVal);
        return openRetVal;
    }

    void close()
    {
        ++closeCount;
    }
    bool hasFeature(QSparqlConnection::Feature) const
    {
        return false;
    }
    MockResult* exec(const QString&, QSparqlQuery::StatementType)
    {
        return new MockResult(this);
    }
    static int openCount;
    static int closeCount;
    static bool openRetVal;
};

int MockResult::size_ = 0;

int MockDriver::openCount = 0;
int MockDriver::closeCount = 0;
bool MockDriver::openRetVal = true;

MockResult::MockResult(const MockDriver*)
    : QSparqlResult()
{
}

class MockDriverCreator : public QSparqlDriverCreatorBase
{
    QSparqlDriver* createObject() const
    {
        return new MockDriver();
    }
};

class tst_QSparql : public QObject
{
    Q_OBJECT

public:
    tst_QSparql();
    virtual ~tst_QSparql();

public slots:
    void initTestCase();
    void cleanupTestCase();
    void init();
    void cleanup();

private slots:
    void mock_creation();
    void wrong_creation();
    void open_fails();
    void connection_scope();
    void drivers_list();

    void iterate_empty_result();
    void iterate_nonempty_result();
    void iterate_nonempty_result_backwards();
};

tst_QSparql::tst_QSparql()
{
}

tst_QSparql::~tst_QSparql()
{
}

void tst_QSparql::initTestCase()
{
    qSparqlRegisterConnectionCreator("MOCK", new MockDriverCreator());

    // For running the test without installing the plugins. Should work in
    // normal and vpath builds.
    QCoreApplication::addLibraryPath("../../../plugins");
}

void tst_QSparql::cleanupTestCase()
{
}

void tst_QSparql::init()
{
    MockDriver::openCount = 0;
    MockDriver::closeCount = 0;
    MockDriver::openRetVal = true;
    MockResult::size_ = 0;
}

void tst_QSparql::cleanup()
{
}

void tst_QSparql::mock_creation()
{
    QSparqlConnection conn("MOCK");
    QCOMPARE(MockDriver::openCount, 1);
}

void tst_QSparql::wrong_creation()
{
    QSparqlConnection conn("TOTALLYNOTTHERE");
    QSparqlResult* res = conn.exec(QSparqlQuery("foo"));
    QVERIFY(res->hasError());
    QCOMPARE(res->lastError().type(), QSparqlError::ConnectionError);
}

void tst_QSparql::open_fails()
{
    MockDriver::openRetVal = false;
    QSparqlConnection conn("MOCK");
    QSparqlResult* res = conn.exec(QSparqlQuery("foo"));
    QVERIFY(res->hasError());
    QCOMPARE(res->lastError().type(), QSparqlError::ConnectionError);
}

void tst_QSparql::connection_scope()
{
    {
        QSparqlConnection conn("MOCK");
    }
    QCOMPARE(MockDriver::openCount, 1);
    QCOMPARE(MockDriver::closeCount, 1);
}

void tst_QSparql::drivers_list()
{
    QStringList expectedDrivers;
    expectedDrivers << "QSPARQL_ENDPOINT" << "QTRACKER" << "QTRACKER_DIRECT" << "QVIRTUOSO" << "MOCK";

    QStringList drivers = QSparqlConnection::drivers();
    foreach (const QString& driver, drivers) {
        QVERIFY(expectedDrivers.contains(driver));
        // qDebug() << driver;
    }
    QVERIFY(drivers.size() >= 1);
    QVERIFY(drivers.contains("MOCK"));
}

void tst_QSparql::iterate_empty_result()
{
    QSparqlConnection conn("MOCK");
    QSparqlResult* res = conn.exec(QSparqlQuery("foo"));
    QVERIFY(!res->hasError());
    QVERIFY(res->pos() == QSparql::BeforeFirstRow);
    QVERIFY(!res->next());
    // QVERIFY(res->pos() == QSparql::AfterLastRow); // fails
    delete res;
}

void tst_QSparql::iterate_nonempty_result()
{
    QSparqlConnection conn("MOCK");
    QSparqlResult* res = conn.exec(QSparqlQuery("foo"));
    QVERIFY(!res->hasError());
    MockResult::size_ = 2;
    QVERIFY(res->pos() == QSparql::BeforeFirstRow);
    QVERIFY(res->next());
    QCOMPARE(res->pos(), 0);
    QVERIFY(res->next());
    QCOMPARE(res->pos(), 1);
    QVERIFY(!res->next());
    QVERIFY(res->pos() == QSparql::AfterLastRow);
    res->first();
    QVERIFY(res->pos() == 0);
    res->last();
    QVERIFY(res->pos() == 1);
    delete res;
}

void tst_QSparql::iterate_nonempty_result_backwards()
{
    QSparqlConnection conn("MOCK");
    QSparqlResult* res = conn.exec(QSparqlQuery("foo"));
    QVERIFY(!res->hasError());
    MockResult::size_ = 2;
    // Get the result to the last position
    QVERIFY(res->last());
    QVERIFY(!res->next());
    // And then iterate
    QVERIFY(res->pos() == QSparql::AfterLastRow);
    QVERIFY(res->previous());
    QCOMPARE(res->pos(), 1);
    QVERIFY(res->previous());
    QCOMPARE(res->pos(), 0);
    QVERIFY(!res->previous());
    QVERIFY(res->pos() == QSparql::BeforeFirstRow);
    delete res;
}

QTEST_MAIN(tst_QSparql)
#include "tst_qsparql.moc"

<commit_msg>Still more tests.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (ivan.frade@nokia.com)
**
** This file is part of the test suite of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at ivan.frade@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>
#include <QtSparql/QtSparql>

#include "private/qsparqlconnection_p.h"
#include "private/qsparqldriver_p.h"
//const QString qtest(qTableName( "qtest", __FILE__ )); // FIXME: what's this

//TESTED_FILES=

class MockDriver;

class MockResult : public QSparqlResult
{
    Q_OBJECT
    public:
    MockResult(const MockDriver* d);
    int size() const
    {
        return size_;
    }

    QSparqlResultRow current() const
    {
        return QSparqlResultRow();
    }

    QSparqlBinding binding(int) const
    {
        return QSparqlBinding();
    }

    QVariant value(int) const
    {
        return QVariant();
    }
public:
    static int size_;
};

class MockDriver : public QSparqlDriver
{
    Q_OBJECT
    public:
    MockDriver()
    {
    }
    ~MockDriver()
    {
    }
    bool open(const QSparqlConnectionOptions&)
    {
        ++openCount;
        setOpen(openRetVal);
        return openRetVal;
    }

    void close()
    {
        ++closeCount;
    }
    bool hasFeature(QSparqlConnection::Feature) const
    {
        return false;
    }
    MockResult* exec(const QString&, QSparqlQuery::StatementType)
    {
        return new MockResult(this);
    }
    static int openCount;
    static int closeCount;
    static bool openRetVal;
};

int MockResult::size_ = 0;

int MockDriver::openCount = 0;
int MockDriver::closeCount = 0;
bool MockDriver::openRetVal = true;

MockResult::MockResult(const MockDriver*)
    : QSparqlResult()
{
}

class MockDriverCreator : public QSparqlDriverCreatorBase
{
    QSparqlDriver* createObject() const
    {
        return new MockDriver();
    }
};

class tst_QSparql : public QObject
{
    Q_OBJECT

public:
    tst_QSparql();
    virtual ~tst_QSparql();

public slots:
    void initTestCase();
    void cleanupTestCase();
    void init();
    void cleanup();

private slots:
    void mock_creation();
    void wrong_creation();
    void open_fails();
    void connection_scope();
    void drivers_list();

    void iterate_empty_result();
    void iterate_nonempty_result();
    void iterate_nonempty_result_backwards();
};

tst_QSparql::tst_QSparql()
{
}

tst_QSparql::~tst_QSparql()
{
}

void tst_QSparql::initTestCase()
{
    qSparqlRegisterConnectionCreator("MOCK", new MockDriverCreator());

    // For running the test without installing the plugins. Should work in
    // normal and vpath builds.
    QCoreApplication::addLibraryPath("../../../plugins");
}

void tst_QSparql::cleanupTestCase()
{
}

void tst_QSparql::init()
{
    MockDriver::openCount = 0;
    MockDriver::closeCount = 0;
    MockDriver::openRetVal = true;
    MockResult::size_ = 0;
}

void tst_QSparql::cleanup()
{
}

void tst_QSparql::mock_creation()
{
    QSparqlConnection conn("MOCK");
    QCOMPARE(MockDriver::openCount, 1);
}

void tst_QSparql::wrong_creation()
{
    QSparqlConnection conn("TOTALLYNOTTHERE");
    QSparqlResult* res = conn.exec(QSparqlQuery("foo"));
    QVERIFY(res->hasError());
    QCOMPARE(res->lastError().type(), QSparqlError::ConnectionError);
}

void tst_QSparql::open_fails()
{
    MockDriver::openRetVal = false;
    QSparqlConnection conn("MOCK");
    QSparqlResult* res = conn.exec(QSparqlQuery("foo"));
    QVERIFY(res->hasError());
    QCOMPARE(res->lastError().type(), QSparqlError::ConnectionError);
}

void tst_QSparql::connection_scope()
{
    {
        QSparqlConnection conn("MOCK");
    }
    QCOMPARE(MockDriver::openCount, 1);
    QCOMPARE(MockDriver::closeCount, 1);
}

void tst_QSparql::drivers_list()
{
    QStringList expectedDrivers;
    expectedDrivers << "QSPARQL_ENDPOINT" << "QTRACKER" << "QTRACKER_DIRECT" << "QVIRTUOSO" << "MOCK";

    QStringList drivers = QSparqlConnection::drivers();
    foreach (const QString& driver, drivers) {
        QVERIFY(expectedDrivers.contains(driver));
        // qDebug() << driver;
    }
    QVERIFY(drivers.size() >= 1);
    QVERIFY(drivers.contains("MOCK"));
}

void tst_QSparql::iterate_empty_result()
{
    QSparqlConnection conn("MOCK");
    QSparqlResult* res = conn.exec(QSparqlQuery("foo"));
    QVERIFY(!res->hasError());
    QVERIFY(res->pos() == QSparql::BeforeFirstRow);
    QVERIFY(!res->next());
    // QVERIFY(res->pos() == QSparql::AfterLastRow); // fails
    delete res;
}

void tst_QSparql::iterate_nonempty_result()
{
    QSparqlConnection conn("MOCK");
    QSparqlResult* res = conn.exec(QSparqlQuery("foo"));
    QVERIFY(!res->hasError());
    MockResult::size_ = 2;
    QVERIFY(res->pos() == QSparql::BeforeFirstRow);
    QVERIFY(res->next());
    QCOMPARE(res->pos(), 0);
    QVERIFY(res->next());
    QCOMPARE(res->pos(), 1);
    QVERIFY(!res->next());
    QVERIFY(res->pos() == QSparql::AfterLastRow);
    QVERIFY(!res->next());
    QVERIFY(res->pos() == QSparql::AfterLastRow);
    res->first();
    QVERIFY(res->pos() == 0);
    res->last();
    QVERIFY(res->pos() == 1);
    delete res;
}

void tst_QSparql::iterate_nonempty_result_backwards()
{
    QSparqlConnection conn("MOCK");
    QSparqlResult* res = conn.exec(QSparqlQuery("foo"));
    QVERIFY(!res->hasError());
    MockResult::size_ = 2;
    // Get the result to the last position
    QVERIFY(res->last());
    QVERIFY(!res->next());
    // And then iterate
    QVERIFY(res->pos() == QSparql::AfterLastRow);
    QVERIFY(res->previous());
    QCOMPARE(res->pos(), 1);
    QVERIFY(res->previous());
    QCOMPARE(res->pos(), 0);
    QVERIFY(!res->previous());
    QVERIFY(res->pos() == QSparql::BeforeFirstRow);
    QVERIFY(!res->previous());
    QVERIFY(res->pos() == QSparql::BeforeFirstRow);
    delete res;
}

QTEST_MAIN(tst_QSparql)
#include "tst_qsparql.moc"

<|endoftext|>


<commit_before>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
 *
 * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#ifndef HAVE_LIBVLC
# error This file requires libvlc
#endif

#include "Directory.h"
#include "File.h"
#include "utils/Filename.h"
#include "utils/Url.h"
#include "utils/VLCInstance.h"
#include "medialibrary/filesystem/Errors.h"
#include "logging/Logger.h"
#include "medialibrary/filesystem/IFileSystemFactory.h"

#include "compat/ConditionVariable.h"
#include "compat/Mutex.h"

#include <sys/types.h>
#include <sys/stat.h>

#ifdef _WIN32
# include "utils/Charsets.h"
#endif

#include <vlcpp/vlc.hpp>

namespace medialibrary
{
namespace fs
{

NetworkDirectory::NetworkDirectory( const std::string& mrl, fs::IFileSystemFactory& fsFactory )
    : CommonDirectory( fsFactory )
    , m_mrl( utils::url::encode( utils::url::decode( mrl ) ) )
{
    // Add the final '/' in place if needed to avoid a useless copy in the init list
    utils::file::toFolderPath( m_mrl );
}

const std::string& NetworkDirectory::mrl() const
{
    return m_mrl;
}

void NetworkDirectory::read() const
{
    VLC::Media media( VLCInstance::get(), m_mrl, VLC::Media::FromLocation );
    assert( media.parsedStatus() != VLC::Media::ParsedStatus::Done );

    compat::Mutex mutex;
    compat::ConditionVariable cond;
    VLC::Media::ParsedStatus res = VLC::Media::ParsedStatus::Skipped;

    auto eventHandler = media.eventManager().onParsedChanged(
        [&mutex, &cond, &res]( VLC::Media::ParsedStatus status) {
            std::lock_guard<compat::Mutex> lock( mutex );
            res = status;
            cond.notify_all();
        });

    std::unique_lock<compat::Mutex> lock( mutex );
    media.parseWithOptions( VLC::Media::ParseFlags::Network |
                            VLC::Media::ParseFlags::Local, -1 );
    bool success = cond.wait_for( lock, std::chrono::seconds{ 5 }, [&res]() {
        return res != VLC::Media::ParsedStatus::Skipped;
    });
    eventHandler->unregister();
    if ( success == false )
        throw errors::System{ ETIMEDOUT,
                              "Failed to browse network directory: Network is too slow" };
    if ( res == VLC::Media::ParsedStatus::Failed )
        throw errors::System{ EIO,
                              "Failed to browse network directory: Unknown error" };
    auto subItems = media.subitems();
    for ( auto i = 0; i < subItems->count(); ++i )
    {
        auto m = subItems->itemAtIndex( i );
        if ( m->type() == VLC::Media::Type::Directory )
            m_dirs.push_back( std::make_shared<fs::NetworkDirectory>( m->mrl(), m_fsFactory ) );
        else
        {
            uint32_t lastModificationDate = 0;
            int64_t fileSize = 0;
            auto mrl = m->mrl();

            if ( m_fsFactory.isNetworkFileSystem() == false )
            {
                auto path = utils::file::toLocalPath( mrl );

#ifdef _WIN32
                struct _stat64 s;
                if ( _wstat64( charset::ToWide( path.c_str() ).get(), &s ) != 0 )
                {
                    LOG_ERROR( "Failed to get ", path, " stats" );
                    throw errors::System{ errno, "Failed to get stats" };
                }
#else
                struct stat s;
                if ( lstat( path.c_str(), &s ) != 0 )
                {
                    if ( errno == EACCES )
                        continue;
                    // some Android devices will list folder content, but will yield
                    // ENOENT when accessing those.
                    // See https://trac.videolan.org/vlc/ticket/19909
                    if ( errno == ENOENT )
                    {
                        LOG_WARN( "Ignoring unexpected ENOENT while listing folder content." );
                        continue;
                    }
                    LOG_ERROR( "Failed to get file ", mrl, " info" );
                    throw errors::System{ errno, "Failed to get file info" };
                }
#endif
                lastModificationDate = s.st_mtime;
                fileSize = s.st_size;
            }
            m_files.push_back( std::make_shared<fs::NetworkFile>( std::move( mrl ),
                               m_fsFactory, lastModificationDate, fileSize ) );
        }
    }
}

}
}
<commit_msg>fs: NetworkDirectory: Tweak VLC to behave like the local fs factory<commit_after>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
 *
 * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#ifndef HAVE_LIBVLC
# error This file requires libvlc
#endif

#include "Directory.h"
#include "File.h"
#include "utils/Filename.h"
#include "utils/Url.h"
#include "utils/VLCInstance.h"
#include "medialibrary/filesystem/Errors.h"
#include "logging/Logger.h"
#include "medialibrary/filesystem/IFileSystemFactory.h"

#include "compat/ConditionVariable.h"
#include "compat/Mutex.h"

#include <sys/types.h>
#include <sys/stat.h>

#ifdef _WIN32
# include "utils/Charsets.h"
#endif

#include <vlcpp/vlc.hpp>

namespace medialibrary
{
namespace fs
{

NetworkDirectory::NetworkDirectory( const std::string& mrl, fs::IFileSystemFactory& fsFactory )
    : CommonDirectory( fsFactory )
    , m_mrl( utils::url::encode( utils::url::decode( mrl ) ) )
{
    // Add the final '/' in place if needed to avoid a useless copy in the init list
    utils::file::toFolderPath( m_mrl );
}

const std::string& NetworkDirectory::mrl() const
{
    return m_mrl;
}

void NetworkDirectory::read() const
{
    VLC::Media media( VLCInstance::get(), m_mrl, VLC::Media::FromLocation );
    assert( media.parsedStatus() != VLC::Media::ParsedStatus::Done );

    compat::Mutex mutex;
    compat::ConditionVariable cond;
    VLC::Media::ParsedStatus res = VLC::Media::ParsedStatus::Skipped;

    media.addOption( ":show-hiddenfiles=true" );
    media.addOption( ":ignore-filetypes=''" );

    auto eventHandler = media.eventManager().onParsedChanged(
        [&mutex, &cond, &res]( VLC::Media::ParsedStatus status) {
            std::lock_guard<compat::Mutex> lock( mutex );
            res = status;
            cond.notify_all();
        });

    std::unique_lock<compat::Mutex> lock( mutex );
    media.parseWithOptions( VLC::Media::ParseFlags::Network |
                            VLC::Media::ParseFlags::Local, -1 );
    bool success = cond.wait_for( lock, std::chrono::seconds{ 5 }, [&res]() {
        return res != VLC::Media::ParsedStatus::Skipped;
    });
    eventHandler->unregister();
    if ( success == false )
        throw errors::System{ ETIMEDOUT,
                              "Failed to browse network directory: Network is too slow" };
    if ( res == VLC::Media::ParsedStatus::Failed )
        throw errors::System{ EIO,
                              "Failed to browse network directory: Unknown error" };
    auto subItems = media.subitems();
    for ( auto i = 0; i < subItems->count(); ++i )
    {
        auto m = subItems->itemAtIndex( i );
        if ( m->type() == VLC::Media::Type::Directory )
            m_dirs.push_back( std::make_shared<fs::NetworkDirectory>( m->mrl(), m_fsFactory ) );
        else
        {
            uint32_t lastModificationDate = 0;
            int64_t fileSize = 0;
            auto mrl = m->mrl();

            if ( m_fsFactory.isNetworkFileSystem() == false )
            {
                auto path = utils::file::toLocalPath( mrl );

#ifdef _WIN32
                struct _stat64 s;
                if ( _wstat64( charset::ToWide( path.c_str() ).get(), &s ) != 0 )
                {
                    LOG_ERROR( "Failed to get ", path, " stats" );
                    throw errors::System{ errno, "Failed to get stats" };
                }
#else
                struct stat s;
                if ( lstat( path.c_str(), &s ) != 0 )
                {
                    if ( errno == EACCES )
                        continue;
                    // some Android devices will list folder content, but will yield
                    // ENOENT when accessing those.
                    // See https://trac.videolan.org/vlc/ticket/19909
                    if ( errno == ENOENT )
                    {
                        LOG_WARN( "Ignoring unexpected ENOENT while listing folder content." );
                        continue;
                    }
                    LOG_ERROR( "Failed to get file ", mrl, " info" );
                    throw errors::System{ errno, "Failed to get file info" };
                }
#endif
                lastModificationDate = s.st_mtime;
                fileSize = s.st_size;
            }
            m_files.push_back( std::make_shared<fs::NetworkFile>( std::move( mrl ),
                               m_fsFactory, lastModificationDate, fileSize ) );
        }
    }
}

}
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */
#include <TDefTableHandler.hxx>
#include <PropertyMap.hxx>
#include <ConversionHelper.hxx>
#include <ooxml/resourceids.hxx>
#include <doctok/resourceids.hxx>
#include <com/sun/star/table/BorderLine2.hpp>
#include <com/sun/star/text/TableColumnSeparator.hpp>
#include <com/sun/star/text/VertOrientation.hpp>

#include "dmapperLoggers.hxx"

namespace writerfilter {
namespace dmapper {

using namespace ::com::sun::star;

TDefTableHandler::TDefTableHandler(bool bOOXML) :
LoggedProperties(dmapper_logger, "TDefTableHandler"),
m_nLineWidth(0),
m_nLineType(0),
m_nLineColor(0),
m_nLineDistance(0),
m_bOOXML( bOOXML )
{
}

TDefTableHandler::~TDefTableHandler()
{
}

void TDefTableHandler::lcl_attribute(Id rName, Value & rVal)
{
    sal_Int32 nIntValue = rVal.getInt();
    (void)nIntValue;
    (void)rName;
    switch( rName )
    {
        case NS_rtf::LN_cellx:
            // nIntValue contains the vert. line position
            //TODO: nIntValue is wrong for negative values!
            if( nIntValue > 0x7fff )
                nIntValue -= 0xffff;
            m_aCellBorderPositions.push_back( ConversionHelper::convertTwipToMM100( nIntValue ) );
        break;
        case NS_rtf::LN_tc:
        {
            writerfilter::Reference<Properties>::Pointer_t pProperties = rVal.getProperties();
            if( pProperties.get())
            {
                pProperties->resolve( *this );
            }
        }
        break;
        //from LN_tc
        case NS_rtf::LN_FFIRSTMERGED:
        case NS_rtf::LN_FMERGED:
        case NS_rtf::LN_FVERTICAL:
        case NS_rtf::LN_FBACKWARD:
        case NS_rtf::LN_FROTATEFONT:
        case NS_rtf::LN_FVERTMERGE:
        case NS_rtf::LN_FVERTRESTART:
        break;
        case NS_rtf::LN_VERTALIGN:
            //TODO: m_aCellVertAlign is just a temporary solution! 0 - top 1 - center 2 - bottom
            m_aCellVertAlign.push_back( nIntValue );
        break;
        case NS_rtf::LN_FUNUSED:
        case NS_rtf::LN_CellPrefferedSize:
        break;
        case NS_rtf::LN_BRCTOP:
        case NS_rtf::LN_BRCLEFT:
        case NS_rtf::LN_BRCBOTTOM:
        case NS_rtf::LN_BRCRIGHT:
        {
            writerfilter::Reference<Properties>::Pointer_t pProperties = rVal.getProperties();
            localResolve( rName, pProperties );
        }
        break;
        //from LN_BRCXXXX - handled within the BorderHandler
        case NS_rtf::LN_DPTLINEWIDTH: // 0x2871
            //  width of a single line in 1/8 pt, max of 32 pt -> twip * 5 / 2.
            m_nLineWidth = nIntValue * 5 / 2;
        break;
        case NS_rtf::LN_BRCTYPE:    // 0x2872
            m_nLineType = nIntValue;
        break;
        case NS_ooxml::LN_CT_Border_color:
        case NS_rtf::LN_ICO:        // 0x2873
            m_nLineColor = nIntValue;
        break;
        case NS_rtf::LN_DPTSPACE:   // 0x2874
            m_nLineDistance = nIntValue;
        break;
        case NS_rtf::LN_FSHADOW:    // 0x2875
            //if 1 then line has shadow - unsupported
        case NS_rtf::LN_FFRAME:     // 0x2876
        case NS_rtf::LN_UNUSED2_15: // 0x2877
            // ignored
        break;
        case NS_ooxml::LN_CT_Border_themeColor:
        case NS_ooxml::LN_CT_Border_themeTint:
        case NS_ooxml::LN_CT_Border_themeShade:
            // ignored
        break;
        default:
            OSL_FAIL("unknown attribute");
    }
}

void TDefTableHandler::localResolve(Id rName, writerfilter::Reference<Properties>::Pointer_t pProperties)
{
    if( pProperties.get())
    {
        m_nLineWidth = m_nLineType = m_nLineColor = m_nLineDistance = 0;
        pProperties->resolve( *this );
        table::BorderLine2 aBorderLine;
        ConversionHelper::MakeBorderLine( m_nLineWidth,   m_nLineType, m_nLineColor,
                                                                        aBorderLine, m_bOOXML );
        bool rtl = false; // TODO
        switch( rName )
        {
            case NS_ooxml::LN_CT_TcBorders_top:
            case NS_rtf::LN_BRCTOP:
                m_aTopBorderLines.push_back(aBorderLine);
            break;
            case NS_ooxml::LN_CT_TcBorders_start:
                if( rtl )
                    m_aRightBorderLines.push_back(aBorderLine);
                else
                    m_aLeftBorderLines.push_back(aBorderLine);
            break;
            case NS_ooxml::LN_CT_TcBorders_left:
            case NS_rtf::LN_BRCLEFT:
                m_aLeftBorderLines.push_back(aBorderLine);
            break;
            case NS_ooxml::LN_CT_TcBorders_bottom:
            case NS_rtf::LN_BRCBOTTOM:
                m_aBottomBorderLines.push_back(aBorderLine);
            break;
            case NS_ooxml::LN_CT_TcBorders_end:
                if( rtl )
                    m_aLeftBorderLines.push_back(aBorderLine);
                else
                    m_aRightBorderLines.push_back(aBorderLine);
            break;
            case NS_ooxml::LN_CT_TcBorders_right:
            case NS_rtf::LN_BRCRIGHT:
                m_aRightBorderLines.push_back(aBorderLine);
            break;
            case NS_ooxml::LN_CT_TcBorders_insideH:
                m_aInsideHBorderLines.push_back(aBorderLine);
            break;
            case NS_ooxml::LN_CT_TcBorders_insideV:
                m_aInsideVBorderLines.push_back(aBorderLine);
            break;
            default:;
        }
    }
}

void TDefTableHandler::lcl_sprm(Sprm & rSprm)
{
    switch( rSprm.getId() )
    {
        case NS_ooxml::LN_CT_TcBorders_top:
        case NS_ooxml::LN_CT_TcBorders_left:
        case NS_ooxml::LN_CT_TcBorders_bottom:
        case NS_ooxml::LN_CT_TcBorders_right:
        case NS_ooxml::LN_CT_TcBorders_insideH:
        case NS_ooxml::LN_CT_TcBorders_insideV:
        case NS_ooxml::LN_CT_TcBorders_tl2br:
        case NS_ooxml::LN_CT_TcBorders_tr2bl:
        {
            writerfilter::Reference<Properties>::Pointer_t pProperties = rSprm.getProps();
            localResolve( rSprm.getId(), pProperties );
        }
        break;
        default:;
    }
}

PropertyMapPtr  TDefTableHandler::getRowProperties() const
{
    PropertyMapPtr pPropertyMap(new PropertyMap);

    // Writer only wants the separators, Word provides also the outer border positions
    if( m_aCellBorderPositions.size() > 2 )
    {
        //determine table width
        double nFullWidth = m_aCellBorderPositions[m_aCellBorderPositions.size() - 1] - m_aCellBorderPositions[0];
        //the positions have to be distibuted in a range of 10000
        const double nFullWidthRelative = 10000.;
        uno::Sequence< text::TableColumnSeparator > aSeparators( m_aCellBorderPositions.size() - 2 );
        text::TableColumnSeparator* pSeparators = aSeparators.getArray();
        for( sal_uInt32 nBorder = 1; nBorder < m_aCellBorderPositions.size() - 1; ++nBorder )
        {
            sal_Int16 nRelPos =
                sal::static_int_cast< sal_Int16 >(double(m_aCellBorderPositions[nBorder]) * nFullWidthRelative / nFullWidth );

            pSeparators[nBorder - 1].Position =  nRelPos;
            pSeparators[nBorder - 1].IsVisible = sal_True;
        }
        pPropertyMap->Insert( PROP_TABLE_COLUMN_SEPARATORS, false, uno::makeAny( aSeparators ) );
    }

    return pPropertyMap;
}

void TDefTableHandler::fillCellProperties(
            size_t nCell, ::boost::shared_ptr< TablePropertyMap > pCellProperties ) const
{
    if( m_aCellBorderPositions.size() > nCell )
    {
        sal_Int16 nVertOrient = text::VertOrientation::NONE;
        switch( m_aCellVertAlign[nCell] ) //0 - top 1 - center 2 - bottom
        {
            case 1: nVertOrient = text::VertOrientation::CENTER; break;
            case 2: nVertOrient = text::VertOrientation::BOTTOM; break;
            default:;
        }
        pCellProperties->Insert( PROP_VERT_ORIENT, false, uno::makeAny( nVertOrient ) );
    }
    if( m_aTopBorderLines.size() > nCell )
        pCellProperties->Insert( PROP_TOP_BORDER, false, uno::makeAny( m_aTopBorderLines[nCell] ) );
    if( m_aLeftBorderLines.size() > nCell )
        pCellProperties->Insert( PROP_LEFT_BORDER, false, uno::makeAny( m_aLeftBorderLines[nCell] ) );
    if( m_aBottomBorderLines.size() > nCell )
        pCellProperties->Insert( PROP_BOTTOM_BORDER, false, uno::makeAny( m_aBottomBorderLines[nCell] ) );
    if( m_aRightBorderLines.size() > nCell )
        pCellProperties->Insert( PROP_RIGHT_BORDER, false, uno::makeAny( m_aRightBorderLines[nCell] ) );
    if( m_aInsideHBorderLines.size() > nCell )
        pCellProperties->Insert( META_PROP_HORIZONTAL_BORDER, false, uno::makeAny( m_aInsideHBorderLines[nCell] ) );
    if( m_aInsideVBorderLines.size() > nCell )
        pCellProperties->Insert( META_PROP_VERTICAL_BORDER, false, uno::makeAny( m_aInsideVBorderLines[nCell] ) );
}

sal_Int32 TDefTableHandler::getTableWidth() const
{
    sal_Int32 nWidth = 0;
    if( m_aCellBorderPositions.size() > 1 )
    {
        //determine table width
        nWidth = m_aCellBorderPositions[m_aCellBorderPositions.size() - 1] - m_aCellBorderPositions[0];
    }
    return nWidth;
}

size_t TDefTableHandler::getCellCount() const
{
    return m_aCellVertAlign.size();
}

} //namespace dmapper
} //namespace writerfilter

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>docx import: handle start/end attribute in tcBorders<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */
#include <TDefTableHandler.hxx>
#include <PropertyMap.hxx>
#include <ConversionHelper.hxx>
#include <ooxml/resourceids.hxx>
#include <doctok/resourceids.hxx>
#include <com/sun/star/table/BorderLine2.hpp>
#include <com/sun/star/text/TableColumnSeparator.hpp>
#include <com/sun/star/text/VertOrientation.hpp>

#include "dmapperLoggers.hxx"

namespace writerfilter {
namespace dmapper {

using namespace ::com::sun::star;

TDefTableHandler::TDefTableHandler(bool bOOXML) :
LoggedProperties(dmapper_logger, "TDefTableHandler"),
m_nLineWidth(0),
m_nLineType(0),
m_nLineColor(0),
m_nLineDistance(0),
m_bOOXML( bOOXML )
{
}

TDefTableHandler::~TDefTableHandler()
{
}

void TDefTableHandler::lcl_attribute(Id rName, Value & rVal)
{
    sal_Int32 nIntValue = rVal.getInt();
    (void)nIntValue;
    (void)rName;
    switch( rName )
    {
        case NS_rtf::LN_cellx:
            // nIntValue contains the vert. line position
            //TODO: nIntValue is wrong for negative values!
            if( nIntValue > 0x7fff )
                nIntValue -= 0xffff;
            m_aCellBorderPositions.push_back( ConversionHelper::convertTwipToMM100( nIntValue ) );
        break;
        case NS_rtf::LN_tc:
        {
            writerfilter::Reference<Properties>::Pointer_t pProperties = rVal.getProperties();
            if( pProperties.get())
            {
                pProperties->resolve( *this );
            }
        }
        break;
        //from LN_tc
        case NS_rtf::LN_FFIRSTMERGED:
        case NS_rtf::LN_FMERGED:
        case NS_rtf::LN_FVERTICAL:
        case NS_rtf::LN_FBACKWARD:
        case NS_rtf::LN_FROTATEFONT:
        case NS_rtf::LN_FVERTMERGE:
        case NS_rtf::LN_FVERTRESTART:
        break;
        case NS_rtf::LN_VERTALIGN:
            //TODO: m_aCellVertAlign is just a temporary solution! 0 - top 1 - center 2 - bottom
            m_aCellVertAlign.push_back( nIntValue );
        break;
        case NS_rtf::LN_FUNUSED:
        case NS_rtf::LN_CellPrefferedSize:
        break;
        case NS_rtf::LN_BRCTOP:
        case NS_rtf::LN_BRCLEFT:
        case NS_rtf::LN_BRCBOTTOM:
        case NS_rtf::LN_BRCRIGHT:
        {
            writerfilter::Reference<Properties>::Pointer_t pProperties = rVal.getProperties();
            localResolve( rName, pProperties );
        }
        break;
        //from LN_BRCXXXX - handled within the BorderHandler
        case NS_rtf::LN_DPTLINEWIDTH: // 0x2871
            //  width of a single line in 1/8 pt, max of 32 pt -> twip * 5 / 2.
            m_nLineWidth = nIntValue * 5 / 2;
        break;
        case NS_rtf::LN_BRCTYPE:    // 0x2872
            m_nLineType = nIntValue;
        break;
        case NS_ooxml::LN_CT_Border_color:
        case NS_rtf::LN_ICO:        // 0x2873
            m_nLineColor = nIntValue;
        break;
        case NS_rtf::LN_DPTSPACE:   // 0x2874
            m_nLineDistance = nIntValue;
        break;
        case NS_rtf::LN_FSHADOW:    // 0x2875
            //if 1 then line has shadow - unsupported
        case NS_rtf::LN_FFRAME:     // 0x2876
        case NS_rtf::LN_UNUSED2_15: // 0x2877
            // ignored
        break;
        case NS_ooxml::LN_CT_Border_themeColor:
        case NS_ooxml::LN_CT_Border_themeTint:
        case NS_ooxml::LN_CT_Border_themeShade:
            // ignored
        break;
        default:
            OSL_FAIL("unknown attribute");
    }
}

void TDefTableHandler::localResolve(Id rName, writerfilter::Reference<Properties>::Pointer_t pProperties)
{
    if( pProperties.get())
    {
        m_nLineWidth = m_nLineType = m_nLineColor = m_nLineDistance = 0;
        pProperties->resolve( *this );
        table::BorderLine2 aBorderLine;
        ConversionHelper::MakeBorderLine( m_nLineWidth,   m_nLineType, m_nLineColor,
                                                                        aBorderLine, m_bOOXML );
        bool rtl = false; // TODO
        switch( rName )
        {
            case NS_ooxml::LN_CT_TcBorders_top:
            case NS_rtf::LN_BRCTOP:
                m_aTopBorderLines.push_back(aBorderLine);
            break;
            case NS_ooxml::LN_CT_TcBorders_start:
                if( rtl )
                    m_aRightBorderLines.push_back(aBorderLine);
                else
                    m_aLeftBorderLines.push_back(aBorderLine);
            break;
            case NS_ooxml::LN_CT_TcBorders_left:
            case NS_rtf::LN_BRCLEFT:
                m_aLeftBorderLines.push_back(aBorderLine);
            break;
            case NS_ooxml::LN_CT_TcBorders_bottom:
            case NS_rtf::LN_BRCBOTTOM:
                m_aBottomBorderLines.push_back(aBorderLine);
            break;
            case NS_ooxml::LN_CT_TcBorders_end:
                if( rtl )
                    m_aLeftBorderLines.push_back(aBorderLine);
                else
                    m_aRightBorderLines.push_back(aBorderLine);
            break;
            case NS_ooxml::LN_CT_TcBorders_right:
            case NS_rtf::LN_BRCRIGHT:
                m_aRightBorderLines.push_back(aBorderLine);
            break;
            case NS_ooxml::LN_CT_TcBorders_insideH:
                m_aInsideHBorderLines.push_back(aBorderLine);
            break;
            case NS_ooxml::LN_CT_TcBorders_insideV:
                m_aInsideVBorderLines.push_back(aBorderLine);
            break;
            default:;
        }
    }
}

void TDefTableHandler::lcl_sprm(Sprm & rSprm)
{
    switch( rSprm.getId() )
    {
        case NS_ooxml::LN_CT_TcBorders_top:
        case NS_ooxml::LN_CT_TcBorders_left:
        case NS_ooxml::LN_CT_TcBorders_start:
        case NS_ooxml::LN_CT_TcBorders_bottom:
        case NS_ooxml::LN_CT_TcBorders_right:
        case NS_ooxml::LN_CT_TcBorders_end:
        case NS_ooxml::LN_CT_TcBorders_insideH:
        case NS_ooxml::LN_CT_TcBorders_insideV:
        case NS_ooxml::LN_CT_TcBorders_tl2br:
        case NS_ooxml::LN_CT_TcBorders_tr2bl:
        {
            writerfilter::Reference<Properties>::Pointer_t pProperties = rSprm.getProps();
            localResolve( rSprm.getId(), pProperties );
        }
        break;
        default:;
    }
}

PropertyMapPtr  TDefTableHandler::getRowProperties() const
{
    PropertyMapPtr pPropertyMap(new PropertyMap);

    // Writer only wants the separators, Word provides also the outer border positions
    if( m_aCellBorderPositions.size() > 2 )
    {
        //determine table width
        double nFullWidth = m_aCellBorderPositions[m_aCellBorderPositions.size() - 1] - m_aCellBorderPositions[0];
        //the positions have to be distibuted in a range of 10000
        const double nFullWidthRelative = 10000.;
        uno::Sequence< text::TableColumnSeparator > aSeparators( m_aCellBorderPositions.size() - 2 );
        text::TableColumnSeparator* pSeparators = aSeparators.getArray();
        for( sal_uInt32 nBorder = 1; nBorder < m_aCellBorderPositions.size() - 1; ++nBorder )
        {
            sal_Int16 nRelPos =
                sal::static_int_cast< sal_Int16 >(double(m_aCellBorderPositions[nBorder]) * nFullWidthRelative / nFullWidth );

            pSeparators[nBorder - 1].Position =  nRelPos;
            pSeparators[nBorder - 1].IsVisible = sal_True;
        }
        pPropertyMap->Insert( PROP_TABLE_COLUMN_SEPARATORS, false, uno::makeAny( aSeparators ) );
    }

    return pPropertyMap;
}

void TDefTableHandler::fillCellProperties(
            size_t nCell, ::boost::shared_ptr< TablePropertyMap > pCellProperties ) const
{
    if( m_aCellBorderPositions.size() > nCell )
    {
        sal_Int16 nVertOrient = text::VertOrientation::NONE;
        switch( m_aCellVertAlign[nCell] ) //0 - top 1 - center 2 - bottom
        {
            case 1: nVertOrient = text::VertOrientation::CENTER; break;
            case 2: nVertOrient = text::VertOrientation::BOTTOM; break;
            default:;
        }
        pCellProperties->Insert( PROP_VERT_ORIENT, false, uno::makeAny( nVertOrient ) );
    }
    if( m_aTopBorderLines.size() > nCell )
        pCellProperties->Insert( PROP_TOP_BORDER, false, uno::makeAny( m_aTopBorderLines[nCell] ) );
    if( m_aLeftBorderLines.size() > nCell )
        pCellProperties->Insert( PROP_LEFT_BORDER, false, uno::makeAny( m_aLeftBorderLines[nCell] ) );
    if( m_aBottomBorderLines.size() > nCell )
        pCellProperties->Insert( PROP_BOTTOM_BORDER, false, uno::makeAny( m_aBottomBorderLines[nCell] ) );
    if( m_aRightBorderLines.size() > nCell )
        pCellProperties->Insert( PROP_RIGHT_BORDER, false, uno::makeAny( m_aRightBorderLines[nCell] ) );
    if( m_aInsideHBorderLines.size() > nCell )
        pCellProperties->Insert( META_PROP_HORIZONTAL_BORDER, false, uno::makeAny( m_aInsideHBorderLines[nCell] ) );
    if( m_aInsideVBorderLines.size() > nCell )
        pCellProperties->Insert( META_PROP_VERTICAL_BORDER, false, uno::makeAny( m_aInsideVBorderLines[nCell] ) );
}

sal_Int32 TDefTableHandler::getTableWidth() const
{
    sal_Int32 nWidth = 0;
    if( m_aCellBorderPositions.size() > 1 )
    {
        //determine table width
        nWidth = m_aCellBorderPositions[m_aCellBorderPositions.size() - 1] - m_aCellBorderPositions[0];
    }
    return nWidth;
}

size_t TDefTableHandler::getCellCount() const
{
    return m_aCellVertAlign.size();
}

} //namespace dmapper
} //namespace writerfilter

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PageMasterPropHdlFactory.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 15:27:50 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"

#ifndef _XMLOFF_PAGEMASTERPROPHDLFACTORY_HXX
#include "PageMasterPropHdlFactory.hxx"
#endif

#ifndef _XMLOFF_XMLTYPES_HXX
#include <xmloff/xmltypes.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_PROPERTYHANDLER_BASICTYPES_HXX
#include "xmlbahdl.hxx"
#endif
#ifndef _XMLOFF_NAMEDBOOLPROPERTYHANDLER_HXX
#include <xmloff/NamedBoolPropertyHdl.hxx>
#endif
#ifndef _XMLOFF_XMLTEXTCOLUMNSPPROPERTYHANDLER_HXX
#include "XMLTextColumnsPropertyHandler.hxx"
#endif
#ifndef _XMLOFF_XMLCONSTANTSPROPERTYHANDLER_HXX
#include <xmloff/XMLConstantsPropertyHandler.hxx>
#endif

#ifndef _XMLOFF_PAGEMASTERPROPHDL_HXX_
#include "PageMasterPropHdl.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX
#include <xmloff/PageMasterStyleMap.hxx>
#endif

#ifndef _COM_SUN_STAR_TEXT_TEXTGRIDMODE_HPP_
#include <com/sun/star/text/TextGridMode.hpp>
#endif

using namespace ::rtl;
using namespace ::xmloff::token;
using namespace ::com::sun::star;

SvXMLEnumMapEntry aXML_TextGridMode_ConstantMap[] =
{
    { XML_NONE,         text::TextGridMode::NONE },
    { XML_LINE,         text::TextGridMode::LINES },
    { XML_BOTH,         text::TextGridMode::LINES_AND_CHARS },
    { XML_TOKEN_INVALID, 0 }
};

//______________________________________________________________________________

XMLPageMasterPropHdlFactory::XMLPageMasterPropHdlFactory() :
    XMLPropertyHandlerFactory()
{
}

XMLPageMasterPropHdlFactory::~XMLPageMasterPropHdlFactory()
{
}

const XMLPropertyHandler* XMLPageMasterPropHdlFactory::GetPropertyHandler( sal_Int32 nType ) const
{
    nType &= MID_FLAG_MASK;

    XMLPropertyHandler* pHdl = (XMLPropertyHandler*) XMLPropertyHandlerFactory::GetPropertyHandler( nType );
    if( !pHdl )
    {
        switch( nType )
        {
            case XML_PM_TYPE_PAGESTYLELAYOUT:
                pHdl = new XMLPMPropHdl_PageStyleLayout();
            break;
            case XML_PM_TYPE_NUMFORMAT:
                pHdl = new XMLPMPropHdl_NumFormat();
            break;
            case XML_PM_TYPE_NUMLETTERSYNC:
                pHdl = new XMLPMPropHdl_NumLetterSync();
            break;
            case XML_PM_TYPE_PAPERTRAYNUMBER:
                pHdl = new XMLPMPropHdl_PaperTrayNumber();
            break;
            case XML_PM_TYPE_PRINTORIENTATION:
                pHdl = new XMLNamedBoolPropertyHdl(
                    GetXMLToken( XML_LANDSCAPE ),
                    GetXMLToken( XML_PORTRAIT ) );
            break;
            case XML_PM_TYPE_PRINTANNOTATIONS:
                pHdl = new XMLPMPropHdl_Print( XML_ANNOTATIONS );
            break;
            case XML_PM_TYPE_PRINTCHARTS:
                pHdl = new XMLPMPropHdl_Print( XML_CHARTS );
            break;
            case XML_PM_TYPE_PRINTDRAWING:
                pHdl = new XMLPMPropHdl_Print( XML_DRAWINGS );
            break;
            case XML_PM_TYPE_PRINTFORMULAS:
                pHdl = new XMLPMPropHdl_Print( XML_FORMULAS );
            break;
            case XML_PM_TYPE_PRINTGRID:
                pHdl = new XMLPMPropHdl_Print( XML_GRID );
            break;
            case XML_PM_TYPE_PRINTHEADERS:
                pHdl = new XMLPMPropHdl_Print( XML_HEADERS );
            break;
            case XML_PM_TYPE_PRINTOBJECTS:
                pHdl = new XMLPMPropHdl_Print( XML_OBJECTS );
            break;
            case XML_PM_TYPE_PRINTZEROVALUES:
                pHdl = new XMLPMPropHdl_Print( XML_ZERO_VALUES );
            break;
            case XML_PM_TYPE_PRINTPAGEORDER:
                pHdl = new XMLNamedBoolPropertyHdl( GetXMLToken( XML_TTB ),
                                                    GetXMLToken( XML_LTR ) );
            break;
            case XML_PM_TYPE_FIRSTPAGENUMBER:
                pHdl = new XMLNumberNonePropHdl( XML_CONTINUE, 2 );
            break;
            case XML_PM_TYPE_CENTER_HORIZONTAL:
                pHdl = new XMLPMPropHdl_CenterHorizontal();
            break;
            case XML_PM_TYPE_CENTER_VERTICAL:
                pHdl = new XMLPMPropHdl_CenterVertical();
            break;
            case XML_TYPE_TEXT_COLUMNS:
                pHdl = new XMLTextColumnsPropertyHandler;
            break;
            case XML_TYPE_LAYOUT_GRID_MODE:
                pHdl = new XMLConstantsPropertyHandler(
                    aXML_TextGridMode_ConstantMap, XML_NONE );
            break;
        }

        if( pHdl )
            PutHdlCache( nType, pHdl );
    }
    return pHdl;
}

<commit_msg>INTEGRATION: CWS impresstables2 (1.9.80); FILE MERGED 2007/08/01 14:25:28 cl 1.9.80.2: RESYNC: (1.9-1.10); FILE MERGED 2007/07/27 09:09:53 cl 1.9.80.1: fixed build issues due to pch and namespace ::rtl<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PageMasterPropHdlFactory.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: rt $ $Date: 2008-03-12 10:43:57 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"

#ifndef _XMLOFF_PAGEMASTERPROPHDLFACTORY_HXX
#include "PageMasterPropHdlFactory.hxx"
#endif

#ifndef _XMLOFF_XMLTYPES_HXX
#include <xmloff/xmltypes.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_PROPERTYHANDLER_BASICTYPES_HXX
#include "xmlbahdl.hxx"
#endif
#ifndef _XMLOFF_NAMEDBOOLPROPERTYHANDLER_HXX
#include <xmloff/NamedBoolPropertyHdl.hxx>
#endif
#ifndef _XMLOFF_XMLTEXTCOLUMNSPPROPERTYHANDLER_HXX
#include "XMLTextColumnsPropertyHandler.hxx"
#endif
#ifndef _XMLOFF_XMLCONSTANTSPROPERTYHANDLER_HXX
#include <xmloff/XMLConstantsPropertyHandler.hxx>
#endif

#ifndef _XMLOFF_PAGEMASTERPROPHDL_HXX_
#include "PageMasterPropHdl.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX
#include <xmloff/PageMasterStyleMap.hxx>
#endif

#ifndef _COM_SUN_STAR_TEXT_TEXTGRIDMODE_HPP_
#include <com/sun/star/text/TextGridMode.hpp>
#endif

using ::rtl::OUString;
using ::rtl::OUStringBuffer;

using namespace ::xmloff::token;
using namespace ::com::sun::star;

SvXMLEnumMapEntry aXML_TextGridMode_ConstantMap[] =
{
    { XML_NONE,         text::TextGridMode::NONE },
    { XML_LINE,         text::TextGridMode::LINES },
    { XML_BOTH,         text::TextGridMode::LINES_AND_CHARS },
    { XML_TOKEN_INVALID, 0 }
};

//______________________________________________________________________________

XMLPageMasterPropHdlFactory::XMLPageMasterPropHdlFactory() :
    XMLPropertyHandlerFactory()
{
}

XMLPageMasterPropHdlFactory::~XMLPageMasterPropHdlFactory()
{
}

const XMLPropertyHandler* XMLPageMasterPropHdlFactory::GetPropertyHandler( sal_Int32 nType ) const
{
    nType &= MID_FLAG_MASK;

    XMLPropertyHandler* pHdl = (XMLPropertyHandler*) XMLPropertyHandlerFactory::GetPropertyHandler( nType );
    if( !pHdl )
    {
        switch( nType )
        {
            case XML_PM_TYPE_PAGESTYLELAYOUT:
                pHdl = new XMLPMPropHdl_PageStyleLayout();
            break;
            case XML_PM_TYPE_NUMFORMAT:
                pHdl = new XMLPMPropHdl_NumFormat();
            break;
            case XML_PM_TYPE_NUMLETTERSYNC:
                pHdl = new XMLPMPropHdl_NumLetterSync();
            break;
            case XML_PM_TYPE_PAPERTRAYNUMBER:
                pHdl = new XMLPMPropHdl_PaperTrayNumber();
            break;
            case XML_PM_TYPE_PRINTORIENTATION:
                pHdl = new XMLNamedBoolPropertyHdl(
                    GetXMLToken( XML_LANDSCAPE ),
                    GetXMLToken( XML_PORTRAIT ) );
            break;
            case XML_PM_TYPE_PRINTANNOTATIONS:
                pHdl = new XMLPMPropHdl_Print( XML_ANNOTATIONS );
            break;
            case XML_PM_TYPE_PRINTCHARTS:
                pHdl = new XMLPMPropHdl_Print( XML_CHARTS );
            break;
            case XML_PM_TYPE_PRINTDRAWING:
                pHdl = new XMLPMPropHdl_Print( XML_DRAWINGS );
            break;
            case XML_PM_TYPE_PRINTFORMULAS:
                pHdl = new XMLPMPropHdl_Print( XML_FORMULAS );
            break;
            case XML_PM_TYPE_PRINTGRID:
                pHdl = new XMLPMPropHdl_Print( XML_GRID );
            break;
            case XML_PM_TYPE_PRINTHEADERS:
                pHdl = new XMLPMPropHdl_Print( XML_HEADERS );
            break;
            case XML_PM_TYPE_PRINTOBJECTS:
                pHdl = new XMLPMPropHdl_Print( XML_OBJECTS );
            break;
            case XML_PM_TYPE_PRINTZEROVALUES:
                pHdl = new XMLPMPropHdl_Print( XML_ZERO_VALUES );
            break;
            case XML_PM_TYPE_PRINTPAGEORDER:
                pHdl = new XMLNamedBoolPropertyHdl( GetXMLToken( XML_TTB ),
                                                    GetXMLToken( XML_LTR ) );
            break;
            case XML_PM_TYPE_FIRSTPAGENUMBER:
                pHdl = new XMLNumberNonePropHdl( XML_CONTINUE, 2 );
            break;
            case XML_PM_TYPE_CENTER_HORIZONTAL:
                pHdl = new XMLPMPropHdl_CenterHorizontal();
            break;
            case XML_PM_TYPE_CENTER_VERTICAL:
                pHdl = new XMLPMPropHdl_CenterVertical();
            break;
            case XML_TYPE_TEXT_COLUMNS:
                pHdl = new XMLTextColumnsPropertyHandler;
            break;
            case XML_TYPE_LAYOUT_GRID_MODE:
                pHdl = new XMLConstantsPropertyHandler(
                    aXML_TextGridMode_ConstantMap, XML_NONE );
            break;
        }

        if( pHdl )
            PutHdlCache( nType, pHdl );
    }
    return pHdl;
}

<|endoftext|>