<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2012-2015 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <QGraphicsDropShadowEffect>
#include <QPainter>
#include <QString>
#include <QPainterPath>
#include <QVector2D>
#include <inviwo/qt/editor/linkgraphicsitem.h>
#include <inviwo/core/ports/port.h>
#include <inviwo/core/links/propertylink.h>
#include <inviwo/qt/editor/processorlinkgraphicsitem.h>
#include <inviwo/qt/editor/processorgraphicsitem.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/network/processornetwork.h>

namespace inviwo {

LinkGraphicsItem::LinkGraphicsItem(QPointF startPoint, QPointF endPoint, ivec3 color,
                                   QPointF startDir, QPointF endDir)
    : startPoint_(startPoint)
    , endPoint_(endPoint)
    , color_(color.r, color.g, color.b)
    , startDir_(startDir)
    , endDir_(endDir) {
    setZValue(LINKGRAPHICSITEM_DEPTH);
    QGraphicsDropShadowEffect* processorShadowEffect = new QGraphicsDropShadowEffect();
    processorShadowEffect->setOffset(3.0);
    processorShadowEffect->setBlurRadius(3.0);
    setGraphicsEffect(processorShadowEffect);
}

LinkGraphicsItem::~LinkGraphicsItem() {}

void LinkGraphicsItem::paint(QPainter* p, const QStyleOptionGraphicsItem* options,
                             QWidget* widget) {
    IVW_UNUSED_PARAM(options);
    IVW_UNUSED_PARAM(widget);

    if (isSelected())
        p->setPen(QPen(Qt::darkRed, 2.0, Qt::DotLine, Qt::RoundCap));
    else
        p->setPen(QPen(color_, 2.0, Qt::DotLine, Qt::RoundCap));

    p->drawPath(path_);
}

QPainterPath LinkGraphicsItem::obtainCurvePath() const {
    QPainterPath bezierCurve;
    float dist =
        1.0f +
        std::min(50.0f, 2.0f * static_cast<float>(QVector2D(startPoint_ - endPoint_).length()));

    bezierCurve.moveTo(startPoint_);
    bezierCurve.cubicTo(startPoint_ + dist * startDir_, endPoint_ + dist * endDir_, endPoint_);
    return bezierCurve;
}

QPainterPath LinkGraphicsItem::shape() const {
    QPainterPathStroker pathStrocker;
    pathStrocker.setWidth(10.0);
    return pathStrocker.createStroke(path_);
}

QRectF LinkGraphicsItem::boundingRect() const {
    return rect_;
}

void LinkGraphicsItem::setStartPoint(QPointF startPoint) {
    updateShape();
    startPoint_ = startPoint;
}

void LinkGraphicsItem::setEndPoint(QPointF endPoint) {
    updateShape();
    endPoint_ = endPoint;
}

QPointF LinkGraphicsItem::getStartPoint() const {
    return startPoint_;
}

void LinkGraphicsItem::setStartDir(QPointF dir) {
    updateShape();
    startDir_ = dir;
}

QPointF LinkGraphicsItem::getStartDir() const {
    return startDir_;
}

void LinkGraphicsItem::setEndDir(QPointF dir) {
    updateShape();
    endDir_ = dir;
}

QPointF LinkGraphicsItem::getEndDir() const {
    return endDir_;
}

QPointF LinkGraphicsItem::getEndPoint() const {
    return endPoint_;
}

void LinkGraphicsItem::updateShape() {
    prepareGeometryChange();

    QPointF topLeft =
        QPointF(std::min(startPoint_.x(), endPoint_.x()), std::min(startPoint_.y(), endPoint_.y()));
    rect_ =  QRectF(topLeft.x() - 40.0, topLeft.y() - 10.0,
                  abs(startPoint_.x() - endPoint_.x()) + 80.0,
                  abs(startPoint_.y() - endPoint_.y()) + 20.0);

    path_ = obtainCurvePath();
}

//////////////////////////////////////////////////////////////////////////

LinkConnectionDragGraphicsItem::LinkConnectionDragGraphicsItem(ProcessorLinkGraphicsItem* outLink, QPointF endPos)
    : LinkGraphicsItem(QPointF(0,0), endPos)
    , inLeft_(endPoint_)
    , inRight_(endPoint_)
    , outLink_(outLink) {

}

LinkConnectionDragGraphicsItem::~LinkConnectionDragGraphicsItem() {}

ProcessorLinkGraphicsItem* LinkConnectionDragGraphicsItem::getSrcProcessorLinkGraphicsItem() const {
    return outLink_;
}

ProcessorGraphicsItem* LinkConnectionDragGraphicsItem::getSrcProcessorGraphicsItem() const {
    return outLink_->getProcessorGraphicsItem();
}

QPainterPath LinkConnectionDragGraphicsItem::obtainCurvePath() const {
    QPointF inLeft = inLeft_;
    QPointF inRight = inRight_;
    QPointF outRight = outLink_->getRightPos();
    QPointF outLeft = outLink_->getLeftPos();

    QPointF start;
    QPointF stop;
    QPointF ctrlPointStart;
    QPointF ctrlPointStop;
    QPointF qp = QPointF(1, 0);
    QPainterPath bezierCurve;

    if (outLeft.x() <= inLeft.x()) {
        start = outLeft;
        stop = inLeft;
        ctrlPointStart = qp;
        ctrlPointStop = -qp;
    } else if (outRight.x() >= inRight.x()) {
        start = outRight;
        stop = inRight;
        ctrlPointStart = -qp;
        ctrlPointStop = qp;
    } else {
        start = outLeft;
        stop = inRight;
        ctrlPointStart = qp;
        ctrlPointStop = qp;
    }

    float dist =
        1.0f + std::min(50.0f, 2.0f * static_cast<float>(QVector2D(start - stop).length()));
    bezierCurve.moveTo(start);
    bezierCurve.cubicTo(start + dist * ctrlPointStart, stop + dist * ctrlPointStop, stop);
    return bezierCurve;
}

void LinkConnectionDragGraphicsItem::reactToProcessorHover(ProcessorGraphicsItem* processor) {
    if (processor != nullptr) {
        inLeft_ = processor->getLinkGraphicsItem()->getRightPos();
        inRight_ = processor->getLinkGraphicsItem()->getLeftPos();
    } else {
        inLeft_ = endPoint_;
        inRight_ = endPoint_;
    }
}

void LinkConnectionDragGraphicsItem::updateShape() {
    QPointF inLeft = inLeft_;
    QPointF inRight = inRight_;
    QPointF outRight = outLink_->getRightPos();
    QPointF outLeft = outLink_->getLeftPos();

    QPointF start;
    QPointF stop;

    if (outLeft.x() < inLeft.x()) {
        start = outLeft;
        stop = inLeft;
    } else if (outRight.x() > inRight.x()) {
        start = outRight;
        stop = inRight;
    } else {
        start = outLeft;
        stop = inRight;
    }

    QPointF topLeft = QPointF(std::min(start.x(), stop.x()), std::min(start.y(), stop.y()));
    QPointF bottomRight = QPointF(std::max(start.x(), stop.x()), std::max(start.y(), stop.y()));
    rect_ =  QRectF(topLeft.x() - 30, topLeft.y() - 10, bottomRight.x() - topLeft.x() + 70,
                  bottomRight.y() - topLeft.y() + 20);

    path_ = obtainCurvePath();

    prepareGeometryChange();
}

//////////////////////////////////////////////////////////////////////////

LinkConnectionGraphicsItem::LinkConnectionGraphicsItem(ProcessorLinkGraphicsItem* outLink,
                                                       ProcessorLinkGraphicsItem* inLink)
    : LinkConnectionDragGraphicsItem(outLink, QPointF(0,0))
    , inLink_(inLink) {
    setFlags(ItemIsSelectable | ItemIsFocusable);

    outLink_->addLink(this);
    inLink_->addLink(this);

    setVisible(outLink_->isVisible() && inLink_->isVisible());
}

LinkConnectionGraphicsItem::~LinkConnectionGraphicsItem() {
    outLink_->removeLink(this);
    inLink_->removeLink(this);
}

QPainterPath LinkConnectionGraphicsItem::obtainCurvePath() const {
    QPointF inRight = inLink_->getRightPos();
    QPointF inLeft = inLink_->getLeftPos();
    QPointF outRight = outLink_->getRightPos();
    QPointF outLeft = outLink_->getLeftPos();

    QPointF start;
    QPointF stop;
    QPointF ctrlPointStart;
    QPointF ctrlPointStop;
    QPointF qp = QPointF(1, 0);
    QPainterPath bezierCurve;

    if (outLeft.x() <= inRight.x()) {
        start = outLeft;
        stop = inRight;
        ctrlPointStart = qp;
        ctrlPointStop = -qp;
    } else if (outRight.x() >= inLeft.x()) {
        start = outRight;
        stop = inLeft;
        ctrlPointStart = -qp;
        ctrlPointStop = qp;
    } else {
        start = outLeft;
        stop = inLeft;
        ctrlPointStart = qp;
        ctrlPointStop = qp;
    }

    float dist =
        1.0f + std::min(50.0f, 2.0f * static_cast<float>(QVector2D(start - stop).length()));
    bezierCurve.moveTo(start);
    bezierCurve.cubicTo(start + dist * ctrlPointStart, stop + dist * ctrlPointStop, stop);
    return bezierCurve;
}

ProcessorLinkGraphicsItem* LinkConnectionGraphicsItem::getDestProcessorLinkGraphicsItem() const {
    return inLink_;
}

ProcessorGraphicsItem* LinkConnectionGraphicsItem::getDestProcessorGraphicsItem() const {
    return inLink_->getProcessorGraphicsItem();
}

void LinkConnectionGraphicsItem::updateShape() {
    QPointF inRight = inLink_->getRightPos();
    QPointF inLeft = inLink_->getLeftPos();
    QPointF outRight = outLink_->getRightPos();
    QPointF outLeft = outLink_->getLeftPos();

    QPointF start;
    QPointF stop;

    if (outLeft.x() < inRight.x()) {
        start = outLeft;
        stop = inRight;
    } else if (outRight.x() > inLeft.x()) {
        start = outRight;
        stop = inLeft;
    } else {
        start = outLeft;
        stop = inLeft;
    }

    QPointF topLeft = QPointF(std::min(start.x(), stop.x()), std::min(start.y(), stop.y()));
    QPointF bottomRight = QPointF(std::max(start.x(), stop.x()), std::max(start.y(), stop.y()));
    rect_ = QRectF(topLeft.x() - 30, topLeft.y() - 10, bottomRight.x() - topLeft.x() + 70,
                  bottomRight.y() - topLeft.y() + 20);

    path_ = obtainCurvePath();

    prepareGeometryChange();
}

std::string getLinkInfoTableRows(const std::vector<PropertyLink *> &links, const std::string &imgName) {
    std::string str;
    std::vector<PropertyLink *>::const_iterator it = links.begin();
    while (it != links.end()) {
        Property* srcProperty = (*it)->getSourceProperty();
        Property* dstProperty = (*it)->getDestinationProperty();
        str += "
" + srcProperty->getDisplayName()
            + "		" + dstProperty->getDisplayName() + "
";
        ++it;
    }
    return str;
}

class LinkConnectionGraphicsItemMatchReverse {
public:
    LinkConnectionGraphicsItemMatchReverse(PropertyLink* link) : link_(link) {}
    bool operator()(const PropertyLink* link) const {
        return link->getDestinationProperty() == link_->getSourceProperty() &&
            link->getSourceProperty() == link_->getDestinationProperty();
    }
private:
    PropertyLink* link_;
};

void LinkConnectionGraphicsItem::showToolTip(QGraphicsSceneHelpEvent* e) {
    Processor* p1 = inLink_->getProcessorGraphicsItem()->getProcessor();
    Processor* p2 = outLink_->getProcessorGraphicsItem()->getProcessor();

    const std::vector<PropertyLink*> propertyLinks =
        InviwoApplication::getPtr()->getProcessorNetwork()->getLinksBetweenProcessors(p1, p2);

    // collect all links based on their direction

    std::vector<PropertyLink*> bidirectional;
    std::vector<PropertyLink*> outgoing;  // from processor 1
    std::vector<PropertyLink*> incoming;  // toward processor 1

    for (const auto& propertyLink : propertyLinks) {
        Processor* linkSrc = dynamic_cast<Processor*>(
            (propertyLink)->getSourceProperty()->getOwner()->getProcessor());

        if (linkSrc == p1) {
            // forward link
            std::vector<PropertyLink*>::iterator sit =
                std::find_if(incoming.begin(), incoming.end(),
                             LinkConnectionGraphicsItemMatchReverse(propertyLink));
            if (sit != incoming.end()) {
                bidirectional.push_back(propertyLink);
                incoming.erase(sit);
            } else {
                outgoing.push_back(propertyLink);
            }
        } else {  // if (linkSrc == processorB)
            std::vector<PropertyLink*>::iterator sit =
                std::find_if(outgoing.begin(), outgoing.end(),
                             LinkConnectionGraphicsItemMatchReverse(propertyLink));
            if (sit != outgoing.end()) {
                bidirectional.push_back(propertyLink);
                outgoing.erase(sit);
            } else {
                incoming.push_back(propertyLink);
            }
        }
    }

    // set up a HTML table containing three columns:
    //    props of outProcesser, link indicator, props of inProcessor
    std::string info =
        "\

";
    // put in the table header consisting of both processor names
    info += "
" + p1->getIdentifier() +
            "		" + p2->getIdentifier() + "
";

    // add outgoing links first
    info.append(getLinkInfoTableRows(outgoing, ":/icons/linkarrow_right.png"));
    // add bidirectional links
    info.append(getLinkInfoTableRows(bidirectional, ":/icons/linkarrow_bidirectional.png"));
    // add incoming links
    info.append(getLinkInfoTableRows(incoming, ":/icons/linkarrow_left.png"));

    info.append("
");

    showToolTipHelper(e, QString(info.c_str()));
}

}  // namespace<commit_msg>Qt: Use std::abs not abs....<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2012-2015 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <QGraphicsDropShadowEffect>
#include <QPainter>
#include <QString>
#include <QPainterPath>
#include <QVector2D>
#include <inviwo/qt/editor/linkgraphicsitem.h>
#include <inviwo/core/ports/port.h>
#include <inviwo/core/links/propertylink.h>
#include <inviwo/qt/editor/processorlinkgraphicsitem.h>
#include <inviwo/qt/editor/processorgraphicsitem.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/network/processornetwork.h>

namespace inviwo {

LinkGraphicsItem::LinkGraphicsItem(QPointF startPoint, QPointF endPoint, ivec3 color,
                                   QPointF startDir, QPointF endDir)
    : startPoint_(startPoint)
    , endPoint_(endPoint)
    , color_(color.r, color.g, color.b)
    , startDir_(startDir)
    , endDir_(endDir) {
    setZValue(LINKGRAPHICSITEM_DEPTH);
    QGraphicsDropShadowEffect* processorShadowEffect = new QGraphicsDropShadowEffect();
    processorShadowEffect->setOffset(3.0);
    processorShadowEffect->setBlurRadius(3.0);
    setGraphicsEffect(processorShadowEffect);
}

LinkGraphicsItem::~LinkGraphicsItem() {}

void LinkGraphicsItem::paint(QPainter* p, const QStyleOptionGraphicsItem* options,
                             QWidget* widget) {
    IVW_UNUSED_PARAM(options);
    IVW_UNUSED_PARAM(widget);

    if (isSelected())
        p->setPen(QPen(Qt::darkRed, 2.0, Qt::DotLine, Qt::RoundCap));
    else
        p->setPen(QPen(color_, 2.0, Qt::DotLine, Qt::RoundCap));

    p->drawPath(path_);
}

QPainterPath LinkGraphicsItem::obtainCurvePath() const {
    QPainterPath bezierCurve;
    float dist =
        1.0f +
        std::min(50.0f, 2.0f * static_cast<float>(QVector2D(startPoint_ - endPoint_).length()));

    bezierCurve.moveTo(startPoint_);
    bezierCurve.cubicTo(startPoint_ + dist * startDir_, endPoint_ + dist * endDir_, endPoint_);
    return bezierCurve;
}

QPainterPath LinkGraphicsItem::shape() const {
    QPainterPathStroker pathStrocker;
    pathStrocker.setWidth(10.0);
    return pathStrocker.createStroke(path_);
}

QRectF LinkGraphicsItem::boundingRect() const {
    return rect_;
}

void LinkGraphicsItem::setStartPoint(QPointF startPoint) {
    updateShape();
    startPoint_ = startPoint;
}

void LinkGraphicsItem::setEndPoint(QPointF endPoint) {
    updateShape();
    endPoint_ = endPoint;
}

QPointF LinkGraphicsItem::getStartPoint() const {
    return startPoint_;
}

void LinkGraphicsItem::setStartDir(QPointF dir) {
    updateShape();
    startDir_ = dir;
}

QPointF LinkGraphicsItem::getStartDir() const {
    return startDir_;
}

void LinkGraphicsItem::setEndDir(QPointF dir) {
    updateShape();
    endDir_ = dir;
}

QPointF LinkGraphicsItem::getEndDir() const {
    return endDir_;
}

QPointF LinkGraphicsItem::getEndPoint() const {
    return endPoint_;
}

void LinkGraphicsItem::updateShape() {
    prepareGeometryChange();

    QPointF topLeft =
        QPointF(std::min(startPoint_.x(), endPoint_.x()), std::min(startPoint_.y(), endPoint_.y()));
    rect_ =  QRectF(topLeft.x() - 40.0, topLeft.y() - 10.0,
                  std::abs(startPoint_.x() - endPoint_.x()) + 80.0,
                  std::abs(startPoint_.y() - endPoint_.y()) + 20.0);

    path_ = obtainCurvePath();
}

//////////////////////////////////////////////////////////////////////////

LinkConnectionDragGraphicsItem::LinkConnectionDragGraphicsItem(ProcessorLinkGraphicsItem* outLink, QPointF endPos)
    : LinkGraphicsItem(QPointF(0,0), endPos)
    , inLeft_(endPoint_)
    , inRight_(endPoint_)
    , outLink_(outLink) {

}

LinkConnectionDragGraphicsItem::~LinkConnectionDragGraphicsItem() {}

ProcessorLinkGraphicsItem* LinkConnectionDragGraphicsItem::getSrcProcessorLinkGraphicsItem() const {
    return outLink_;
}

ProcessorGraphicsItem* LinkConnectionDragGraphicsItem::getSrcProcessorGraphicsItem() const {
    return outLink_->getProcessorGraphicsItem();
}

QPainterPath LinkConnectionDragGraphicsItem::obtainCurvePath() const {
    QPointF inLeft = inLeft_;
    QPointF inRight = inRight_;
    QPointF outRight = outLink_->getRightPos();
    QPointF outLeft = outLink_->getLeftPos();

    QPointF start;
    QPointF stop;
    QPointF ctrlPointStart;
    QPointF ctrlPointStop;
    QPointF qp = QPointF(1, 0);
    QPainterPath bezierCurve;

    if (outLeft.x() <= inLeft.x()) {
        start = outLeft;
        stop = inLeft;
        ctrlPointStart = qp;
        ctrlPointStop = -qp;
    } else if (outRight.x() >= inRight.x()) {
        start = outRight;
        stop = inRight;
        ctrlPointStart = -qp;
        ctrlPointStop = qp;
    } else {
        start = outLeft;
        stop = inRight;
        ctrlPointStart = qp;
        ctrlPointStop = qp;
    }

    float dist =
        1.0f + std::min(50.0f, 2.0f * static_cast<float>(QVector2D(start - stop).length()));
    bezierCurve.moveTo(start);
    bezierCurve.cubicTo(start + dist * ctrlPointStart, stop + dist * ctrlPointStop, stop);
    return bezierCurve;
}

void LinkConnectionDragGraphicsItem::reactToProcessorHover(ProcessorGraphicsItem* processor) {
    if (processor != nullptr) {
        inLeft_ = processor->getLinkGraphicsItem()->getRightPos();
        inRight_ = processor->getLinkGraphicsItem()->getLeftPos();
    } else {
        inLeft_ = endPoint_;
        inRight_ = endPoint_;
    }
}

void LinkConnectionDragGraphicsItem::updateShape() {
    QPointF inLeft = inLeft_;
    QPointF inRight = inRight_;
    QPointF outRight = outLink_->getRightPos();
    QPointF outLeft = outLink_->getLeftPos();

    QPointF start;
    QPointF stop;

    if (outLeft.x() < inLeft.x()) {
        start = outLeft;
        stop = inLeft;
    } else if (outRight.x() > inRight.x()) {
        start = outRight;
        stop = inRight;
    } else {
        start = outLeft;
        stop = inRight;
    }

    QPointF topLeft = QPointF(std::min(start.x(), stop.x()), std::min(start.y(), stop.y()));
    QPointF bottomRight = QPointF(std::max(start.x(), stop.x()), std::max(start.y(), stop.y()));
    rect_ =  QRectF(topLeft.x() - 30, topLeft.y() - 10, bottomRight.x() - topLeft.x() + 70,
                  bottomRight.y() - topLeft.y() + 20);

    path_ = obtainCurvePath();

    prepareGeometryChange();
}

//////////////////////////////////////////////////////////////////////////

LinkConnectionGraphicsItem::LinkConnectionGraphicsItem(ProcessorLinkGraphicsItem* outLink,
                                                       ProcessorLinkGraphicsItem* inLink)
    : LinkConnectionDragGraphicsItem(outLink, QPointF(0,0))
    , inLink_(inLink) {
    setFlags(ItemIsSelectable | ItemIsFocusable);

    outLink_->addLink(this);
    inLink_->addLink(this);

    setVisible(outLink_->isVisible() && inLink_->isVisible());
}

LinkConnectionGraphicsItem::~LinkConnectionGraphicsItem() {
    outLink_->removeLink(this);
    inLink_->removeLink(this);
}

QPainterPath LinkConnectionGraphicsItem::obtainCurvePath() const {
    QPointF inRight = inLink_->getRightPos();
    QPointF inLeft = inLink_->getLeftPos();
    QPointF outRight = outLink_->getRightPos();
    QPointF outLeft = outLink_->getLeftPos();

    QPointF start;
    QPointF stop;
    QPointF ctrlPointStart;
    QPointF ctrlPointStop;
    QPointF qp = QPointF(1, 0);
    QPainterPath bezierCurve;

    if (outLeft.x() <= inRight.x()) {
        start = outLeft;
        stop = inRight;
        ctrlPointStart = qp;
        ctrlPointStop = -qp;
    } else if (outRight.x() >= inLeft.x()) {
        start = outRight;
        stop = inLeft;
        ctrlPointStart = -qp;
        ctrlPointStop = qp;
    } else {
        start = outLeft;
        stop = inLeft;
        ctrlPointStart = qp;
        ctrlPointStop = qp;
    }

    float dist =
        1.0f + std::min(50.0f, 2.0f * static_cast<float>(QVector2D(start - stop).length()));
    bezierCurve.moveTo(start);
    bezierCurve.cubicTo(start + dist * ctrlPointStart, stop + dist * ctrlPointStop, stop);
    return bezierCurve;
}

ProcessorLinkGraphicsItem* LinkConnectionGraphicsItem::getDestProcessorLinkGraphicsItem() const {
    return inLink_;
}

ProcessorGraphicsItem* LinkConnectionGraphicsItem::getDestProcessorGraphicsItem() const {
    return inLink_->getProcessorGraphicsItem();
}

void LinkConnectionGraphicsItem::updateShape() {
    QPointF inRight = inLink_->getRightPos();
    QPointF inLeft = inLink_->getLeftPos();
    QPointF outRight = outLink_->getRightPos();
    QPointF outLeft = outLink_->getLeftPos();

    QPointF start;
    QPointF stop;

    if (outLeft.x() < inRight.x()) {
        start = outLeft;
        stop = inRight;
    } else if (outRight.x() > inLeft.x()) {
        start = outRight;
        stop = inLeft;
    } else {
        start = outLeft;
        stop = inLeft;
    }

    QPointF topLeft = QPointF(std::min(start.x(), stop.x()), std::min(start.y(), stop.y()));
    QPointF bottomRight = QPointF(std::max(start.x(), stop.x()), std::max(start.y(), stop.y()));
    rect_ = QRectF(topLeft.x() - 30, topLeft.y() - 10, bottomRight.x() - topLeft.x() + 70,
                  bottomRight.y() - topLeft.y() + 20);

    path_ = obtainCurvePath();

    prepareGeometryChange();
}

std::string getLinkInfoTableRows(const std::vector<PropertyLink *> &links, const std::string &imgName) {
    std::string str;
    std::vector<PropertyLink *>::const_iterator it = links.begin();
    while (it != links.end()) {
        Property* srcProperty = (*it)->getSourceProperty();
        Property* dstProperty = (*it)->getDestinationProperty();
        str += "
" + srcProperty->getDisplayName()
            + "		" + dstProperty->getDisplayName() + "
";
        ++it;
    }
    return str;
}

class LinkConnectionGraphicsItemMatchReverse {
public:
    LinkConnectionGraphicsItemMatchReverse(PropertyLink* link) : link_(link) {}
    bool operator()(const PropertyLink* link) const {
        return link->getDestinationProperty() == link_->getSourceProperty() &&
            link->getSourceProperty() == link_->getDestinationProperty();
    }
private:
    PropertyLink* link_;
};

void LinkConnectionGraphicsItem::showToolTip(QGraphicsSceneHelpEvent* e) {
    Processor* p1 = inLink_->getProcessorGraphicsItem()->getProcessor();
    Processor* p2 = outLink_->getProcessorGraphicsItem()->getProcessor();

    const std::vector<PropertyLink*> propertyLinks =
        InviwoApplication::getPtr()->getProcessorNetwork()->getLinksBetweenProcessors(p1, p2);

    // collect all links based on their direction

    std::vector<PropertyLink*> bidirectional;
    std::vector<PropertyLink*> outgoing;  // from processor 1
    std::vector<PropertyLink*> incoming;  // toward processor 1

    for (const auto& propertyLink : propertyLinks) {
        Processor* linkSrc = dynamic_cast<Processor*>(
            (propertyLink)->getSourceProperty()->getOwner()->getProcessor());

        if (linkSrc == p1) {
            // forward link
            std::vector<PropertyLink*>::iterator sit =
                std::find_if(incoming.begin(), incoming.end(),
                             LinkConnectionGraphicsItemMatchReverse(propertyLink));
            if (sit != incoming.end()) {
                bidirectional.push_back(propertyLink);
                incoming.erase(sit);
            } else {
                outgoing.push_back(propertyLink);
            }
        } else {  // if (linkSrc == processorB)
            std::vector<PropertyLink*>::iterator sit =
                std::find_if(outgoing.begin(), outgoing.end(),
                             LinkConnectionGraphicsItemMatchReverse(propertyLink));
            if (sit != outgoing.end()) {
                bidirectional.push_back(propertyLink);
                outgoing.erase(sit);
            } else {
                incoming.push_back(propertyLink);
            }
        }
    }

    // set up a HTML table containing three columns:
    //    props of outProcesser, link indicator, props of inProcessor
    std::string info =
        "\

";
    // put in the table header consisting of both processor names
    info += "
" + p1->getIdentifier() +
            "		" + p2->getIdentifier() + "
";

    // add outgoing links first
    info.append(getLinkInfoTableRows(outgoing, ":/icons/linkarrow_right.png"));
    // add bidirectional links
    info.append(getLinkInfoTableRows(bidirectional, ":/icons/linkarrow_bidirectional.png"));
    // add incoming links
    info.append(getLinkInfoTableRows(incoming, ":/icons/linkarrow_left.png"));

    info.append("
");

    showToolTipHelper(e, QString(info.c_str()));
}

}  // namespace<|endoftext|>


<commit_before>#include "signverifymessagedialog.h"
#include "ui_signverifymessagedialog.h"

#include "addressbookpage.h"
#include "base58.h"
#include "guiutil.h"
#include "init.h"
#include "main.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "wallet.h"

#include <string>
#include <vector>

#include <QClipboard>

SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SignVerifyMessageDialog),
    model(0)
{
    ui->setupUi(this);

#if (QT_VERSION >= 0x040700)
    /* Do not move this to the XML file, Qt before 4.7 will choke on it */
    ui->addressIn_SM->setPlaceholderText(tr("Enter a CapriCoin address (e.g. CapriCoinfwYhBmGXcFP2Po1NpRUEiK8km2)"));
    ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature"));

    ui->addressIn_VM->setPlaceholderText(tr("Enter a CapriCoin address (e.g. CapriCoinfwYhBmGXcFP2Po1NpRUEiK8km2)"));
    ui->signatureIn_VM->setPlaceholderText(tr("Enter CapriCoin signature"));
#endif

    GUIUtil::setupAddressWidget(ui->addressIn_SM, this);
    GUIUtil::setupAddressWidget(ui->addressIn_VM, this);

    ui->addressIn_SM->installEventFilter(this);
    ui->messageIn_SM->installEventFilter(this);
    ui->signatureOut_SM->installEventFilter(this);
    ui->addressIn_VM->installEventFilter(this);
    ui->messageIn_VM->installEventFilter(this);
    ui->signatureIn_VM->installEventFilter(this);

    ui->signatureOut_SM->setFont(GUIUtil::bitcoinAddressFont());
    ui->signatureIn_VM->setFont(GUIUtil::bitcoinAddressFont());
}

SignVerifyMessageDialog::~SignVerifyMessageDialog()
{
    delete ui;
}

void SignVerifyMessageDialog::setModel(WalletModel *model)
{
    this->model = model;
}

void SignVerifyMessageDialog::setAddress_SM(QString address)
{
    ui->addressIn_SM->setText(address);
    ui->messageIn_SM->setFocus();
}

void SignVerifyMessageDialog::setAddress_VM(QString address)
{
    ui->addressIn_VM->setText(address);
    ui->messageIn_VM->setFocus();
}

void SignVerifyMessageDialog::showTab_SM(bool fShow)
{
    ui->tabWidget->setCurrentIndex(0);

    if (fShow)
        this->show();
}

void SignVerifyMessageDialog::showTab_VM(bool fShow)
{
    ui->tabWidget->setCurrentIndex(1);
    if (fShow)
        this->show();
}

void SignVerifyMessageDialog::on_addressBookButton_SM_clicked()
{
    if (model && model->getAddressTableModel())
    {
        AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this);
        dlg.setModel(model->getAddressTableModel());
        if (dlg.exec())
        {
            setAddress_SM(dlg.getReturnValue());
        }
    }
}

void SignVerifyMessageDialog::on_pasteButton_SM_clicked()
{
    setAddress_SM(QApplication::clipboard()->text());
}

void SignVerifyMessageDialog::on_signMessageButton_SM_clicked()
{
    /* Clear old signature to ensure users don't get confused on error with an old signature displayed */
    ui->signatureOut_SM->clear();

    CBitcoinAddress addr(ui->addressIn_SM->text().toStdString());
    if (!addr.IsValid())
    {
        ui->addressIn_SM->setValid(false);
        ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
        return;
    }
    CKeyID keyID;
    if (!addr.GetKeyID(keyID))
    {
        ui->addressIn_SM->setValid(false);
        ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
        return;
    }

    WalletModel::UnlockContext ctx(model->requestUnlock());
    if (!ctx.isValid())
    {
        ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled."));
        return;
    }

    CKey key;
    if (!pwalletMain->GetKey(keyID, key))
    {
        ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_SM->setText(tr("Private key for the entered address is not available."));
        return;
    }

    CDataStream ss(SER_GETHASH, 0);
    ss << strMessageMagic;
    ss << ui->messageIn_SM->document()->toPlainText().toStdString();

    std::vector<unsigned char> vchSig;
    if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))
    {
        ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>"));
        return;
    }

    ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }");
    ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>"));

    ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size())));
}

void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked()
{
    QApplication::clipboard()->setText(ui->signatureOut_SM->text());
}

void SignVerifyMessageDialog::on_clearButton_SM_clicked()
{
    ui->addressIn_SM->clear();
    ui->messageIn_SM->clear();
    ui->signatureOut_SM->clear();
    ui->statusLabel_SM->clear();

    ui->addressIn_SM->setFocus();
}

void SignVerifyMessageDialog::on_addressBookButton_VM_clicked()
{
    if (model && model->getAddressTableModel())
    {
        AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
        dlg.setModel(model->getAddressTableModel());
        if (dlg.exec())
        {
            setAddress_VM(dlg.getReturnValue());
        }
    }
}

void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked()
{
    CBitcoinAddress addr(ui->addressIn_VM->text().toStdString());
    if (!addr.IsValid())
    {
        ui->addressIn_VM->setValid(false);
        ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
        return;
    }
    CKeyID keyID;
    if (!addr.GetKeyID(keyID))
    {
        ui->addressIn_VM->setValid(false);
        ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
        return;
    }

    bool fInvalid = false;
    std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid);

    if (fInvalid)
    {
        ui->signatureIn_VM->setValid(false);
        ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again."));
        return;
    }

    CDataStream ss(SER_GETHASH, 0);
    ss << strMessageMagic;
    ss << ui->messageIn_VM->document()->toPlainText().toStdString();

    CKey key;
    if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig))
    {
        ui->signatureIn_VM->setValid(false);
        ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again."));
        return;
    }

    if (!(CBitcoinAddress(key.GetPubKey().GetID()) == addr))
    {
        ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>"));
        return;
    }

    ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }");
    ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>"));
}

void SignVerifyMessageDialog::on_clearButton_VM_clicked()
{
    ui->addressIn_VM->clear();
    ui->signatureIn_VM->clear();
    ui->messageIn_VM->clear();
    ui->statusLabel_VM->clear();

    ui->addressIn_VM->setFocus();
}

bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn)
    {
        if (ui->tabWidget->currentIndex() == 0)
        {
            /* Clear status message on focus change */
            ui->statusLabel_SM->clear();

            /* Select generated signature */
            if (object == ui->signatureOut_SM)
            {
                ui->signatureOut_SM->selectAll();
                return true;
            }
        }
        else if (ui->tabWidget->currentIndex() == 1)
        {
            /* Clear status message on focus change */
            ui->statusLabel_VM->clear();
        }
    }
    return QDialog::eventFilter(object, event);
}
<commit_msg>Update signverifymessagedialog.cpp<commit_after>#include "signverifymessagedialog.h"
#include "ui_signverifymessagedialog.h"

#include "addressbookpage.h"
#include "base58.h"
#include "guiutil.h"
#include "init.h"
#include "main.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "wallet.h"

#include <string>
#include <vector>

#include <QClipboard>

SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SignVerifyMessageDialog),
    model(0)
{
    ui->setupUi(this);

#if (QT_VERSION >= 0x040700)
    /* Do not move this to the XML file, Qt before 4.7 will choke on it */
    ui->addressIn_SM->setPlaceholderText(tr("Enter a Capricoin address (e.g. CapricoinfwYhBmGXcFP2Po1NpRUEiK8km2)"));
    ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature"));

    ui->addressIn_VM->setPlaceholderText(tr("Enter a Capricoin address (e.g. CapricoinfwYhBmGXcFP2Po1NpRUEiK8km2)"));
    ui->signatureIn_VM->setPlaceholderText(tr("Enter Capricoin signature"));
#endif

    GUIUtil::setupAddressWidget(ui->addressIn_SM, this);
    GUIUtil::setupAddressWidget(ui->addressIn_VM, this);

    ui->addressIn_SM->installEventFilter(this);
    ui->messageIn_SM->installEventFilter(this);
    ui->signatureOut_SM->installEventFilter(this);
    ui->addressIn_VM->installEventFilter(this);
    ui->messageIn_VM->installEventFilter(this);
    ui->signatureIn_VM->installEventFilter(this);

    ui->signatureOut_SM->setFont(GUIUtil::bitcoinAddressFont());
    ui->signatureIn_VM->setFont(GUIUtil::bitcoinAddressFont());
}

SignVerifyMessageDialog::~SignVerifyMessageDialog()
{
    delete ui;
}

void SignVerifyMessageDialog::setModel(WalletModel *model)
{
    this->model = model;
}

void SignVerifyMessageDialog::setAddress_SM(QString address)
{
    ui->addressIn_SM->setText(address);
    ui->messageIn_SM->setFocus();
}

void SignVerifyMessageDialog::setAddress_VM(QString address)
{
    ui->addressIn_VM->setText(address);
    ui->messageIn_VM->setFocus();
}

void SignVerifyMessageDialog::showTab_SM(bool fShow)
{
    ui->tabWidget->setCurrentIndex(0);

    if (fShow)
        this->show();
}

void SignVerifyMessageDialog::showTab_VM(bool fShow)
{
    ui->tabWidget->setCurrentIndex(1);
    if (fShow)
        this->show();
}

void SignVerifyMessageDialog::on_addressBookButton_SM_clicked()
{
    if (model && model->getAddressTableModel())
    {
        AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this);
        dlg.setModel(model->getAddressTableModel());
        if (dlg.exec())
        {
            setAddress_SM(dlg.getReturnValue());
        }
    }
}

void SignVerifyMessageDialog::on_pasteButton_SM_clicked()
{
    setAddress_SM(QApplication::clipboard()->text());
}

void SignVerifyMessageDialog::on_signMessageButton_SM_clicked()
{
    /* Clear old signature to ensure users don't get confused on error with an old signature displayed */
    ui->signatureOut_SM->clear();

    CBitcoinAddress addr(ui->addressIn_SM->text().toStdString());
    if (!addr.IsValid())
    {
        ui->addressIn_SM->setValid(false);
        ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
        return;
    }
    CKeyID keyID;
    if (!addr.GetKeyID(keyID))
    {
        ui->addressIn_SM->setValid(false);
        ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
        return;
    }

    WalletModel::UnlockContext ctx(model->requestUnlock());
    if (!ctx.isValid())
    {
        ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled."));
        return;
    }

    CKey key;
    if (!pwalletMain->GetKey(keyID, key))
    {
        ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_SM->setText(tr("Private key for the entered address is not available."));
        return;
    }

    CDataStream ss(SER_GETHASH, 0);
    ss << strMessageMagic;
    ss << ui->messageIn_SM->document()->toPlainText().toStdString();

    std::vector<unsigned char> vchSig;
    if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))
    {
        ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>"));
        return;
    }

    ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }");
    ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>"));

    ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size())));
}

void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked()
{
    QApplication::clipboard()->setText(ui->signatureOut_SM->text());
}

void SignVerifyMessageDialog::on_clearButton_SM_clicked()
{
    ui->addressIn_SM->clear();
    ui->messageIn_SM->clear();
    ui->signatureOut_SM->clear();
    ui->statusLabel_SM->clear();

    ui->addressIn_SM->setFocus();
}

void SignVerifyMessageDialog::on_addressBookButton_VM_clicked()
{
    if (model && model->getAddressTableModel())
    {
        AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
        dlg.setModel(model->getAddressTableModel());
        if (dlg.exec())
        {
            setAddress_VM(dlg.getReturnValue());
        }
    }
}

void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked()
{
    CBitcoinAddress addr(ui->addressIn_VM->text().toStdString());
    if (!addr.IsValid())
    {
        ui->addressIn_VM->setValid(false);
        ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
        return;
    }
    CKeyID keyID;
    if (!addr.GetKeyID(keyID))
    {
        ui->addressIn_VM->setValid(false);
        ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
        return;
    }

    bool fInvalid = false;
    std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid);

    if (fInvalid)
    {
        ui->signatureIn_VM->setValid(false);
        ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again."));
        return;
    }

    CDataStream ss(SER_GETHASH, 0);
    ss << strMessageMagic;
    ss << ui->messageIn_VM->document()->toPlainText().toStdString();

    CKey key;
    if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig))
    {
        ui->signatureIn_VM->setValid(false);
        ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again."));
        return;
    }

    if (!(CBitcoinAddress(key.GetPubKey().GetID()) == addr))
    {
        ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>"));
        return;
    }

    ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }");
    ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>"));
}

void SignVerifyMessageDialog::on_clearButton_VM_clicked()
{
    ui->addressIn_VM->clear();
    ui->signatureIn_VM->clear();
    ui->messageIn_VM->clear();
    ui->statusLabel_VM->clear();

    ui->addressIn_VM->setFocus();
}

bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn)
    {
        if (ui->tabWidget->currentIndex() == 0)
        {
            /* Clear status message on focus change */
            ui->statusLabel_SM->clear();

            /* Select generated signature */
            if (object == ui->signatureOut_SM)
            {
                ui->signatureOut_SM->selectAll();
                return true;
            }
        }
        else if (ui->tabWidget->currentIndex() == 1)
        {
            /* Clear status message on focus change */
            ui->statusLabel_VM->clear();
        }
    }
    return QDialog::eventFilter(object, event);
}
<|endoftext|>


<commit_before>/* Copyright 2010 Antonie Jovanoski
 *
 * Licensed 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
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com>
 */

#include <QtDebug>
#include <QNetworkRequest>
#include <QNetworkReply>
#include "qtweetdirectmessagedestroy.h"
#include "qtweetdmstatus.h"
#include "qtweetconvert.h"
#include "json/qjsondocument.h"
#include "json/qjsonobject.h"

/**
 *  Constructor
 */
QTweetDirectMessageDestroy::QTweetDirectMessageDestroy(QObject *parent) :
    QTweetNetBase(parent)
{
}

/**
 *  Constructor
 *  @param oauthTwitter OAuthTwitter object
 *  @param parent parent QObject
 */
QTweetDirectMessageDestroy::QTweetDirectMessageDestroy(OAuthTwitter *oauthTwitter, QObject *parent) :
        QTweetNetBase(oauthTwitter, parent)
{
}

/**
 *   @param id the ID of the direct message to delete.
 *   @param includeEntities When set to true, each tweet will include a node called "entities,"
 */
void QTweetDirectMessageDestroy::destroyMessage(qint64 id, bool includeEntities)
{
    if (!isAuthenticationEnabled()) {
        qCritical("Needs authentication to be enabled");
        return;
    }

    QUrl url(QString("http://api.twitter.com/1/direct_messages/destroy/%1.json").arg(id));

    if (includeEntities)
        url.addQueryItem("include_entities", "true");

    QNetworkRequest req(url);

    QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(url, OAuth::DELETE);
    req.setRawHeader(AUTH_HEADER, oauthHeader);

    QNetworkReply *reply = oauthTwitter()->networkAccessManager()->deleteResource(req);
    connect(reply, SIGNAL(finished()), this, SLOT(reply()));
}

void QTweetDirectMessageDestroy::parseJsonFinished(const QJsonDocument &jsonDoc)
{
    if (jsonDoc.isObject()) {
        QTweetDMStatus dm = QTweetConvert::jsonObjectToDirectMessage(jsonDoc.object());

        emit parsedDirectMessage(dm);
    }
}

<commit_msg>Update QTweetDirectMessageDestroy to use 1.1 API<commit_after>/* Copyright 2010 Antonie Jovanoski
 *
 * Licensed 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
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com>
 */

#include <QtDebug>
#include <QNetworkRequest>
#include <QNetworkReply>
#include "qtweetdirectmessagedestroy.h"
#include "qtweetdmstatus.h"
#include "qtweetconvert.h"
#include "json/qjsondocument.h"
#include "json/qjsonobject.h"

/**
 *  Constructor
 */
QTweetDirectMessageDestroy::QTweetDirectMessageDestroy(QObject *parent) :
    QTweetNetBase(parent)
{
}

/**
 *  Constructor
 *  @param oauthTwitter OAuthTwitter object
 *  @param parent parent QObject
 */
QTweetDirectMessageDestroy::QTweetDirectMessageDestroy(OAuthTwitter *oauthTwitter, QObject *parent) :
        QTweetNetBase(oauthTwitter, parent)
{
}

/**
 *   @param id the ID of the direct message to delete.
 *   @param includeEntities When set to true, each tweet will include a node called "entities,"
 */
void QTweetDirectMessageDestroy::destroyMessage(qint64 id, bool includeEntities)
{
    if (!isAuthenticationEnabled()) {
        qCritical("Needs authentication to be enabled");
        return;
    }

    QUrl url("https://api.twitter.com/1.1/direct_messages/destroy.json");
    QUrl urlQuery("https://api.twitter.com/1.1/direct_messages/destroy.json");

    urlQuery.addQueryItem("id", QString::number(id));

    if (includeEntities)
        urlQuery.addQueryItem("include_entities", "true");

    QNetworkRequest req(url);

    QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(urlQuery, OAuth::POST);
    req.setRawHeader(AUTH_HEADER, oauthHeader);
    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    QByteArray statusPost = urlQuery.toEncoded(QUrl::RemoveScheme | QUrl::RemoveAuthority | QUrl::RemovePath);
    statusPost.remove(0, 1);

    QNetworkReply *reply = oauthTwitter()->networkAccessManager()->post(req, statusPost);
    connect(reply, SIGNAL(finished()), this, SLOT(reply()));
}

void QTweetDirectMessageDestroy::parseJsonFinished(const QJsonDocument &jsonDoc)
{
    if (jsonDoc.isObject()) {
        QTweetDMStatus dm = QTweetConvert::jsonObjectToDirectMessage(jsonDoc.object());

        emit parsedDirectMessage(dm);
    }
}

<|endoftext|>


<commit_before>/***************************************
** Tsunagari Tile Engine              **
** resources-physfs.cpp               **
** Copyright 2011-2015 Michael Reiley **
** Copyright 2011-2016 Paul Merrill   **
***************************************/

// **********
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// **********

#include "resources/resources-physfs.h"

#include <physfs.h>

#include <limits>
#include <mutex>

#include "core/formatter.h"
#include "core/log.h"
#include "core/measure.h"

#include "data/data-world.h"

PhysfsResource::PhysfsResource(std::unique_ptr<const char[]> data, size_t size)
    : _data(std::move(data)), _size(size)
{
}

const void* PhysfsResource::data()
{
    return _data.get();
}

size_t PhysfsResource::size()
{
    return _size;
}

static PhysfsResources globalResources;
static std::mutex globalPhysfsMutex;

Resources& Resources::instance()
{
    return globalResources;
}

PhysfsResources::PhysfsResources()
    : initialized(false)
{
}

static void initialize()
{
    if (!PHYSFS_init(nullptr)) {
        Log::fatal("Resources", "PHYSFS_init");
    }

    const std::string& path = DataWorld::instance().datafile;

    if (!PHYSFS_mount(path.c_str(), nullptr, 0)) {
        Log::fatal(
            "Resources",
            Formatter("%: could not open archive: %")
                % path % PHYSFS_getLastError()
        );
    }
}

std::unique_ptr<Resource> PhysfsResources::load(const std::string& path)
{
    std::lock_guard<std::mutex> lock(globalPhysfsMutex);

    TimeMeasure m("Mapped " + path);

    if (!initialized) {
        initialized = true;
        initialize();
    }

    const std::string fullPath = DataWorld::instance().datafile + "/" + path;

    if (!PHYSFS_exists(path.c_str())) {
        Log::err(
            "Resources",
            Formatter("%: file missing") % fullPath
        );
        return std::unique_ptr<Resource>();
    }

    PHYSFS_File* zf = PHYSFS_openRead(path.c_str());
    if (!zf) {
        Log::err(
            "Resources",
            Formatter("%: error opening file: %")
                % fullPath % PHYSFS_getLastError()
        );
        return std::unique_ptr<Resource>();
    }

    PHYSFS_sint64 foundSize = PHYSFS_fileLength(zf);

    if (foundSize == -1) {
        Log::err(
            "Resources",
            Formatter("%: could not determine file size: %")
                % fullPath % PHYSFS_getLastError()
        );
        PHYSFS_close(zf);
        return std::unique_ptr<Resource>();;
    }
    else if ((size_t)foundSize > std::numeric_limits<size_t>::max()) {
        // Won't fit in memory.
        Log::err(
            "Resources",
            Formatter("%: file too large") % fullPath
        );
        PHYSFS_close(zf);
        return std::unique_ptr<Resource>();;
    }
    else if (foundSize > std::numeric_limits<uint32_t>::max()) {
        // FIXME: Technically, we just need to issue multiple calls to
        // PHYSFS_read. Fix when needed.
        Log::err(
            "Resources",
            Formatter("%: file too large") % fullPath
        );
        PHYSFS_close(zf);
        return std::unique_ptr<Resource>();;
    }
    else if (foundSize < -1) {
        Log::err(
            "Resources",
            Formatter("%: invalid file size: %")
                % fullPath % PHYSFS_getLastError()
        );
        PHYSFS_close(zf);
        return std::unique_ptr<Resource>();;
    }

    size_t size = (size_t)foundSize;

    auto data = std::make_unique<char[]>(size);
    if (size == 0) {
        // Don't perform file read if file is zero bytes.
        return std::make_unique<PhysfsResource>(std::move(data), size);
    }

    PHYSFS_sint64 err = PHYSFS_read(zf, (char*)data.get(),
        (PHYSFS_uint32)size, 1);
    if (err != 1) {
        Log::err(
            "Resources",
            Formatter("%: error reading file: %")
                % fullPath % PHYSFS_getLastError()
        );
        PHYSFS_close(zf);
        return std::unique_ptr<Resource>();;
    }

    return std::make_unique<PhysfsResource>(std::move(data), size);
}
<commit_msg>PhysFS: Close files after reading from them<commit_after>/***************************************
** Tsunagari Tile Engine              **
** resources-physfs.cpp               **
** Copyright 2011-2015 Michael Reiley **
** Copyright 2011-2016 Paul Merrill   **
***************************************/

// **********
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// **********

#include "resources/resources-physfs.h"

#include <physfs.h>

#include <limits>
#include <mutex>

#include "core/formatter.h"
#include "core/log.h"
#include "core/measure.h"

#include "data/data-world.h"

PhysfsResource::PhysfsResource(std::unique_ptr<const char[]> data, size_t size)
    : _data(std::move(data)), _size(size)
{
}

const void* PhysfsResource::data()
{
    return _data.get();
}

size_t PhysfsResource::size()
{
    return _size;
}

static PhysfsResources globalResources;
static std::mutex globalPhysfsMutex;

Resources& Resources::instance()
{
    return globalResources;
}

PhysfsResources::PhysfsResources()
    : initialized(false)
{
}

static void initialize()
{
    if (!PHYSFS_init(nullptr)) {
        Log::fatal("Resources", "PHYSFS_init");
    }

    const std::string& path = DataWorld::instance().datafile;

    if (!PHYSFS_mount(path.c_str(), nullptr, 0)) {
        Log::fatal(
            "Resources",
            Formatter("%: could not open archive: %")
                % path % PHYSFS_getLastError()
        );
    }
}

std::unique_ptr<Resource> PhysfsResources::load(const std::string& path)
{
    std::lock_guard<std::mutex> lock(globalPhysfsMutex);

    TimeMeasure m("Mapped " + path);

    if (!initialized) {
        initialized = true;
        initialize();
    }

    const std::string fullPath = DataWorld::instance().datafile + "/" + path;

    if (!PHYSFS_exists(path.c_str())) {
        Log::err(
            "Resources",
            Formatter("%: file missing") % fullPath
        );
        return std::unique_ptr<Resource>();
    }

    PHYSFS_File* zf = PHYSFS_openRead(path.c_str());
    if (!zf) {
        Log::err(
            "Resources",
            Formatter("%: error opening file: %")
                % fullPath % PHYSFS_getLastError()
        );
        return std::unique_ptr<Resource>();
    }

    PHYSFS_sint64 foundSize = PHYSFS_fileLength(zf);

    if (foundSize == -1) {
        Log::err(
            "Resources",
            Formatter("%: could not determine file size: %")
                % fullPath % PHYSFS_getLastError()
        );
        PHYSFS_close(zf);
        return std::unique_ptr<Resource>();;
    }
    else if ((size_t)foundSize > std::numeric_limits<size_t>::max()) {
        // Won't fit in memory.
        Log::err(
            "Resources",
            Formatter("%: file too large") % fullPath
        );
        PHYSFS_close(zf);
        return std::unique_ptr<Resource>();;
    }
    else if (foundSize > std::numeric_limits<uint32_t>::max()) {
        // FIXME: Technically, we just need to issue multiple calls to
        // PHYSFS_read. Fix when needed.
        Log::err(
            "Resources",
            Formatter("%: file too large") % fullPath
        );
        PHYSFS_close(zf);
        return std::unique_ptr<Resource>();;
    }
    else if (foundSize < -1) {
        Log::err(
            "Resources",
            Formatter("%: invalid file size: %")
                % fullPath % PHYSFS_getLastError()
        );
        PHYSFS_close(zf);
        return std::unique_ptr<Resource>();;
    }

    size_t size = (size_t)foundSize;

    auto data = std::make_unique<char[]>(size);
    if (size == 0) {
        // Don't perform file read if file is zero bytes.
        return std::make_unique<PhysfsResource>(std::move(data), size);
    }

    PHYSFS_sint64 err = PHYSFS_read(zf, (char*)data.get(),
        (PHYSFS_uint32)size, 1);
    if (err != 1) {
        Log::err(
            "Resources",
            Formatter("%: error reading file: %")
                % fullPath % PHYSFS_getLastError()
        );
        PHYSFS_close(zf);
        return std::unique_ptr<Resource>();;
    }

    PHYSFS_close(zf);

    return std::make_unique<PhysfsResource>(std::move(data), size);
}
<|endoftext|>


<commit_before>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Claire Xenia Wolf <claire@yosyshq.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct SynthSf2Pass : public ScriptPass
{
	SynthSf2Pass() : ScriptPass("synth_sf2", "synthesis for SmartFusion2 and IGLOO2 FPGAs") { }

	void help() override
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    synth_sf2 [options]\n");
		log("\n");
		log("This command runs synthesis for SmartFusion2 and IGLOO2 FPGAs.\n");
		log("\n");
		log("    -top <module>\n");
		log("        use the specified module as top module\n");
		log("\n");
		log("    -edif <file>\n");
		log("        write the design to the specified EDIF file. writing of an output file\n");
		log("        is omitted if this parameter is not specified.\n");
		log("\n");
		log("    -vlog <file>\n");
		log("        write the design to the specified Verilog file. writing of an output\n");
		log("        file is omitted if this parameter is not specified.\n");
		log("\n");
		log("    -json <file>\n");
		log("        write the design to the specified JSON file. writing of an output file\n");
		log("        is omitted if this parameter is not specified.\n");
		log("\n");
		log("    -run <from_label>:<to_label>\n");
		log("        only run the commands between the labels (see below). an empty\n");
		log("        from label is synonymous to 'begin', and empty to label is\n");
		log("        synonymous to the end of the command list.\n");
		log("\n");
		log("    -noflatten\n");
		log("        do not flatten design before synthesis\n");
		log("\n");
		log("    -noiobs\n");
		log("        run synthesis in \"block mode\", i.e. do not insert IO buffers\n");
		log("\n");
		log("    -clkbuf\n");
		log("        insert direct PAD->global_net buffers\n");
		log("\n");
		log("    -retime\n");
		log("        run 'abc' with '-dff -D 1' options\n");
		log("\n");
		log("\n");
		log("The following commands are executed by this synthesis command:\n");
		help_script();
		log("\n");
	}

	string top_opt, edif_file, vlog_file, json_file;
	bool flatten, retime, iobs, clkbuf;

	void clear_flags() override
	{
		top_opt = "-auto-top";
		edif_file = "";
		vlog_file = "";
		json_file = "";
		flatten = true;
		retime = false;
		iobs = true;
		clkbuf = false;
	}

	void execute(std::vector<std::string> args, RTLIL::Design *design) override
	{
		string run_from, run_to;
		clear_flags();

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			if (args[argidx] == "-top" && argidx+1 < args.size()) {
				top_opt = "-top " + args[++argidx];
				continue;
			}
			if (args[argidx] == "-edif" && argidx+1 < args.size()) {
				edif_file = args[++argidx];
				continue;
			}
			if (args[argidx] == "-vlog" && argidx+1 < args.size()) {
				vlog_file = args[++argidx];
				continue;
			}
			if (args[argidx] == "-json" && argidx+1 < args.size()) {
				json_file = args[++argidx];
				continue;
			}
			if (args[argidx] == "-run" && argidx+1 < args.size()) {
				size_t pos = args[argidx+1].find(':');
				if (pos == std::string::npos)
					break;
				run_from = args[++argidx].substr(0, pos);
				run_to = args[argidx].substr(pos+1);
				continue;
			}
			if (args[argidx] == "-noflatten") {
				flatten = false;
				continue;
			}
			if (args[argidx] == "-retime") {
				retime = true;
				continue;
			}
			if (args[argidx] == "-noiobs") {
				iobs = false;
				continue;
			}
			if (args[argidx] == "-clkbuf") {
				clkbuf = true;
				continue;
			}
			break;
		}
		extra_args(args, argidx, design);

		if (!design->full_selection())
			log_cmd_error("This command only operates on fully selected designs!\n");

		log_header(design, "Executing SYNTH_SF2 pass.\n");
		log_push();

		run_script(design, run_from, run_to);

		log_pop();
	}

	void script() override
	{
		if (check_label("begin"))
		{
			run("read_verilog -lib +/sf2/cells_sim.v");
			run(stringf("hierarchy -check %s", help_mode ? "-top <top>" : top_opt.c_str()));
		}

		if (flatten && check_label("flatten", "(unless -noflatten)"))
		{
			run("proc");
			run("flatten");
			run("tribuf -logic");
			run("deminout");
		}

		if (check_label("coarse"))
		{
			run("synth -run coarse");
		}

		if (check_label("fine"))
		{
			run("opt -fast -mux_undef -undriven -fine");
			run("memory_map");
			run("opt -undriven -fine");
			run("techmap -map +/techmap.v -map +/sf2/arith_map.v");
			run("opt -fast");
			if (retime || help_mode)
				run("abc -dff -D 1", "(only if -retime)");
		}

		if (check_label("map_ffs"))
		{
			run("dfflegalize -cell $_DFFE_PN?P_ x -cell $_SDFFCE_PN?P_ x -cell $_DLATCH_PN?_ x");
			run("techmap -D NO_LUT -map +/sf2/cells_map.v");
			run("opt_expr -mux_undef");
			run("simplemap");
			// run("sf2_ffinit");
			// run("sf2_ffssr");
			// run("sf2_opt -full");
		}

		if (check_label("map_luts"))
		{
			run("abc -lut 4");
			run("clean");
		}

		if (check_label("map_cells"))
		{
			run("techmap -map +/sf2/cells_map.v");
			run("clean");
		}

		if (check_label("map_iobs"))
		{
			if (help_mode || iobs) {
				if (help_mode) {
					run("clkbufmap -buf CLKINT Y:A [-inpad CLKBUF Y:PAD]", "(unless -noiobs, -inpad only passed if -clkbuf)");
				} else if (clkbuf) {
					run("clkbufmap -buf CLKINT Y:A -inpad CLKBUF Y:PAD");
				} else {
					run("clkbufmap -buf CLKINT Y:A");
				}
				run("iopadmap -bits -inpad INBUF Y:PAD -outpad OUTBUF D:PAD -toutpad TRIBUFF E:D:PAD -tinoutpad BIBUF E:Y:D:PAD", "(unless -noiobs");
			}
			run("clean");
		}

		if (check_label("check"))
		{
			run("hierarchy -check");
			run("stat");
			run("check -noinit");
			run("blackbox =A:whitebox");
		}

		if (check_label("edif"))
		{
			if (!edif_file.empty() || help_mode)
				run(stringf("write_edif -gndvccy %s", help_mode ? "<file-name>" : edif_file.c_str()));
		}

		if (check_label("vlog"))
		{
			if (!vlog_file.empty() || help_mode)
				run(stringf("write_verilog %s", help_mode ? "<file-name>" : vlog_file.c_str()));
		}

		if (check_label("json"))
		{
			if (!json_file.empty() || help_mode)
				run(stringf("write_json %s", help_mode ? "<file-name>" : json_file.c_str()));
		}
	}
} SynthSf2Pass;

PRIVATE_NAMESPACE_END
<commit_msg>synth_sf2: add -discard-ffinit option to discard ff initial value<commit_after>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Claire Xenia Wolf <claire@yosyshq.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct SynthSf2Pass : public ScriptPass
{
	SynthSf2Pass() : ScriptPass("synth_sf2", "synthesis for SmartFusion2 and IGLOO2 FPGAs") { }

	void help() override
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    synth_sf2 [options]\n");
		log("\n");
		log("This command runs synthesis for SmartFusion2 and IGLOO2 FPGAs.\n");
		log("\n");
		log("    -top <module>\n");
		log("        use the specified module as top module\n");
		log("\n");
		log("    -edif <file>\n");
		log("        write the design to the specified EDIF file. writing of an output file\n");
		log("        is omitted if this parameter is not specified.\n");
		log("\n");
		log("    -vlog <file>\n");
		log("        write the design to the specified Verilog file. writing of an output\n");
		log("        file is omitted if this parameter is not specified.\n");
		log("\n");
		log("    -json <file>\n");
		log("        write the design to the specified JSON file. writing of an output file\n");
		log("        is omitted if this parameter is not specified.\n");
		log("\n");
		log("    -run <from_label>:<to_label>\n");
		log("        only run the commands between the labels (see below). an empty\n");
		log("        from label is synonymous to 'begin', and empty to label is\n");
		log("        synonymous to the end of the command list.\n");
		log("\n");
		log("    -noflatten\n");
		log("        do not flatten design before synthesis\n");
		log("\n");
		log("    -noiobs\n");
		log("        run synthesis in \"block mode\", i.e. do not insert IO buffers\n");
		log("\n");
		log("    -clkbuf\n");
		log("        insert direct PAD->global_net buffers\n");
		log("\n");
		log("    -discard-ffinit\n");
		log("        discard FF init value instead of emitting an error\n");
		log("\n");
		log("    -retime\n");
		log("        run 'abc' with '-dff -D 1' options\n");
		log("\n");
		log("\n");
		log("The following commands are executed by this synthesis command:\n");
		help_script();
		log("\n");
	}

	string top_opt, edif_file, vlog_file, json_file;
	bool flatten, retime, iobs, clkbuf, discard_ffinit;

	void clear_flags() override
	{
		top_opt = "-auto-top";
		edif_file = "";
		vlog_file = "";
		json_file = "";
		flatten = true;
		retime = false;
		iobs = true;
		clkbuf = false;
		discard_ffinit = false;
	}

	void execute(std::vector<std::string> args, RTLIL::Design *design) override
	{
		string run_from, run_to;
		clear_flags();

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			if (args[argidx] == "-top" && argidx+1 < args.size()) {
				top_opt = "-top " + args[++argidx];
				continue;
			}
			if (args[argidx] == "-edif" && argidx+1 < args.size()) {
				edif_file = args[++argidx];
				continue;
			}
			if (args[argidx] == "-vlog" && argidx+1 < args.size()) {
				vlog_file = args[++argidx];
				continue;
			}
			if (args[argidx] == "-json" && argidx+1 < args.size()) {
				json_file = args[++argidx];
				continue;
			}
			if (args[argidx] == "-run" && argidx+1 < args.size()) {
				size_t pos = args[argidx+1].find(':');
				if (pos == std::string::npos)
					break;
				run_from = args[++argidx].substr(0, pos);
				run_to = args[argidx].substr(pos+1);
				continue;
			}
			if (args[argidx] == "-noflatten") {
				flatten = false;
				continue;
			}
			if (args[argidx] == "-retime") {
				retime = true;
				continue;
			}
			if (args[argidx] == "-noiobs") {
				iobs = false;
				continue;
			}
			if (args[argidx] == "-clkbuf") {
				clkbuf = true;
				continue;
			}
			if (args[argidx] == "-discard-ffinit") {
				discard_ffinit = true;
				continue;
			}
			break;
		}
		extra_args(args, argidx, design);

		if (!design->full_selection())
			log_cmd_error("This command only operates on fully selected designs!\n");

		log_header(design, "Executing SYNTH_SF2 pass.\n");
		log_push();

		run_script(design, run_from, run_to);

		log_pop();
	}

	void script() override
	{
		if (check_label("begin"))
		{
			run("read_verilog -lib +/sf2/cells_sim.v");
			run(stringf("hierarchy -check %s", help_mode ? "-top <top>" : top_opt.c_str()));
		}

		if (flatten && check_label("flatten", "(unless -noflatten)"))
		{
			run("proc");
			run("flatten");
			run("tribuf -logic");
			run("deminout");
		}

		if (check_label("coarse"))
		{
			if (discard_ffinit || help_mode)
				run("attrmap -remove init", "(only if -discard-ffinit)");
			run("synth -run coarse");
		}

		if (check_label("fine"))
		{
			run("opt -fast -mux_undef -undriven -fine");
			run("memory_map");
			run("opt -undriven -fine");
			run("techmap -map +/techmap.v -map +/sf2/arith_map.v");
			run("opt -fast");
			if (retime || help_mode)
				run("abc -dff -D 1", "(only if -retime)");
		}

		if (check_label("map_ffs"))
		{
			run("dfflegalize -cell $_DFFE_PN?P_ x -cell $_SDFFCE_PN?P_ x -cell $_DLATCH_PN?_ x");
			run("techmap -D NO_LUT -map +/sf2/cells_map.v");
			run("opt_expr -mux_undef");
			run("simplemap");
			// run("sf2_ffinit");
			// run("sf2_ffssr");
			// run("sf2_opt -full");
		}

		if (check_label("map_luts"))
		{
			run("abc -lut 4");
			run("clean");
		}

		if (check_label("map_cells"))
		{
			run("techmap -map +/sf2/cells_map.v");
			run("clean");
		}

		if (check_label("map_iobs"))
		{
			if (help_mode || iobs) {
				if (help_mode) {
					run("clkbufmap -buf CLKINT Y:A [-inpad CLKBUF Y:PAD]", "(unless -noiobs, -inpad only passed if -clkbuf)");
				} else if (clkbuf) {
					run("clkbufmap -buf CLKINT Y:A -inpad CLKBUF Y:PAD");
				} else {
					run("clkbufmap -buf CLKINT Y:A");
				}
				run("iopadmap -bits -inpad INBUF Y:PAD -outpad OUTBUF D:PAD -toutpad TRIBUFF E:D:PAD -tinoutpad BIBUF E:Y:D:PAD", "(unless -noiobs");
			}
			run("clean");
		}

		if (check_label("check"))
		{
			run("hierarchy -check");
			run("stat");
			run("check -noinit");
			run("blackbox =A:whitebox");
		}

		if (check_label("edif"))
		{
			if (!edif_file.empty() || help_mode)
				run(stringf("write_edif -gndvccy %s", help_mode ? "<file-name>" : edif_file.c_str()));
		}

		if (check_label("vlog"))
		{
			if (!vlog_file.empty() || help_mode)
				run(stringf("write_verilog %s", help_mode ? "<file-name>" : vlog_file.c_str()));
		}

		if (check_label("json"))
		{
			if (!json_file.empty() || help_mode)
				run(stringf("write_json %s", help_mode ? "<file-name>" : json_file.c_str()));
		}
	}
} SynthSf2Pass;

PRIVATE_NAMESPACE_END
<|endoftext|>


<commit_before>//
//  sound_player.cc
//  SoundEngine
//
//  Created by Jon Sharkey on 2013-03-21.
//  Copyright 2013 Sharkable. All rights reserved.
//

#include "soundengine/sound_player.h"

// TODO this is now tied to gameengine.
#include "gameengine/android/modules/asset_reader_android.h"

using std::string;

static SoundPlayerImpl *soundInstance_ = NULL;

SoundPlayer *SoundPlayer::instance() {
  if (soundInstance_ == NULL) {
    soundInstance_ = new SoundPlayerImpl();
  }
  return soundInstance_;
}

SoundPlayer *SoundPlayer::shutdown() {
  delete soundInstance_;
}

SoundPlayerImpl::SoundPlayerImpl()
    : engine_object_(NULL),
      engine_engine_(NULL),
      output_mix_object_(NULL) {
}

SoundPlayerImpl::~SoundPlayerImpl() {
  for (auto i = sounds_.begin(); i != sounds_.end(); i++) {
    delete i->second;
  }
  (*output_mix_object_)->Destroy(output_mix_object_);
  (*engine_object_)->Destroy(engine_object_);
}

//AVAudioSession *SoundPlayerImpl::session() {
//  return session_;
//}

bool SoundPlayerImpl::isMusicPlayingInITunes() {
  return false;
}

// allow sound effects to be clear by ducking the iTunes song
void SoundPlayerImpl::duckAudioFromITunes(bool duck) {
}

void SoundPlayerImpl::initialize() {
  SLresult result;

  const SLuint32 engineMixIIDCount = 1;
  const SLInterfaceID engineMixIIDs[] = {SL_IID_ENGINE};
  const SLboolean engineMixReqs[] = {SL_BOOLEAN_TRUE};

  // create engine
  result = slCreateEngine(&engine_object_, 0, NULL, engineMixIIDCount, engineMixIIDs,
                          engineMixReqs);
  assert(SL_RESULT_SUCCESS == result);

  // realize the engine
  result = (*engine_object_)->Realize(engine_object_, SL_BOOLEAN_FALSE);
  assert(SL_RESULT_SUCCESS == result);

  // get the engine interface, which is needed in order to create other objects
  result = (*engine_object_)->GetInterface(engine_object_, SL_IID_ENGINE, &engine_engine_);
  assert(SL_RESULT_SUCCESS == result);

  // create output mix
  result = (*engine_engine_)->CreateOutputMix(engine_engine_, &output_mix_object_, 0, NULL, NULL);
  assert(SL_RESULT_SUCCESS == result);

  // realize the output mix
  result = (*output_mix_object_)->Realize(output_mix_object_, SL_BOOLEAN_FALSE);
  assert(SL_RESULT_SUCCESS == result);

  // configure audio sink
  loc_outmix_ = {SL_DATALOCATOR_OUTPUTMIX, output_mix_object_};
  audio_sink_ = {&loc_outmix_, NULL};

  sounds_[kSoundScore] = (new SoundType())->Init(asset_manager_, engine_engine_, audio_sink_,
                                                 "sounds/score.wav");
  sounds_[kSoundScoreFinal] = (new SoundType())->Init(asset_manager_, engine_engine_, audio_sink_,
                                                      "sounds/score_final.wav");
  sounds_[kSoundPaddleHit] = (new SoundType())->Init(asset_manager_, engine_engine_, audio_sink_,
                                                     "sounds/paddle_hit.wav");
  sounds_[kSoundPuckRinkBounce] =
      (new SoundType())->Init(asset_manager_, engine_engine_, audio_sink_, "sounds/puck_rink_bounce.wav");
  sounds_[kSoundTwoPuckHit] =
      (new SoundType())->Init(asset_manager_, engine_engine_, audio_sink_, "sounds/puck_puck_hit.wav");
  sounds_[kSoundButton] =
      (new SoundType())->Init(asset_manager_, engine_engine_, audio_sink_, "sounds/beep.wav");
  sounds_[kSoundMultiSelect] =
      (new SoundType())->Init(asset_manager_, engine_engine_, audio_sink_, "sounds/button_click.wav");
  sounds_[kSoundGetReady] =
      (new SoundType())->Init(asset_manager_, engine_engine_, audio_sink_, "sounds/get_ready.wav");
  sounds_[kSoundStart] =
      (new SoundType())->Init(asset_manager_, engine_engine_, audio_sink_, "sounds/start.wav");

  sound_volumes_[kSoundScore]  = 1;
  sound_volumes_[kSoundScoreFinal]  = 1;
  sound_volumes_[kSoundPaddleHit]  = 1;
  sound_volumes_[kSoundPuckRinkBounce]  = 1;
  sound_volumes_[kSoundTwoPuckHit]  = 1;
  sound_volumes_[kSoundButton]  = 1;
  sound_volumes_[kSoundMultiSelect]  = 1;
  sound_volumes_[kSoundGetReady]  = 1;
  sound_volumes_[kSoundStart]  = 1;
}

bool SoundPlayerImpl::setGlobalVolume(float volume) {
  global_volume_ = volume;
}

bool SoundPlayerImpl::setVolume(Sound sound, float volume) {
  sound_volumes_[sound] = volume;
}

bool SoundPlayerImpl::setPosition(Sound sound, float position) {
  sound_positions_[sound] = position;
}

bool SoundPlayerImpl::playSound(Sound sound) {
  sounds_[sound]->Play(global_volume_ * sound_volumes_[sound], sound_positions_[sound]);
}

bool SoundPlayerImpl::stopSound(Sound sound) {
}

void SoundPlayerImpl::playSong(string filename) {
}

void SoundPlayerImpl::stopSong() {
}

void SoundPlayerImpl::setMusicOn(bool on) {
}

void SoundPlayerImpl::setSoundEffectsOn(bool on) {
}

void SoundPlayerImpl::syncAudioSessionForITunes() {
}
<commit_msg>[Android] [SoundEngine] soundInstance_ must be made NULL or it's value is the same next time the app is loaded :o<commit_after>//
//  sound_player.cc
//  SoundEngine
//
//  Created by Jon Sharkey on 2013-03-21.
//  Copyright 2013 Sharkable. All rights reserved.
//

#include "soundengine/sound_player.h"

// TODO this is now tied to gameengine.
#include "gameengine/android/modules/asset_reader_android.h"

using std::string;

static SoundPlayerImpl *soundInstance_ = NULL;

SoundPlayer *SoundPlayer::instance() {
  if (soundInstance_ == NULL) {
    soundInstance_ = new SoundPlayerImpl();
  }
  return soundInstance_;
}

SoundPlayer *SoundPlayer::shutdown() {
  delete soundInstance_;
  soundInstance_ = NULL;
}

SoundPlayerImpl::SoundPlayerImpl()
    : engine_object_(NULL),
      engine_engine_(NULL),
      output_mix_object_(NULL) {
}

SoundPlayerImpl::~SoundPlayerImpl() {
  for (auto i = sounds_.begin(); i != sounds_.end(); i++) {
    delete i->second;
  }
  (*output_mix_object_)->Destroy(output_mix_object_);
  (*engine_object_)->Destroy(engine_object_);
}

//AVAudioSession *SoundPlayerImpl::session() {
//  return session_;
//}

bool SoundPlayerImpl::isMusicPlayingInITunes() {
  return false;
}

// allow sound effects to be clear by ducking the iTunes song
void SoundPlayerImpl::duckAudioFromITunes(bool duck) {
}

void SoundPlayerImpl::initialize() {
  SLresult result;

  const SLuint32 engineMixIIDCount = 1;
  const SLInterfaceID engineMixIIDs[] = {SL_IID_ENGINE};
  const SLboolean engineMixReqs[] = {SL_BOOLEAN_TRUE};

  // create engine
  result = slCreateEngine(&engine_object_, 0, NULL, engineMixIIDCount, engineMixIIDs,
                          engineMixReqs);
  assert(SL_RESULT_SUCCESS == result);

  // realize the engine
  result = (*engine_object_)->Realize(engine_object_, SL_BOOLEAN_FALSE);
  assert(SL_RESULT_SUCCESS == result);

  // get the engine interface, which is needed in order to create other objects
  result = (*engine_object_)->GetInterface(engine_object_, SL_IID_ENGINE, &engine_engine_);
  assert(SL_RESULT_SUCCESS == result);

  // create output mix
  result = (*engine_engine_)->CreateOutputMix(engine_engine_, &output_mix_object_, 0, NULL, NULL);
  assert(SL_RESULT_SUCCESS == result);

  // realize the output mix
  result = (*output_mix_object_)->Realize(output_mix_object_, SL_BOOLEAN_FALSE);
  assert(SL_RESULT_SUCCESS == result);

  // configure audio sink
  loc_outmix_ = {SL_DATALOCATOR_OUTPUTMIX, output_mix_object_};
  audio_sink_ = {&loc_outmix_, NULL};

  sounds_[kSoundScore] = (new SoundType())->Init(asset_manager_, engine_engine_, audio_sink_,
                                                 "sounds/score.wav");
  sounds_[kSoundScoreFinal] = (new SoundType())->Init(asset_manager_, engine_engine_, audio_sink_,
                                                      "sounds/score_final.wav");
  sounds_[kSoundPaddleHit] = (new SoundType())->Init(asset_manager_, engine_engine_, audio_sink_,
                                                     "sounds/paddle_hit.wav");
  sounds_[kSoundPuckRinkBounce] =
      (new SoundType())->Init(asset_manager_, engine_engine_, audio_sink_, "sounds/puck_rink_bounce.wav");
  sounds_[kSoundTwoPuckHit] =
      (new SoundType())->Init(asset_manager_, engine_engine_, audio_sink_, "sounds/puck_puck_hit.wav");
  sounds_[kSoundButton] =
      (new SoundType())->Init(asset_manager_, engine_engine_, audio_sink_, "sounds/beep.wav");
  sounds_[kSoundMultiSelect] =
      (new SoundType())->Init(asset_manager_, engine_engine_, audio_sink_, "sounds/button_click.wav");
  sounds_[kSoundGetReady] =
      (new SoundType())->Init(asset_manager_, engine_engine_, audio_sink_, "sounds/get_ready.wav");
  sounds_[kSoundStart] =
      (new SoundType())->Init(asset_manager_, engine_engine_, audio_sink_, "sounds/start.wav");

  sound_volumes_[kSoundScore]  = 1;
  sound_volumes_[kSoundScoreFinal]  = 1;
  sound_volumes_[kSoundPaddleHit]  = 1;
  sound_volumes_[kSoundPuckRinkBounce]  = 1;
  sound_volumes_[kSoundTwoPuckHit]  = 1;
  sound_volumes_[kSoundButton]  = 1;
  sound_volumes_[kSoundMultiSelect]  = 1;
  sound_volumes_[kSoundGetReady]  = 1;
  sound_volumes_[kSoundStart]  = 1;
}

bool SoundPlayerImpl::setGlobalVolume(float volume) {
  global_volume_ = volume;
}

bool SoundPlayerImpl::setVolume(Sound sound, float volume) {
  sound_volumes_[sound] = volume;
}

bool SoundPlayerImpl::setPosition(Sound sound, float position) {
  sound_positions_[sound] = position;
}

bool SoundPlayerImpl::playSound(Sound sound) {
  sounds_[sound]->Play(global_volume_ * sound_volumes_[sound], sound_positions_[sound]);
}

bool SoundPlayerImpl::stopSound(Sound sound) {
}

void SoundPlayerImpl::playSong(string filename) {
}

void SoundPlayerImpl::stopSong() {
}

void SoundPlayerImpl::setMusicOn(bool on) {
}

void SoundPlayerImpl::setSoundEffectsOn(bool on) {
}

void SoundPlayerImpl::syncAudioSessionForITunes() {
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <string>

#include "Options.hpp"
#include "Compiler.hpp"
#include "Utils.hpp"
#include "Platform.hpp"

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE EddicTestSuites
#include <boost/test/unit_test.hpp>

#define TEST_SAMPLE(file)\
BOOST_AUTO_TEST_CASE( samples_##file ){\
    assertCompiles("samples/" #file ".eddi", "--32");\
    assertCompiles("samples/" #file ".eddi", "--64");\
}

#define ASSERT_OUTPUT(file, output)\
    assertOutputEquals(file, output, "--32");\
    assertOutputEquals(file, output, "--64");

#include <iostream>

void assertCompiles(const std::string& file, const std::string& param){
    const char* options[3] = {"./bin/test", param.c_str(), file.c_str()};
    BOOST_REQUIRE (eddic::parseOptions(3, options));

    eddic::Compiler compiler;

    eddic::Platform platform = eddic::Platform::INTEL_X86;
    int code = compiler.compileOnly(file, platform);

    BOOST_REQUIRE_EQUAL (code, 0);
}

void assertOutputEquals(const std::string& file, const std::string& output, const std::string& param){
    assertCompiles("test/cases/" + file, param);

    std::string out = eddic::execCommand("./a.out");

    BOOST_CHECK_EQUAL (output, out);
}

/* Compiles all the samples */

BOOST_AUTO_TEST_SUITE(SamplesSuite)

TEST_SAMPLE(arrays)
TEST_SAMPLE(asm)
TEST_SAMPLE(assembly)
TEST_SAMPLE(bool)
TEST_SAMPLE(compound)
TEST_SAMPLE(concat)
TEST_SAMPLE(const)
TEST_SAMPLE(functions)
TEST_SAMPLE(float)
TEST_SAMPLE(casts)
TEST_SAMPLE(inc)
TEST_SAMPLE(includes)
TEST_SAMPLE(optimize)
TEST_SAMPLE(problem)
TEST_SAMPLE(sort)
TEST_SAMPLE(identifiers)
TEST_SAMPLE(structures)

BOOST_AUTO_TEST_SUITE_END()

/* Specific tests */

BOOST_AUTO_TEST_SUITE(SpecificSuite)

BOOST_AUTO_TEST_CASE( if_ ){
    ASSERT_OUTPUT("if.eddi", "Cool");
}

BOOST_AUTO_TEST_CASE( while_ ){
    ASSERT_OUTPUT("while.eddi", "01234");
}

BOOST_AUTO_TEST_CASE( do_while_ ){
    ASSERT_OUTPUT("do_while.eddi", "01234");
}

BOOST_AUTO_TEST_CASE( for_ ){
    ASSERT_OUTPUT("for.eddi", "01234");
}

BOOST_AUTO_TEST_CASE( foreach_ ){
    ASSERT_OUTPUT("foreach.eddi", "012345");
}

BOOST_AUTO_TEST_CASE( globals_ ){
    assertOutputEquals("globals.eddi", "1000a2000aa", "-32");
    assertOutputEquals("globals.eddi", "1000a2000aa", "-64");
}

BOOST_AUTO_TEST_CASE( void_functions ){
    assertOutputEquals("void.eddi", "4445", "-32");
    assertOutputEquals("void.eddi", "4445", "-64");
}

BOOST_AUTO_TEST_CASE( string_functions ){
    assertOutputEquals("return_string.eddi", "abcdef", "-32");
    assertOutputEquals("return_string.eddi", "abcdef", "-64");
}

BOOST_AUTO_TEST_CASE( int_functions ){
    assertOutputEquals("return_int.eddi", "484", "-32");
    assertOutputEquals("return_int.eddi", "484", "-64");
}

BOOST_AUTO_TEST_CASE( recursive_functions ){
    assertOutputEquals("recursive.eddi", "362880", "-32");
    assertOutputEquals("recursive.eddi", "362880", "-64");
}

BOOST_AUTO_TEST_CASE( math ){
    assertOutputEquals("math.eddi", "333|111|-111|0|24642|2|-2|-1|1|2|0|-111|", "-32");
    assertOutputEquals("math.eddi", "333|111|-111|0|24642|2|-2|-1|1|2|0|-111|", "-64");
}

BOOST_AUTO_TEST_CASE( builtin ){
    assertOutputEquals("builtin.eddi", "10|11|12|13|12|13|10|11|4|8|13|8|0|3|", "-32");
    assertOutputEquals("builtin.eddi", "10|11|12|13|12|13|10|11|4|8|13|8|0|3|", "-64");
}

BOOST_AUTO_TEST_CASE( assign_value ){
    assertOutputEquals("assign_value.eddi", "66779921", "-32");
    assertOutputEquals("assign_value.eddi", "66779921", "-64");
}

BOOST_AUTO_TEST_CASE( args ){
    assertCompiles("test/cases/args.eddi", "-32");

    std::string out = eddic::execCommand("./a.out");
    BOOST_CHECK_EQUAL ("./a.out|", out);

    out = eddic::execCommand("./a.out arg1 arg2 arg3");
    BOOST_CHECK_EQUAL ("./a.out|arg1|arg2|arg3|", out);

    assertCompiles("test/cases/args.eddi", "-64");

    out = eddic::execCommand("./a.out");
    BOOST_CHECK_EQUAL ("./a.out|", out);

    out = eddic::execCommand("./a.out arg1 arg2 arg3");
    BOOST_CHECK_EQUAL ("./a.out|arg1|arg2|arg3|", out);
}

BOOST_AUTO_TEST_SUITE_END()

/* Unit test for bug fixes regression */

BOOST_AUTO_TEST_SUITE(BugFixesSuite)

BOOST_AUTO_TEST_CASE( while_bug ){
    assertOutputEquals("while_bug.eddi", "W1W2W3W4W5", "-32");
    assertOutputEquals("while_bug.eddi", "W1W2W3W4W5", "-64");
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Safe passing of parameters<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <string>

#include "Options.hpp"
#include "Compiler.hpp"
#include "Utils.hpp"
#include "Platform.hpp"

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE EddicTestSuites
#include <boost/test/unit_test.hpp>

#define TEST_SAMPLE(file)\
BOOST_AUTO_TEST_CASE( samples_##file ){\
    assertCompiles("samples/" #file ".eddi", "--32");\
    assertCompiles("samples/" #file ".eddi", "--64");\
}

#define ASSERT_OUTPUT(file, output)\
    assertOutputEquals(file, output, "--32");\
    assertOutputEquals(file, output, "--64");

#include <iostream>

void assertCompiles(const std::string& file, const std::string& param){
    const char* argv[3];
    argv[0] = "./bin/test";
    argv[1] = param.c_str();
    argv[2] = file.c_str();

    BOOST_REQUIRE (eddic::parseOptions(3, argv));

    eddic::Compiler compiler;

    eddic::Platform platform = eddic::Platform::INTEL_X86;
    int code = compiler.compileOnly(file, platform);

    BOOST_REQUIRE_EQUAL (code, 0);
}

void assertOutputEquals(const std::string& file, const std::string& output, const std::string& param){
    assertCompiles("test/cases/" + file, param);

    std::string out = eddic::execCommand("./a.out");

    BOOST_CHECK_EQUAL (output, out);
}

/* Compiles all the samples */

BOOST_AUTO_TEST_SUITE(SamplesSuite)

TEST_SAMPLE(arrays)
TEST_SAMPLE(asm)
TEST_SAMPLE(assembly)
TEST_SAMPLE(bool)
TEST_SAMPLE(compound)
TEST_SAMPLE(concat)
TEST_SAMPLE(const)
TEST_SAMPLE(functions)
TEST_SAMPLE(float)
TEST_SAMPLE(casts)
TEST_SAMPLE(inc)
TEST_SAMPLE(includes)
TEST_SAMPLE(optimize)
TEST_SAMPLE(problem)
TEST_SAMPLE(sort)
TEST_SAMPLE(identifiers)
TEST_SAMPLE(structures)

BOOST_AUTO_TEST_SUITE_END()

/* Specific tests */

BOOST_AUTO_TEST_SUITE(SpecificSuite)

BOOST_AUTO_TEST_CASE( if_ ){
    ASSERT_OUTPUT("if.eddi", "Cool");
}

BOOST_AUTO_TEST_CASE( while_ ){
    ASSERT_OUTPUT("while.eddi", "01234");
}

BOOST_AUTO_TEST_CASE( do_while_ ){
    ASSERT_OUTPUT("do_while.eddi", "01234");
}

BOOST_AUTO_TEST_CASE( for_ ){
    ASSERT_OUTPUT("for.eddi", "01234");
}

BOOST_AUTO_TEST_CASE( foreach_ ){
    ASSERT_OUTPUT("foreach.eddi", "012345");
}

BOOST_AUTO_TEST_CASE( globals_ ){
    assertOutputEquals("globals.eddi", "1000a2000aa", "-32");
    assertOutputEquals("globals.eddi", "1000a2000aa", "-64");
}

BOOST_AUTO_TEST_CASE( void_functions ){
    assertOutputEquals("void.eddi", "4445", "-32");
    assertOutputEquals("void.eddi", "4445", "-64");
}

BOOST_AUTO_TEST_CASE( string_functions ){
    assertOutputEquals("return_string.eddi", "abcdef", "-32");
    assertOutputEquals("return_string.eddi", "abcdef", "-64");
}

BOOST_AUTO_TEST_CASE( int_functions ){
    assertOutputEquals("return_int.eddi", "484", "-32");
    assertOutputEquals("return_int.eddi", "484", "-64");
}

BOOST_AUTO_TEST_CASE( recursive_functions ){
    assertOutputEquals("recursive.eddi", "362880", "-32");
    assertOutputEquals("recursive.eddi", "362880", "-64");
}

BOOST_AUTO_TEST_CASE( math ){
    assertOutputEquals("math.eddi", "333|111|-111|0|24642|2|-2|-1|1|2|0|-111|", "-32");
    assertOutputEquals("math.eddi", "333|111|-111|0|24642|2|-2|-1|1|2|0|-111|", "-64");
}

BOOST_AUTO_TEST_CASE( builtin ){
    assertOutputEquals("builtin.eddi", "10|11|12|13|12|13|10|11|4|8|13|8|0|3|", "-32");
    assertOutputEquals("builtin.eddi", "10|11|12|13|12|13|10|11|4|8|13|8|0|3|", "-64");
}

BOOST_AUTO_TEST_CASE( assign_value ){
    assertOutputEquals("assign_value.eddi", "66779921", "-32");
    assertOutputEquals("assign_value.eddi", "66779921", "-64");
}

BOOST_AUTO_TEST_CASE( args ){
    assertCompiles("test/cases/args.eddi", "-32");

    std::string out = eddic::execCommand("./a.out");
    BOOST_CHECK_EQUAL ("./a.out|", out);

    out = eddic::execCommand("./a.out arg1 arg2 arg3");
    BOOST_CHECK_EQUAL ("./a.out|arg1|arg2|arg3|", out);

    assertCompiles("test/cases/args.eddi", "-64");

    out = eddic::execCommand("./a.out");
    BOOST_CHECK_EQUAL ("./a.out|", out);

    out = eddic::execCommand("./a.out arg1 arg2 arg3");
    BOOST_CHECK_EQUAL ("./a.out|arg1|arg2|arg3|", out);
}

BOOST_AUTO_TEST_SUITE_END()

/* Unit test for bug fixes regression */

BOOST_AUTO_TEST_SUITE(BugFixesSuite)

BOOST_AUTO_TEST_CASE( while_bug ){
    assertOutputEquals("while_bug.eddi", "W1W2W3W4W5", "-32");
    assertOutputEquals("while_bug.eddi", "W1W2W3W4W5", "-64");
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>#include "ScriptLibrary.h"

#include <iostream>
#include <fstream>
#include <streambuf>
#include <string>

ScriptLibrary::ScriptLibrary()
{
}

ScriptLibrary* ScriptLibrary::instance;
ScriptLibrary* ScriptLibrary::getInstance()
{
    if(instance == NULL)
    {
        instance = new ScriptLibrary();
    }

    return instance;
}

ScriptLibrary::~ScriptLibrary()
{
}

std::string* ScriptLibrary::loadLua(std::string path)
{
    // Create a new file stream
    std::ifstream fileStream;

    // Open file with mode "input"
    fileStream.open(path.c_str(), std::ios::in);

    // Tell the file stream to go to the end
    fileStream.seekg(0, fileStream.end);
    int length = fileStream.tellg();
    fileStream.seekg(0, fileStream.beg);

    //
    char* buffer = new char[length];

    // Write everything from beginning to end to the string
    fileStream.read(buffer, length);

    // Close the file
    fileStream.close();

    std::cout << buffer;
}
<commit_msg>Removed unnecessary includes<commit_after>#include "ScriptLibrary.h"

#include <iostream>
#include <fstream>

ScriptLibrary::ScriptLibrary()
{
}

ScriptLibrary* ScriptLibrary::instance;
ScriptLibrary* ScriptLibrary::getInstance()
{
    if(instance == NULL)
    {
        instance = new ScriptLibrary();
    }

    return instance;
}

ScriptLibrary::~ScriptLibrary()
{
}

std::string* ScriptLibrary::loadLua(std::string path)
{
    // Create a new file stream
    std::ifstream fileStream;

    // Open file with mode "input"
    fileStream.open(path.c_str(), std::ios::in);

    // Tell the file stream to go to the end
    fileStream.seekg(0, fileStream.end);
    int length = fileStream.tellg();
    fileStream.seekg(0, fileStream.beg);

    //
    char* buffer = new char[length];

    // Write everything from beginning to end to the string
    fileStream.read(buffer, length);

    // Close the file
    fileStream.close();

    std::cout << buffer;
}
<|endoftext|>


<commit_before>#ifndef SENSOR_MEASUREMENTS_HPP_
#define SENSOR_MEASUREMENTS_HPP_

#include "sensors/accelerometer.hpp"
#include "sensors/gps.hpp"
#include "sensors/gyroscope.hpp"
#include "sensors/magnetometer.hpp"

struct SensorMeasurements {
  optional<AccelerometerReading> accel;
  optional<GyroscopeReading> gyro;
  optional<GPSReading> gps;
  optional<MagnetometerReading> mag;
};

#endif
<commit_msg>refs #7 Alphabetize sensor list.<commit_after>#ifndef SENSOR_MEASUREMENTS_HPP_
#define SENSOR_MEASUREMENTS_HPP_

#include "sensor/accelerometer.hpp"
#include "sensor/gps.hpp"
#include "sensor/gyroscope.hpp"
#include "sensor/magnetometer.hpp"

#include "util/optional.hpp"

struct SensorMeasurements {
  optional<AccelerometerReading> accel;
  optional<GPSReading> gps;
  optional<GyroscopeReading> gyro;
  optional<MagnetometerReading> mag;
};

#endif
<|endoftext|>