<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "formeditorgraphicsview.h"

#include <QWheelEvent>
#include <QApplication>
#include <QtDebug>

#include <qmlanchors.h>

namespace QmlDesigner {

FormEditorGraphicsView::FormEditorGraphicsView(QWidget *parent) :
    QGraphicsView(parent)
{
    setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
    setResizeAnchor(QGraphicsView::AnchorViewCenter);
    setAlignment(Qt::AlignCenter);
    setCacheMode(QGraphicsView::CacheNone);
    setViewportUpdateMode(QGraphicsView::MinimalViewportUpdate);
    setOptimizationFlags(QGraphicsView::DontSavePainterState);
//    setViewportUpdateMode(QGraphicsView::NoViewportUpdate);
    setRenderHint(QPainter::Antialiasing, false);

    setFrameShape(QFrame::NoFrame);

    setAutoFillBackground(true);
    setBackgroundRole(QPalette::Window);

    const int checkerbordSize= 20;
    QPixmap tilePixmap(checkerbordSize * 2, checkerbordSize * 2);
    tilePixmap.fill(Qt::white);
    QPainter tilePainter(&tilePixmap);
    QColor color(220, 220, 220);
    tilePainter.fillRect(0, 0, checkerbordSize, checkerbordSize, color);
    tilePainter.fillRect(checkerbordSize, checkerbordSize, checkerbordSize, checkerbordSize, color);
    tilePainter.end();

    setBackgroundBrush(tilePixmap);

    viewport()->setMouseTracking(true);
}

void FormEditorGraphicsView::wheelEvent(QWheelEvent *event)
{
    if (event->modifiers().testFlag(Qt::ControlModifier)) {
        event->ignore();
    } else {
        QGraphicsView::wheelEvent(event);
    }

}

void FormEditorGraphicsView::mouseMoveEvent(QMouseEvent *event)
{
    QGraphicsView::mouseMoveEvent(event);

//    if (rect().contains(event->pos())) {
//        QGraphicsView::mouseMoveEvent(event);
//    } else {
//        QPoint position = event->pos();
//        QPoint topLeft = rect().topLeft();
//        QPoint bottomRight = rect().bottomRight();
//        position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
//        position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
//        QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());

//        QGraphicsView::mouseMoveEvent(mouseEvent);
//        delete mouseEvent;
//    }

//    // Keeps the feedback bubble within screen boundraries
//    int tx = qMin(width() - 114,  qMax(16, event->pos().x() + 50));
//    int ty = qMin(height() - 45, qMax(10, event->pos().y() - 70));
//    m_feedbackOriginPoint = QPoint(tx, ty);
}

void FormEditorGraphicsView::keyPressEvent(QKeyEvent *event)
{
    m_feedbackOriginPoint = QPoint();
    QGraphicsView::keyPressEvent(event);
}

void FormEditorGraphicsView::setRootItemRect(const QRectF &rect)
{
    m_rootItemRect = rect;
    viewport()->update();
}

QRectF FormEditorGraphicsView::rootItemRect() const
{
    return m_rootItemRect;
}

void FormEditorGraphicsView::mousePressEvent(QMouseEvent *mouseEvent)
{
    QGraphicsView::mousePressEvent(mouseEvent);
}

void FormEditorGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
    QGraphicsView::mouseReleaseEvent(event);
//    if (rect().contains(event->pos())) {
//        QGraphicsView::mouseReleaseEvent(event);
//    } else {
//        QPoint position = event->pos();
//        QPoint topLeft = rect().topLeft();
//        QPoint bottomRight = rect().bottomRight();
//        position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
//        position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
//        QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());

//        QGraphicsView::mouseReleaseEvent(mouseEvent);
//        delete mouseEvent;
//    }

//    m_feedbackOriginPoint = QPoint();
}

void FormEditorGraphicsView::leaveEvent(QEvent *event)
{
     m_feedbackOriginPoint = QPoint();
     QGraphicsView::leaveEvent(event);
 }

static QPixmap createBubblePixmap()
{
    QPixmap pixmap(124, 48);
    pixmap.fill(Qt::transparent);
    QPainter pmPainter(&pixmap);
    pmPainter.setRenderHint(QPainter::Antialiasing);
    pmPainter.setOpacity(0.85);
    pmPainter.translate(0.5, 0.5);
    pmPainter.setPen(Qt::NoPen);
    pmPainter.setBrush(QColor(0, 0, 0, 40));
    pmPainter.drawRoundedRect(QRect(0, 0, 124, 48), 8, 8);
    QLinearGradient gradient(QPoint(0, 0), QPoint(0, 44));
    gradient.setColorAt(0.0, QColor(70, 70, 70));
    gradient.setColorAt(1.0, QColor(10, 10, 10));
    pmPainter.setBrush(gradient);
    pmPainter.setPen(QColor(60, 60, 60));
    pmPainter.drawRoundedRect(QRect(2, 1, 120, 45), 5, 5);
    pmPainter.setBrush(Qt::NoBrush);
    pmPainter.setPen(QColor(255, 255, 255, 140));
    pmPainter.drawRoundedRect(QRect(3, 2, 118, 43), 5, 5);
    pmPainter.end();
    return pixmap;
}

void FormEditorGraphicsView::drawForeground(QPainter *painter, const QRectF &/*rect*/ )
{
//    if (!m_feedbackNode.isValid())
//        return;

//    if (m_feedbackOriginPoint.isNull())
//        return;

//    painter->save();
//    painter->resetTransform();
//    painter->translate(m_feedbackOriginPoint);

//    QColor defaultColor(Qt::white);
//    QColor changeColor("#9999ff");

//    QFont font;
//    font.setFamily("Helvetica");
//    font.setPixelSize(12);
//    painter->setFont(font);

//    if (m_bubblePixmap.isNull())
//        m_bubblePixmap = createBubblePixmap();
//    painter->drawPixmap(-13, -7, m_bubblePixmap);

//    if (m_beginXHasExpression) {
//        if(m_feedbackNode.hasBindingProperty("x"))
//            painter->setPen(defaultColor);
//        else
//            painter->setPen(Qt::red);
//    } else {
//        if (m_beginX != m_feedbackNode.instanceValue("x"))
//            painter->setPen(changeColor);
//        else
//            painter->setPen(defaultColor);
//    }

//    painter->drawText(QPoint(8.0, 13.0), QString("x:"));
//    painter->drawText(QPoint(22.0, 13.0), m_feedbackNode.instanceValue("x").toString());

//    if (m_beginYHasExpression) {
//        if(m_feedbackNode.hasBindingProperty("y"))
//            painter->setPen(defaultColor);
//        else
//            painter->setPen(Qt::red);
//    } else {
//        if (m_beginY != m_feedbackNode.instanceValue("y"))
//            painter->setPen(changeColor);
//        else
//            painter->setPen(defaultColor);
//    }

//    painter->drawText(QPoint(60.0, 13.0), QString("y:"));
//    painter->drawText(QPoint(72.0, 13.0), m_feedbackNode.instanceValue("y").toString());

//    if (m_beginWidthHasExpression) {
//        if(m_feedbackNode.hasBindingProperty("width"))
//            painter->setPen(defaultColor);
//        else
//            painter->setPen(Qt::red);
//    } else {
//        if (m_beginWidth != m_feedbackNode.instanceValue("width"))
//            painter->setPen(changeColor);
//        else
//            painter->setPen(defaultColor);
//    }

//    painter->drawText(QPoint(8.0, 29.0), QString("w:"));
//    painter->drawText(QPoint(22.0, 29.0), m_feedbackNode.instanceValue("width").toString());

//    if (m_beginHeightHasExpression) {
//        if(m_feedbackNode.hasBindingProperty("height"))
//            painter->setPen(defaultColor);
//        else
//            painter->setPen(Qt::red);
//    } else {
//        if (m_beginHeight != m_feedbackNode.instanceValue("height"))
//            painter->setPen(changeColor);
//        else
//            painter->setPen(defaultColor);
//    }

//    painter->drawText(QPoint(60.0, 29.0), QString("h:"));
//    painter->drawText(QPoint(72.0, 29.0), m_feedbackNode.instanceValue("height").toString());

//    if (m_parentNode != m_feedbackNode.instanceParent()) {
//        painter->setPen(changeColor);
//        painter->drawText(QPoint(2.0, 39.0), QString("Parent changed"));

//    }

//    painter->restore();
}

void FormEditorGraphicsView::setFeedbackNode(const QmlItemNode &node)
{
//    if (node == m_feedbackNode)
//        return;

//    m_feedbackNode = node;

//    if (m_feedbackNode.isValid()) {
//        m_beginX = m_feedbackNode.instanceValue("x");
//        m_beginY = m_feedbackNode.instanceValue("y");
//        m_beginWidth = m_feedbackNode.instanceValue("width");
//        m_beginHeight = m_feedbackNode.instanceValue("height");
//        m_parentNode = m_feedbackNode.instanceParent();
//        m_beginLeftMargin = m_feedbackNode.instanceValue("anchors.leftMargin");
//        m_beginRightMargin = m_feedbackNode.instanceValue("anchors.rightMargin");
//        m_beginTopMargin = m_feedbackNode.instanceValue("anchors.topMargin");
//        m_beginBottomMargin = m_feedbackNode.instanceValue("anchors.bottomMargin");
//        m_beginXHasExpression = m_feedbackNode.hasBindingProperty("x");
//        m_beginYHasExpression = m_feedbackNode.hasBindingProperty("y");
//        m_beginWidthHasExpression = m_feedbackNode.hasBindingProperty("width");
//        m_beginHeightHasExpression = m_feedbackNode.hasBindingProperty("height");
//    } else {
//        m_beginX = QVariant();
//        m_beginY = QVariant();
//        m_beginWidth = QVariant();
//        m_beginHeight = QVariant();
//        m_parentNode = QmlObjectNode();
//        m_beginLeftMargin = QVariant();
//        m_beginRightMargin = QVariant();
//        m_beginTopMargin = QVariant();
//        m_beginBottomMargin = QVariant();
//        m_beginXHasExpression = false;
//        m_beginYHasExpression = false;
//        m_beginWidthHasExpression = false;
//        m_beginHeightHasExpression = false;
//    }
}

void FormEditorGraphicsView::drawBackground(QPainter *painter, const QRectF &rectangle)
{
    painter->save();
    painter->setBrushOrigin(0, 0);

    painter->fillRect(rectangle.intersected(rootItemRect()), backgroundBrush());
    // paint rect around editable area
    painter->setPen(Qt::black);
    painter->drawRect( rootItemRect());
    painter->restore();
}

} // namespace QmlDesigner
<commit_msg>fixes warnings<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "formeditorgraphicsview.h"

#include <QWheelEvent>
#include <QApplication>
#include <QtDebug>

#include <qmlanchors.h>

namespace QmlDesigner {

FormEditorGraphicsView::FormEditorGraphicsView(QWidget *parent) :
    QGraphicsView(parent)
{
    setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
    setResizeAnchor(QGraphicsView::AnchorViewCenter);
    setAlignment(Qt::AlignCenter);
    setCacheMode(QGraphicsView::CacheNone);
    setViewportUpdateMode(QGraphicsView::MinimalViewportUpdate);
    setOptimizationFlags(QGraphicsView::DontSavePainterState);
//    setViewportUpdateMode(QGraphicsView::NoViewportUpdate);
    setRenderHint(QPainter::Antialiasing, false);

    setFrameShape(QFrame::NoFrame);

    setAutoFillBackground(true);
    setBackgroundRole(QPalette::Window);

    const int checkerbordSize= 20;
    QPixmap tilePixmap(checkerbordSize * 2, checkerbordSize * 2);
    tilePixmap.fill(Qt::white);
    QPainter tilePainter(&tilePixmap);
    QColor color(220, 220, 220);
    tilePainter.fillRect(0, 0, checkerbordSize, checkerbordSize, color);
    tilePainter.fillRect(checkerbordSize, checkerbordSize, checkerbordSize, checkerbordSize, color);
    tilePainter.end();

    setBackgroundBrush(tilePixmap);

    viewport()->setMouseTracking(true);
}

void FormEditorGraphicsView::wheelEvent(QWheelEvent *event)
{
    if (event->modifiers().testFlag(Qt::ControlModifier)) {
        event->ignore();
    } else {
        QGraphicsView::wheelEvent(event);
    }

}

void FormEditorGraphicsView::mouseMoveEvent(QMouseEvent *event)
{
    QGraphicsView::mouseMoveEvent(event);

//    if (rect().contains(event->pos())) {
//        QGraphicsView::mouseMoveEvent(event);
//    } else {
//        QPoint position = event->pos();
//        QPoint topLeft = rect().topLeft();
//        QPoint bottomRight = rect().bottomRight();
//        position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
//        position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
//        QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());

//        QGraphicsView::mouseMoveEvent(mouseEvent);
//        delete mouseEvent;
//    }

//    // Keeps the feedback bubble within screen boundraries
//    int tx = qMin(width() - 114,  qMax(16, event->pos().x() + 50));
//    int ty = qMin(height() - 45, qMax(10, event->pos().y() - 70));
//    m_feedbackOriginPoint = QPoint(tx, ty);
}

void FormEditorGraphicsView::keyPressEvent(QKeyEvent *event)
{
    m_feedbackOriginPoint = QPoint();
    QGraphicsView::keyPressEvent(event);
}

void FormEditorGraphicsView::setRootItemRect(const QRectF &rect)
{
    m_rootItemRect = rect;
    viewport()->update();
}

QRectF FormEditorGraphicsView::rootItemRect() const
{
    return m_rootItemRect;
}

void FormEditorGraphicsView::mousePressEvent(QMouseEvent *mouseEvent)
{
    QGraphicsView::mousePressEvent(mouseEvent);
}

void FormEditorGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
    QGraphicsView::mouseReleaseEvent(event);
//    if (rect().contains(event->pos())) {
//        QGraphicsView::mouseReleaseEvent(event);
//    } else {
//        QPoint position = event->pos();
//        QPoint topLeft = rect().topLeft();
//        QPoint bottomRight = rect().bottomRight();
//        position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
//        position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
//        QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());

//        QGraphicsView::mouseReleaseEvent(mouseEvent);
//        delete mouseEvent;
//    }

//    m_feedbackOriginPoint = QPoint();
}

void FormEditorGraphicsView::leaveEvent(QEvent *event)
{
     m_feedbackOriginPoint = QPoint();
     QGraphicsView::leaveEvent(event);
 }

//static QPixmap createBubblePixmap()
//{
//    QPixmap pixmap(124, 48);
//    pixmap.fill(Qt::transparent);
//    QPainter pmPainter(&pixmap);
//    pmPainter.setRenderHint(QPainter::Antialiasing);
//    pmPainter.setOpacity(0.85);
//    pmPainter.translate(0.5, 0.5);
//    pmPainter.setPen(Qt::NoPen);
//    pmPainter.setBrush(QColor(0, 0, 0, 40));
//    pmPainter.drawRoundedRect(QRect(0, 0, 124, 48), 8, 8);
//    QLinearGradient gradient(QPoint(0, 0), QPoint(0, 44));
//    gradient.setColorAt(0.0, QColor(70, 70, 70));
//    gradient.setColorAt(1.0, QColor(10, 10, 10));
//    pmPainter.setBrush(gradient);
//    pmPainter.setPen(QColor(60, 60, 60));
//    pmPainter.drawRoundedRect(QRect(2, 1, 120, 45), 5, 5);
//    pmPainter.setBrush(Qt::NoBrush);
//    pmPainter.setPen(QColor(255, 255, 255, 140));
//    pmPainter.drawRoundedRect(QRect(3, 2, 118, 43), 5, 5);
//    pmPainter.end();
//    return pixmap;
//}

void FormEditorGraphicsView::drawForeground(QPainter * /*painter*/, const QRectF & /*rect*/ )
{
//    if (!m_feedbackNode.isValid())
//        return;

//    if (m_feedbackOriginPoint.isNull())
//        return;

//    painter->save();
//    painter->resetTransform();
//    painter->translate(m_feedbackOriginPoint);

//    QColor defaultColor(Qt::white);
//    QColor changeColor("#9999ff");

//    QFont font;
//    font.setFamily("Helvetica");
//    font.setPixelSize(12);
//    painter->setFont(font);

//    if (m_bubblePixmap.isNull())
//        m_bubblePixmap = createBubblePixmap();
//    painter->drawPixmap(-13, -7, m_bubblePixmap);

//    if (m_beginXHasExpression) {
//        if(m_feedbackNode.hasBindingProperty("x"))
//            painter->setPen(defaultColor);
//        else
//            painter->setPen(Qt::red);
//    } else {
//        if (m_beginX != m_feedbackNode.instanceValue("x"))
//            painter->setPen(changeColor);
//        else
//            painter->setPen(defaultColor);
//    }

//    painter->drawText(QPoint(8.0, 13.0), QString("x:"));
//    painter->drawText(QPoint(22.0, 13.0), m_feedbackNode.instanceValue("x").toString());

//    if (m_beginYHasExpression) {
//        if(m_feedbackNode.hasBindingProperty("y"))
//            painter->setPen(defaultColor);
//        else
//            painter->setPen(Qt::red);
//    } else {
//        if (m_beginY != m_feedbackNode.instanceValue("y"))
//            painter->setPen(changeColor);
//        else
//            painter->setPen(defaultColor);
//    }

//    painter->drawText(QPoint(60.0, 13.0), QString("y:"));
//    painter->drawText(QPoint(72.0, 13.0), m_feedbackNode.instanceValue("y").toString());

//    if (m_beginWidthHasExpression) {
//        if(m_feedbackNode.hasBindingProperty("width"))
//            painter->setPen(defaultColor);
//        else
//            painter->setPen(Qt::red);
//    } else {
//        if (m_beginWidth != m_feedbackNode.instanceValue("width"))
//            painter->setPen(changeColor);
//        else
//            painter->setPen(defaultColor);
//    }

//    painter->drawText(QPoint(8.0, 29.0), QString("w:"));
//    painter->drawText(QPoint(22.0, 29.0), m_feedbackNode.instanceValue("width").toString());

//    if (m_beginHeightHasExpression) {
//        if(m_feedbackNode.hasBindingProperty("height"))
//            painter->setPen(defaultColor);
//        else
//            painter->setPen(Qt::red);
//    } else {
//        if (m_beginHeight != m_feedbackNode.instanceValue("height"))
//            painter->setPen(changeColor);
//        else
//            painter->setPen(defaultColor);
//    }

//    painter->drawText(QPoint(60.0, 29.0), QString("h:"));
//    painter->drawText(QPoint(72.0, 29.0), m_feedbackNode.instanceValue("height").toString());

//    if (m_parentNode != m_feedbackNode.instanceParent()) {
//        painter->setPen(changeColor);
//        painter->drawText(QPoint(2.0, 39.0), QString("Parent changed"));

//    }

//    painter->restore();
}

void FormEditorGraphicsView::setFeedbackNode(const QmlItemNode & /*node*/)
{
//    if (node == m_feedbackNode)
//        return;

//    m_feedbackNode = node;

//    if (m_feedbackNode.isValid()) {
//        m_beginX = m_feedbackNode.instanceValue("x");
//        m_beginY = m_feedbackNode.instanceValue("y");
//        m_beginWidth = m_feedbackNode.instanceValue("width");
//        m_beginHeight = m_feedbackNode.instanceValue("height");
//        m_parentNode = m_feedbackNode.instanceParent();
//        m_beginLeftMargin = m_feedbackNode.instanceValue("anchors.leftMargin");
//        m_beginRightMargin = m_feedbackNode.instanceValue("anchors.rightMargin");
//        m_beginTopMargin = m_feedbackNode.instanceValue("anchors.topMargin");
//        m_beginBottomMargin = m_feedbackNode.instanceValue("anchors.bottomMargin");
//        m_beginXHasExpression = m_feedbackNode.hasBindingProperty("x");
//        m_beginYHasExpression = m_feedbackNode.hasBindingProperty("y");
//        m_beginWidthHasExpression = m_feedbackNode.hasBindingProperty("width");
//        m_beginHeightHasExpression = m_feedbackNode.hasBindingProperty("height");
//    } else {
//        m_beginX = QVariant();
//        m_beginY = QVariant();
//        m_beginWidth = QVariant();
//        m_beginHeight = QVariant();
//        m_parentNode = QmlObjectNode();
//        m_beginLeftMargin = QVariant();
//        m_beginRightMargin = QVariant();
//        m_beginTopMargin = QVariant();
//        m_beginBottomMargin = QVariant();
//        m_beginXHasExpression = false;
//        m_beginYHasExpression = false;
//        m_beginWidthHasExpression = false;
//        m_beginHeightHasExpression = false;
//    }
}

void FormEditorGraphicsView::drawBackground(QPainter *painter, const QRectF &rectangle)
{
    painter->save();
    painter->setBrushOrigin(0, 0);

    painter->fillRect(rectangle.intersected(rootItemRect()), backgroundBrush());
    // paint rect around editable area
    painter->setPen(Qt::black);
    painter->drawRect( rootItemRect());
    painter->restore();
}

} // namespace QmlDesigner
<|endoftext|>


<commit_before>// Copyright (c) 2005-2016 Gzp
// Distributed under MIT License.

#include "cmdctrl.h"

#include <QDebug>
#include <QGraphicsScene>
#include <QJsonObject>
#include <QJsonValue>

CommandReset::CommandReset()
    : SceneManager::Command( Type )
{
}

CommandReset* CommandReset::parse( const QJsonObject& aData )
{
    if( aData["command"].toString() != "reset" )
        return NULL;

    return new CommandReset();
}

void CommandReset::execute( SceneManager& aScene )
{
    aScene.reset();
}

CommandClear::CommandClear( QString aLayer )
    : SceneManager::Command( Type )
    , layer( aLayer )
{
}

CommandClear* CommandClear::parse( const QJsonObject& aData )
{
    if( aData["command"].toString() != "clear" )
        return NULL;

    QString layer = toLayer( aData["layer"], "*" );
    return new CommandClear( layer );
}

void CommandClear::execute( SceneManager& aScene )
{
    qDebug() << "clear command" << layer;
    if( layer == "*" )
        aScene.clear();
    else
        aScene.clear( layer );
}

CommandCache::CommandCache()
    : SceneManager::Command( Type )
{
}

CommandCache::CommandCache( int aId )
    : SceneManager::Command( Type )
    , id( aId )
{
}

CommandCache* CommandCache::parse( const QJsonObject& aData )
{
    if( aData["command"].toString() != "cache" )
        return NULL;

    bool ok = true;
    int id = toInt( aData["id"], &ok );
    if( !ok || id < 1 || id > 4 ) { qDebug() << "error in cache command, invalid id: " << aData["id"].toString(); return NULL; }

    return new CommandCache( id );
}

void CommandCache::execute( SceneManager& aScene )
{
    aScene.saveCache( id );
}
<commit_msg>remove some debug messages<commit_after>// Copyright (c) 2005-2016 Gzp
// Distributed under MIT License.

#include "cmdctrl.h"

#include <QDebug>
#include <QGraphicsScene>
#include <QJsonObject>
#include <QJsonValue>

CommandReset::CommandReset()
    : SceneManager::Command( Type )
{
}

CommandReset* CommandReset::parse( const QJsonObject& aData )
{
    if( aData["command"].toString() != "reset" )
        return NULL;

    return new CommandReset();
}

void CommandReset::execute( SceneManager& aScene )
{
    aScene.reset();
}

CommandClear::CommandClear( QString aLayer )
    : SceneManager::Command( Type )
    , layer( aLayer )
{
}

CommandClear* CommandClear::parse( const QJsonObject& aData )
{
    if( aData["command"].toString() != "clear" )
        return NULL;

    QString layer = toLayer( aData["layer"], "*" );
    return new CommandClear( layer );
}

void CommandClear::execute( SceneManager& aScene )
{
    if( layer == "*" )
        aScene.clear();
    else
        aScene.clear( layer );
}

CommandCache::CommandCache()
    : SceneManager::Command( Type )
{
}

CommandCache::CommandCache( int aId )
    : SceneManager::Command( Type )
    , id( aId )
{
}

CommandCache* CommandCache::parse( const QJsonObject& aData )
{
    if( aData["command"].toString() != "cache" )
        return NULL;

    bool ok = true;
    int id = toInt( aData["id"], &ok );
    if( !ok || id < 1 || id > 4 ) { qDebug() << "error in cache command, invalid id: " << aData["id"].toString(); return NULL; }

    return new CommandCache( id );
}

void CommandCache::execute( SceneManager& aScene )
{
    aScene.saveCache( id );
}
<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2017, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* 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.                                             */
/* -------------------------------------------------------------------------- */

#include "RequestManagerVirtualRouter.h"
#include "RequestManagerVMTemplate.h"
#include "RequestManagerVirtualMachine.h"
#include "PoolObjectAuth.h"
#include "Nebula.h"

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void VirtualRouterInstantiate::request_execute(
        xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
    int    vrid       = xmlrpc_c::value_int(paramList.getInt(1));
    int    n_vms      = xmlrpc_c::value_int(paramList.getInt(2));
    int    tmpl_id    = xmlrpc_c::value_int(paramList.getInt(3));
    string name       = xmlrpc_c::value_string(paramList.getString(4));
    bool   on_hold    = xmlrpc_c::value_boolean(paramList.getBoolean(5));
    string str_uattrs = xmlrpc_c::value_string(paramList.getString(6));

    Nebula& nd = Nebula::instance();

    VirtualRouterPool*  vrpool = nd.get_vrouterpool();
    VirtualRouter *     vr;
    DispatchManager*    dm = nd.get_dm();
    VMTemplatePool*     tpool = nd.get_tpool();

    PoolObjectAuth vr_perms;
    Template*      extra_attrs;
    string         error;
    string         vr_name, tmp_name;
    ostringstream  oss;

    vector<int>           vms;
    vector<int>::iterator vmid;

    int vid;

    /* ---------------------------------------------------------------------- */
    /* Get the Virtual Router NICs                                            */
    /* ---------------------------------------------------------------------- */
    vr = vrpool->get(vrid, true);

    if (vr == 0)
    {
        att.resp_id = vrid;
        failure_response(NO_EXISTS, att);
        return;
    }

    vr->get_permissions(vr_perms);

    extra_attrs = vr->get_vm_template();
    vr_name     = vr->get_name();

    if (tmpl_id == -1)
    {
        tmpl_id = vr->get_template_id();
    }

    vr->unlock();

    if (tmpl_id == -1)
    {
        att.resp_msg = "A template ID was not provided, and the virtual router "
                       "does not have a default one";
        failure_response(ACTION, att);
        return;
    }

    if ( att.uid != 0 )
    {
        AuthRequest ar(att.uid, att.group_ids);

        ar.add_auth(AuthRequest::MANAGE, vr_perms); // MANAGE VROUTER

        if (UserPool::authorize(ar) == -1)
        {
            att.resp_msg = ar.message;
            failure_response(AUTHORIZATION, att);
            return;
        }
    }

    VMTemplate * tmpl = tpool->get(tmpl_id,true);

    if ( tmpl == 0 )
    {
        att.resp_id = tmpl_id;
        att.resp_obj = PoolObjectSQL::TEMPLATE;
        failure_response(NO_EXISTS, att);
        return;
    }

    bool is_vrouter = tmpl->is_vrouter();

    tmpl->unlock();

    if (!is_vrouter)
    {
        att.resp_msg = "Only virtual router templates are allowed";
        failure_response(ACTION, att);
        return;
    }

    if (name.empty())
    {
        name = "vr-" + vr_name + "-%i";
    }

    VMTemplateInstantiate tmpl_instantiate;

    for (int i=0; i<n_vms; oss.str(""), i++)
    {
        oss << i;

        tmp_name = one_util::gsub(name, "%i", oss.str());

        ErrorCode ec = tmpl_instantiate.request_execute(tmpl_id, tmp_name,
                true, str_uattrs, extra_attrs, vid, att);

        if (ec != SUCCESS)
        {
            failure_response(ec, att);

            for (vmid = vms.begin(); vmid != vms.end(); vmid++)
            {
                dm->delete_vm(*vmid, att, att.resp_msg);
            }

            return;
        }

        vms.push_back(vid);
    }

    vr = vrpool->get(vrid, true);

    if (vr != 0)
    {
        for (vmid = vms.begin(); vmid != vms.end(); vmid++)
        {
            vr->add_vmid(*vmid);
        }

        vr->set_template_id(tmpl_id);

        vrpool->update(vr);

        vr->unlock();
    }

    // VMs are created on hold to wait for all of them to be created
    // successfully, to avoid the rollback dm->finalize call on prolog
    if (!on_hold)
    {
        for (vmid = vms.begin(); vmid != vms.end(); vmid++)
        {
            dm->release(*vmid, att, att.resp_msg);
        }
    }

    success_response(vrid, att);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void VirtualRouterAttachNic::request_execute(
        xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
    VirtualRouterPool*  vrpool = static_cast<VirtualRouterPool*>(pool);
    VirtualRouter *     vr;
    VectorAttribute*    nic;

    VirtualMachineTemplate  tmpl;
    PoolObjectAuth          vr_perms;

    int    rc;

    int    vrid     = xmlrpc_c::value_int(paramList.getInt(1));
    string str_tmpl = xmlrpc_c::value_string(paramList.getString(2));

    // -------------------------------------------------------------------------
    // Parse NIC template
    // -------------------------------------------------------------------------
    rc = tmpl.parse_str_or_xml(str_tmpl, att.resp_msg);

    if ( rc != 0 )
    {
        failure_response(INTERNAL, att);
        return;
    }

    // -------------------------------------------------------------------------
    // Authorize the operation & check quotas
    // -------------------------------------------------------------------------
    vr = vrpool->get(vrid, true);

    if (vr == 0)
    {
        att.resp_id = vrid;
        failure_response(NO_EXISTS, att);
        return;
    }

    vr->get_permissions(vr_perms);

    vr->unlock();

    if ( att.uid != 0 )
    {
        AuthRequest ar(att.uid, att.group_ids);

        ar.add_auth(AuthRequest::MANAGE, vr_perms); // MANAGE VROUTER

        VirtualRouter::set_auth_request(att.uid, ar, &tmpl); // USE VNET

        if (UserPool::authorize(ar) == -1)
        {
            att.resp_msg = ar.message;
            failure_response(AUTHORIZATION, att);
            return;
        }
    }

    RequestAttributes att_quota(vr_perms.uid, vr_perms.gid, att);

    if ( quota_authorization(&tmpl, Quotas::VIRTUALROUTER, att_quota) == false )
    {
        return;
    }

    // -------------------------------------------------------------------------
    // Attach NIC to the Virtual Router
    // -------------------------------------------------------------------------
    vr = vrpool->get(vrid, true);

    if (vr == 0)
    {
        quota_rollback(&tmpl, Quotas::VIRTUALROUTER, att_quota);

        att.resp_id = vrid;
        failure_response(NO_EXISTS, att);
        return;
    }

    nic = vr->attach_nic(&tmpl, att.resp_msg);

    set<int> vms = vr->get_vms();

    vrpool->update(vr);

    vr->unlock();

    if (nic == 0)
    {
        quota_rollback(&tmpl, Quotas::VIRTUALROUTER, att_quota);

        failure_response(ACTION, att);
        return;
    }

    // -------------------------------------------------------------------------
    // Attach NIC to each VM
    // -------------------------------------------------------------------------
    VirtualMachineAttachNic vm_attach_nic;

    for (set<int>::iterator vmid = vms.begin(); vmid != vms.end(); vmid++)
    {
        VirtualMachineTemplate tmpl;

        tmpl.set(nic->clone());

        ErrorCode ec = vm_attach_nic.request_execute(*vmid, tmpl, att);

        if (ec != SUCCESS) //TODO: manage individual attach error, do rollback?
        {
            failure_response(ACTION, att);

            delete nic;
            return;
        }
    }

    delete nic;

    success_response(vrid, att);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void VirtualRouterDetachNic::request_execute(
        xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
    VirtualRouterPool*  vrpool = static_cast<VirtualRouterPool*>(pool);
    VirtualRouter *     vr;
    PoolObjectAuth      vr_perms;

    int rc;

    int vrid    = xmlrpc_c::value_int(paramList.getInt(1));
    int nic_id  = xmlrpc_c::value_int(paramList.getInt(2));

    // -------------------------------------------------------------------------
    // Authorize the operation
    // -------------------------------------------------------------------------
    vr = vrpool->get(vrid, true);

    if (vr == 0)
    {
        att.resp_id = vrid;
        failure_response(NO_EXISTS, att);
        return;
    }

    vr->get_permissions(vr_perms);

    vr->unlock();

    if ( att.uid != 0 )
    {
        AuthRequest ar(att.uid, att.group_ids);

        ar.add_auth(AuthRequest::MANAGE, vr_perms); // MANAGE VROUTER

        if (UserPool::authorize(ar) == -1)
        {
            att.resp_msg = ar.message;
            failure_response(AUTHORIZATION, att);
            return;
        }
    }

    // -------------------------------------------------------------------------
    // Detach the NIC from the Virtual Router
    // -------------------------------------------------------------------------
    vr = vrpool->get(vrid, true);

    if (vr == 0)
    {
        att.resp_id = vrid;
        failure_response(NO_EXISTS, att);
        return;
    }

    rc = vr->detach_nic(nic_id);

    set<int> vms = vr->get_vms();

    vrpool->update(vr);

    vr->unlock();

    if (rc != 0)
    {
        ostringstream oss;

        oss << "NIC with NIC_ID " << nic_id << " does not exist.";

        att.resp_msg = oss.str();
        failure_response(Request::ACTION, att);

        return;
    }

    // -------------------------------------------------------------------------
    // Detach NIC from each VM
    // -------------------------------------------------------------------------
    VirtualMachineDetachNic vm_detach_nic;

    for (set<int>::iterator vmid = vms.begin(); vmid != vms.end(); vmid++)
    {
        ErrorCode ec = vm_detach_nic.request_execute(*vmid, nic_id, att);

        if (ec != SUCCESS) //TODO: manage individual attach error, do rollback?
        {
            failure_response(Request::ACTION, att);
            return;
        }
    }

    success_response(vrid, att);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

<commit_msg>B #1505: Removed delete nic (#1516)<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2017, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* 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.                                             */
/* -------------------------------------------------------------------------- */

#include "RequestManagerVirtualRouter.h"
#include "RequestManagerVMTemplate.h"
#include "RequestManagerVirtualMachine.h"
#include "PoolObjectAuth.h"
#include "Nebula.h"

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void VirtualRouterInstantiate::request_execute(
        xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
    int    vrid       = xmlrpc_c::value_int(paramList.getInt(1));
    int    n_vms      = xmlrpc_c::value_int(paramList.getInt(2));
    int    tmpl_id    = xmlrpc_c::value_int(paramList.getInt(3));
    string name       = xmlrpc_c::value_string(paramList.getString(4));
    bool   on_hold    = xmlrpc_c::value_boolean(paramList.getBoolean(5));
    string str_uattrs = xmlrpc_c::value_string(paramList.getString(6));

    Nebula& nd = Nebula::instance();

    VirtualRouterPool*  vrpool = nd.get_vrouterpool();
    VirtualRouter *     vr;
    DispatchManager*    dm = nd.get_dm();
    VMTemplatePool*     tpool = nd.get_tpool();

    PoolObjectAuth vr_perms;
    Template*      extra_attrs;
    string         error;
    string         vr_name, tmp_name;
    ostringstream  oss;

    vector<int>           vms;
    vector<int>::iterator vmid;

    int vid;

    /* ---------------------------------------------------------------------- */
    /* Get the Virtual Router NICs                                            */
    /* ---------------------------------------------------------------------- */
    vr = vrpool->get(vrid, true);

    if (vr == 0)
    {
        att.resp_id = vrid;
        failure_response(NO_EXISTS, att);
        return;
    }

    vr->get_permissions(vr_perms);

    extra_attrs = vr->get_vm_template();
    vr_name     = vr->get_name();

    if (tmpl_id == -1)
    {
        tmpl_id = vr->get_template_id();
    }

    vr->unlock();

    if (tmpl_id == -1)
    {
        att.resp_msg = "A template ID was not provided, and the virtual router "
                       "does not have a default one";
        failure_response(ACTION, att);
        return;
    }

    if ( att.uid != 0 )
    {
        AuthRequest ar(att.uid, att.group_ids);

        ar.add_auth(AuthRequest::MANAGE, vr_perms); // MANAGE VROUTER

        if (UserPool::authorize(ar) == -1)
        {
            att.resp_msg = ar.message;
            failure_response(AUTHORIZATION, att);
            return;
        }
    }

    VMTemplate * tmpl = tpool->get(tmpl_id,true);

    if ( tmpl == 0 )
    {
        att.resp_id = tmpl_id;
        att.resp_obj = PoolObjectSQL::TEMPLATE;
        failure_response(NO_EXISTS, att);
        return;
    }

    bool is_vrouter = tmpl->is_vrouter();

    tmpl->unlock();

    if (!is_vrouter)
    {
        att.resp_msg = "Only virtual router templates are allowed";
        failure_response(ACTION, att);
        return;
    }

    if (name.empty())
    {
        name = "vr-" + vr_name + "-%i";
    }

    VMTemplateInstantiate tmpl_instantiate;

    for (int i=0; i<n_vms; oss.str(""), i++)
    {
        oss << i;

        tmp_name = one_util::gsub(name, "%i", oss.str());

        ErrorCode ec = tmpl_instantiate.request_execute(tmpl_id, tmp_name,
                true, str_uattrs, extra_attrs, vid, att);

        if (ec != SUCCESS)
        {
            failure_response(ec, att);

            for (vmid = vms.begin(); vmid != vms.end(); vmid++)
            {
                dm->delete_vm(*vmid, att, att.resp_msg);
            }

            return;
        }

        vms.push_back(vid);
    }

    vr = vrpool->get(vrid, true);

    if (vr != 0)
    {
        for (vmid = vms.begin(); vmid != vms.end(); vmid++)
        {
            vr->add_vmid(*vmid);
        }

        vr->set_template_id(tmpl_id);

        vrpool->update(vr);

        vr->unlock();
    }

    // VMs are created on hold to wait for all of them to be created
    // successfully, to avoid the rollback dm->finalize call on prolog
    if (!on_hold)
    {
        for (vmid = vms.begin(); vmid != vms.end(); vmid++)
        {
            dm->release(*vmid, att, att.resp_msg);
        }
    }

    success_response(vrid, att);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void VirtualRouterAttachNic::request_execute(
        xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
    VirtualRouterPool*  vrpool = static_cast<VirtualRouterPool*>(pool);
    VirtualRouter *     vr;
    VectorAttribute*    nic;

    VirtualMachineTemplate  tmpl;
    PoolObjectAuth          vr_perms;

    int    rc;

    int    vrid     = xmlrpc_c::value_int(paramList.getInt(1));
    string str_tmpl = xmlrpc_c::value_string(paramList.getString(2));

    // -------------------------------------------------------------------------
    // Parse NIC template
    // -------------------------------------------------------------------------
    rc = tmpl.parse_str_or_xml(str_tmpl, att.resp_msg);

    if ( rc != 0 )
    {
        failure_response(INTERNAL, att);
        return;
    }

    // -------------------------------------------------------------------------
    // Authorize the operation & check quotas
    // -------------------------------------------------------------------------
    vr = vrpool->get(vrid, true);

    if (vr == 0)
    {
        att.resp_id = vrid;
        failure_response(NO_EXISTS, att);
        return;
    }

    vr->get_permissions(vr_perms);

    vr->unlock();

    if ( att.uid != 0 )
    {
        AuthRequest ar(att.uid, att.group_ids);

        ar.add_auth(AuthRequest::MANAGE, vr_perms); // MANAGE VROUTER

        VirtualRouter::set_auth_request(att.uid, ar, &tmpl); // USE VNET

        if (UserPool::authorize(ar) == -1)
        {
            att.resp_msg = ar.message;
            failure_response(AUTHORIZATION, att);
            return;
        }
    }

    RequestAttributes att_quota(vr_perms.uid, vr_perms.gid, att);

    if ( quota_authorization(&tmpl, Quotas::VIRTUALROUTER, att_quota) == false )
    {
        return;
    }

    // -------------------------------------------------------------------------
    // Attach NIC to the Virtual Router
    // -------------------------------------------------------------------------
    vr = vrpool->get(vrid, true);

    if (vr == 0)
    {
        quota_rollback(&tmpl, Quotas::VIRTUALROUTER, att_quota);

        att.resp_id = vrid;
        failure_response(NO_EXISTS, att);
        return;
    }

    nic = vr->attach_nic(&tmpl, att.resp_msg);

    set<int> vms = vr->get_vms();

    vrpool->update(vr);

    vr->unlock();

    if (nic == 0)
    {
        quota_rollback(&tmpl, Quotas::VIRTUALROUTER, att_quota);

        failure_response(ACTION, att);
        return;
    }

    // -------------------------------------------------------------------------
    // Attach NIC to each VM
    // -------------------------------------------------------------------------
    VirtualMachineAttachNic vm_attach_nic;

    for (set<int>::iterator vmid = vms.begin(); vmid != vms.end(); vmid++)
    {
        VirtualMachineTemplate tmpl;

        tmpl.set(nic->clone());

        ErrorCode ec = vm_attach_nic.request_execute(*vmid, tmpl, att);

        if (ec != SUCCESS) //TODO: manage individual attach error, do rollback?
        {
            failure_response(ACTION, att);

            return;
        }
    }

    success_response(vrid, att);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void VirtualRouterDetachNic::request_execute(
        xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
    VirtualRouterPool*  vrpool = static_cast<VirtualRouterPool*>(pool);
    VirtualRouter *     vr;
    PoolObjectAuth      vr_perms;

    int rc;

    int vrid    = xmlrpc_c::value_int(paramList.getInt(1));
    int nic_id  = xmlrpc_c::value_int(paramList.getInt(2));

    // -------------------------------------------------------------------------
    // Authorize the operation
    // -------------------------------------------------------------------------
    vr = vrpool->get(vrid, true);

    if (vr == 0)
    {
        att.resp_id = vrid;
        failure_response(NO_EXISTS, att);
        return;
    }

    vr->get_permissions(vr_perms);

    vr->unlock();

    if ( att.uid != 0 )
    {
        AuthRequest ar(att.uid, att.group_ids);

        ar.add_auth(AuthRequest::MANAGE, vr_perms); // MANAGE VROUTER

        if (UserPool::authorize(ar) == -1)
        {
            att.resp_msg = ar.message;
            failure_response(AUTHORIZATION, att);
            return;
        }
    }

    // -------------------------------------------------------------------------
    // Detach the NIC from the Virtual Router
    // -------------------------------------------------------------------------
    vr = vrpool->get(vrid, true);

    if (vr == 0)
    {
        att.resp_id = vrid;
        failure_response(NO_EXISTS, att);
        return;
    }

    rc = vr->detach_nic(nic_id);

    set<int> vms = vr->get_vms();

    vrpool->update(vr);

    vr->unlock();

    if (rc != 0)
    {
        ostringstream oss;

        oss << "NIC with NIC_ID " << nic_id << " does not exist.";

        att.resp_msg = oss.str();
        failure_response(Request::ACTION, att);

        return;
    }

    // -------------------------------------------------------------------------
    // Detach NIC from each VM
    // -------------------------------------------------------------------------
    VirtualMachineDetachNic vm_detach_nic;

    for (set<int>::iterator vmid = vms.begin(); vmid != vms.end(); vmid++)
    {
        ErrorCode ec = vm_detach_nic.request_execute(*vmid, nic_id, att);

        if (ec != SUCCESS) //TODO: manage individual attach error, do rollback?
        {
            failure_response(Request::ACTION, att);
            return;
        }
    }

    success_response(vrid, att);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

<|endoftext|>


<commit_before>#include "card.h"

#include <QDebug>

Card::Card()
{
}

void Card::setInfo(const pa_card_info *info)
{
    m_index = info->index;
    m_name = QString::fromUtf8(info->name);
    m_driver = QString::fromUtf8(info->driver);

    qDebug() << "processing card" << info->index << info->name;

    m_profiles.clear();
#warning more inconsistent api... profiels end with entry with name on null...
    for (auto *it = info->profiles; it->name != nullptr; ++it) {
        CardProfile profile;
        profile.setInfo(it);
        m_profiles.append(profile);
        if (info->active_profile == it) {
            qDebug() << "+++++++++++++++++ profile " << it->description << " appears the active one at index: "<< m_profiles.length() - 1;
            m_activeProfileIndex = m_profiles.length() - 1;
        }
    }

#warning there is no active port prop so it is possible that this is actually very worthless since we have sinks and sources
    m_ports.clear();
    for (auto **it = info->ports; *it != nullptr; ++it) {
        CardPort port;
        port.setInfo(*it);
        m_ports.append(port);
    }

    void *it = nullptr;
    while (const char *key = pa_proplist_iterate(info->proplist, &it)) {
        Q_ASSERT(key);
        const char *value = pa_proplist_gets(info->proplist, key);
        if (!value) {
            qDebug() << "property" << key << "not a string";
            continue;
        }
        Q_ASSERT(value);
        m_properties.insert(QString::fromUtf8(key), QString::fromUtf8(value));
    }
}
<commit_msg>prevent crash when a card has no ports<commit_after>#include "card.h"

#include <QDebug>

Card::Card()
{
}

void Card::setInfo(const pa_card_info *info)
{
    m_index = info->index;
    m_name = QString::fromUtf8(info->name);
    m_driver = QString::fromUtf8(info->driver);

    qDebug() << "processing card" << info->index << info->name;

    m_profiles.clear();
#warning more inconsistent api... profiels end with entry with name on null...
    for (auto *it = info->profiles; it->name != nullptr; ++it) {
        CardProfile profile;
        profile.setInfo(it);
        m_profiles.append(profile);
        if (info->active_profile == it) {
            qDebug() << "+++++++++++++++++ profile " << it->description << " appears the active one at index: "<< m_profiles.length() - 1;
            m_activeProfileIndex = m_profiles.length() - 1;
        }
    }

#warning there is no active port prop so it is possible that this is actually very worthless since we have sinks and sources
    m_ports.clear();
    for (auto **it = info->ports; it && *it != nullptr; ++it) {
        CardPort port;
        port.setInfo(*it);
        m_ports.append(port);
    }

    void *it = nullptr;
    while (const char *key = pa_proplist_iterate(info->proplist, &it)) {
        Q_ASSERT(key);
        const char *value = pa_proplist_gets(info->proplist, key);
        if (!value) {
            qDebug() << "property" << key << "not a string";
            continue;
        }
        Q_ASSERT(value);
        m_properties.insert(QString::fromUtf8(key), QString::fromUtf8(value));
    }
}
<|endoftext|>


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

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

#ifndef _NUMBERINGTYPELISTBOX_HXX
#include <numberingtypelistbox.hxx>
#endif
#ifndef _MISC_HRC
#include <misc.hrc>
#endif
#ifndef _CNTTAB_HXX
#include <cnttab.hxx>
#endif
#ifndef _COM_SUN_STAR_STYLE_NUMBERINGTYPE_HPP_
#include <com/sun/star/style/NumberingType.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XDEFAULTNUMBERINGPROVIDER_HPP_
#include <com/sun/star/text/XDefaultNumberingProvider.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_TEXT_XNUMBERINGTYPEINFO_HPP_
#include <com/sun/star/text/XNumberingTypeInfo.hpp>
#endif

//#ifndef _SVTOOLS_LANGUAGEOPTIONS_HXX
//#include <svtools/languageoptions.hxx>
//#endif

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

#define C2S(cChar) UniString::CreateFromAscii(cChar)
/* -----------------------------01.03.01 16:04--------------------------------

 ---------------------------------------------------------------------------*/
struct SwNumberingTypeListBox_Impl
{
    uno::Reference<text::XNumberingTypeInfo> xInfo;
};
/* -----------------------------01.03.01 14:46--------------------------------

 ---------------------------------------------------------------------------*/
SwNumberingTypeListBox::SwNumberingTypeListBox( Window* pWin, const ResId& rResId,
        USHORT nTypeFlags ) :
    ListBox(pWin, rResId),
    pImpl(new SwNumberingTypeListBox_Impl)
{
    uno::Reference< lang::XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();
    uno::Reference < uno::XInterface > xI = xMSF->createInstance(
        ::rtl::OUString::createFromAscii( "com.sun.star.text.DefaultNumberingProvider" ) );
    uno::Reference<text::XDefaultNumberingProvider> xDefNum(xI, uno::UNO_QUERY);
    DBG_ASSERT(xDefNum.is(), "service missing: \"com.sun.star.text.DefaultNumberingProvider\"")

    pImpl->xInfo = uno::Reference<text::XNumberingTypeInfo>(xDefNum, uno::UNO_QUERY);
    Reload(nTypeFlags);
}
/* -----------------------------01.03.01 14:46--------------------------------

 ---------------------------------------------------------------------------*/
SwNumberingTypeListBox::~SwNumberingTypeListBox()
{
    delete pImpl;
}
/* -----------------------------01.03.01 16:02--------------------------------

 ---------------------------------------------------------------------------*/
void SwNumberingTypeListBox::Reload(USHORT nTypeFlags)
{
    Clear();
    uno::Sequence<sal_Int16> aTypes;
    const sal_Int16* pTypes = NULL;
    if(0 != (nTypeFlags&INSERT_NUM_EXTENDED_TYPES) )
    {
        if(pImpl->xInfo.is())
        {
            aTypes = pImpl->xInfo->getSupportedNumberingTypes();
            pTypes = aTypes.getConstArray();
        }
    }
    SwOLENames aNames(SW_RES(STRRES_NUMTYPES));
    ResStringArray& rNames = aNames.GetNames();
    for(sal_uInt16 i = 0; i < rNames.Count(); i++)
    {
        long nValue = rNames.GetValue(i);
        sal_Bool bInsert = sal_True;
        USHORT nPos = LISTBOX_APPEND;
        switch(nValue)
        {
            case  style::NumberingType::NUMBER_NONE:
                bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_NO_NUMBERING);
                nPos = 0;
             break;
            case  style::NumberingType::CHAR_SPECIAL:   bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_BULLET); break;
            case  style::NumberingType::PAGE_DESCRIPTOR:bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_PAGE_STYLE_NUMBERING); break;
            case  style::NumberingType::BITMAP:bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_BITMAP ); break;
            default:
                if (nValue >  style::NumberingType::CHARS_LOWER_LETTER_N)
                {
                    // Insert only if offered by i18n framework per configuration.
                    bInsert = sal_False;
                    if (pTypes)
                    {
                        for(sal_Int32 nType = 0; nType < aTypes.getLength(); nType++)
                        {
                            if (pTypes[nType] == nValue)
                            {
                                bInsert = sal_True;
                                break;  // for
                            }
                        }
                    }
                }
        }
        if(bInsert)
        {
            USHORT nEntry = InsertEntry(rNames.GetString(i), nPos);
            SetEntryData( nEntry, (void*)nValue );
        }
    }
    if(0 != (nTypeFlags&INSERT_NUM_EXTENDED_TYPES) )
    {
        if(pTypes)
        {
            for(sal_Int32 nType = 0; nType < aTypes.getLength(); nType++)
            {
                sal_Int16 nCurrent = pTypes[nType];
                if(nCurrent > style::NumberingType::CHARS_LOWER_LETTER_N)
                {
                    if(LISTBOX_ENTRY_NOTFOUND == GetEntryPos((void*)(ULONG)nCurrent))
                    {
                        OUString aIdent = pImpl->xInfo->getNumberingIdentifier( nCurrent );
                        USHORT nPos = InsertEntry(aIdent);
                        SetEntryData(nPos,(void*)(ULONG)nCurrent);
                    }
                }
            }
        }
        SelectEntryPos(0);
    }
}
/* -----------------------------01.03.01 14:46--------------------------------

 ---------------------------------------------------------------------------*/
sal_Int16   SwNumberingTypeListBox::GetSelectedNumberingType()
{
    sal_Int16 nRet = 0;
    USHORT nSelPos = GetSelectEntryPos();
    if(LISTBOX_ENTRY_NOTFOUND != nSelPos)
        nRet = (sal_Int16)(ULONG)GetEntryData(nSelPos);
#ifdef DBG_UTIL
    else
        DBG_ERROR("SwNumberingTypeListBox not selected")
#endif
    return nRet;
}
/* -----------------------------01.03.01 14:46--------------------------------

 ---------------------------------------------------------------------------*/
sal_Bool    SwNumberingTypeListBox::SelectNumberingType(sal_Int16 nType)
{
    USHORT nPos = GetEntryPos((void*)(ULONG)nType);
    SelectEntryPos( nPos );
    return LISTBOX_ENTRY_NOTFOUND != nPos;
}

<commit_msg>INTEGRATION: CWS swwarnings (1.11.222); FILE MERGED 2007/06/28 11:59:23 os 1.11.222.3: RESYNC: (1.11-1.12); FILE MERGED 2007/06/01 07:17:44 tl 1.11.222.2: #i69287# warning-free code 2007/04/11 07:03:29 tl 1.11.222.1: #i69287# warning-free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: numberingtypelistbox.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 12:22:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef _NUMBERINGTYPELISTBOX_HXX
#include <numberingtypelistbox.hxx>
#endif
#ifndef _MISC_HRC
#include <misc.hrc>
#endif
#ifndef _CNTTAB_HXX
#include <cnttab.hxx>
#endif
#ifndef _COM_SUN_STAR_STYLE_NUMBERINGTYPE_HPP_
#include <com/sun/star/style/NumberingType.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XDEFAULTNUMBERINGPROVIDER_HPP_
#include <com/sun/star/text/XDefaultNumberingProvider.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_TEXT_XNUMBERINGTYPEINFO_HPP_
#include <com/sun/star/text/XNumberingTypeInfo.hpp>
#endif

#include <unomid.h>

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

/* -----------------------------01.03.01 16:04--------------------------------

 ---------------------------------------------------------------------------*/
struct SwNumberingTypeListBox_Impl
{
    uno::Reference<text::XNumberingTypeInfo> xInfo;
};
/* -----------------------------01.03.01 14:46--------------------------------

 ---------------------------------------------------------------------------*/
SwNumberingTypeListBox::SwNumberingTypeListBox( Window* pWin, const ResId& rResId,
        USHORT nTypeFlags ) :
    ListBox(pWin, rResId),
    pImpl(new SwNumberingTypeListBox_Impl)
{
    uno::Reference< lang::XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();
    uno::Reference < uno::XInterface > xI = xMSF->createInstance(
        ::rtl::OUString::createFromAscii( "com.sun.star.text.DefaultNumberingProvider" ) );
    uno::Reference<text::XDefaultNumberingProvider> xDefNum(xI, uno::UNO_QUERY);
    DBG_ASSERT(xDefNum.is(), "service missing: \"com.sun.star.text.DefaultNumberingProvider\"")

    pImpl->xInfo = uno::Reference<text::XNumberingTypeInfo>(xDefNum, uno::UNO_QUERY);
    Reload(nTypeFlags);
}
/* -----------------------------01.03.01 14:46--------------------------------

 ---------------------------------------------------------------------------*/
SwNumberingTypeListBox::~SwNumberingTypeListBox()
{
    delete pImpl;
}
/* -----------------------------01.03.01 16:02--------------------------------

 ---------------------------------------------------------------------------*/
void SwNumberingTypeListBox::Reload(USHORT nTypeFlags)
{
    Clear();
    uno::Sequence<sal_Int16> aTypes;
    const sal_Int16* pTypes = NULL;
    if(0 != (nTypeFlags&INSERT_NUM_EXTENDED_TYPES) )
    {
        if(pImpl->xInfo.is())
        {
            aTypes = pImpl->xInfo->getSupportedNumberingTypes();
            pTypes = aTypes.getConstArray();
        }
    }
    SwOLENames aNames(SW_RES(STRRES_NUMTYPES));
    ResStringArray& rNames = aNames.GetNames();
    for(sal_uInt16 i = 0; i < rNames.Count(); i++)
    {
        long nValue = rNames.GetValue(i);
        sal_Bool bInsert = sal_True;
        USHORT nPos = LISTBOX_APPEND;
        switch(nValue)
        {
            case  style::NumberingType::NUMBER_NONE:
                bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_NO_NUMBERING);
                nPos = 0;
             break;
            case  style::NumberingType::CHAR_SPECIAL:   bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_BULLET); break;
            case  style::NumberingType::PAGE_DESCRIPTOR:bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_PAGE_STYLE_NUMBERING); break;
            case  style::NumberingType::BITMAP:bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_BITMAP ); break;
            default:
                if (nValue >  style::NumberingType::CHARS_LOWER_LETTER_N)
                {
                    // Insert only if offered by i18n framework per configuration.
                    bInsert = sal_False;
                    if (pTypes)
                    {
                        for(sal_Int32 nType = 0; nType < aTypes.getLength(); nType++)
                        {
                            if (pTypes[nType] == nValue)
                            {
                                bInsert = sal_True;
                                break;  // for
                            }
                        }
                    }
                }
        }
        if(bInsert)
        {
            USHORT nEntry = InsertEntry(rNames.GetString(i), nPos);
            SetEntryData( nEntry, (void*)nValue );
        }
    }
    if(0 != (nTypeFlags&INSERT_NUM_EXTENDED_TYPES) )
    {
        if(pTypes)
        {
            for(sal_Int32 nType = 0; nType < aTypes.getLength(); nType++)
            {
                sal_Int16 nCurrent = pTypes[nType];
                if(nCurrent > style::NumberingType::CHARS_LOWER_LETTER_N)
                {
                    if(LISTBOX_ENTRY_NOTFOUND == GetEntryPos((void*)(ULONG)nCurrent))
                    {
                        OUString aIdent = pImpl->xInfo->getNumberingIdentifier( nCurrent );
                        USHORT nPos = InsertEntry(aIdent);
                        SetEntryData(nPos,(void*)(ULONG)nCurrent);
                    }
                }
            }
        }
        SelectEntryPos(0);
    }
}
/* -----------------------------01.03.01 14:46--------------------------------

 ---------------------------------------------------------------------------*/
sal_Int16   SwNumberingTypeListBox::GetSelectedNumberingType()
{
    sal_Int16 nRet = 0;
    USHORT nSelPos = GetSelectEntryPos();
    if(LISTBOX_ENTRY_NOTFOUND != nSelPos)
        nRet = (sal_Int16)(ULONG)GetEntryData(nSelPos);
#ifdef DBG_UTIL
    else
        DBG_ERROR("SwNumberingTypeListBox not selected")
#endif
    return nRet;
}
/* -----------------------------01.03.01 14:46--------------------------------

 ---------------------------------------------------------------------------*/
sal_Bool    SwNumberingTypeListBox::SelectNumberingType(sal_Int16 nType)
{
    USHORT nPos = GetEntryPos((void*)(ULONG)nType);
    SelectEntryPos( nPos );
    return LISTBOX_ENTRY_NOTFOUND != nPos;
}

<|endoftext|>


<commit_before>//created by goodje

#include "launcher.h"

typedef struct _PER_HANDLE_DATA
{
	SOCKET Socket;
} PER_HANDLE_DATA, *LPPER_HANDLE_DATA;

typedef struct
{
	WSAOVERLAPPED wsaOverlapped;
	WSABUF wsaBuf;
	int OperationType;
} PER_IO_DATA, *LPPER_IO_DATA;

static DWORD WINAPI ClientWorkerThread(LPVOID lpParameter)
{
	HANDLE hCompletionPort = (HANDLE)lpParameter;
	DWORD bytesCopied = 0;
	OVERLAPPED *overlapped = 0;
	LPPER_HANDLE_DATA PerHandleData;
	LPPER_IO_DATA PerIoData;
	DWORD SendBytes, RecvBytes;
	DWORD Flags;
	BOOL bRet;

	while (TRUE)
	{
		bRet = GetQueuedCompletionStatus(hCompletionPort, &bytesCopied, (LPDWORD)&PerHandleData, (LPOVERLAPPED*)&PerIoData, INFINITE);

		if (bytesCopied == 0)
		{
			break;
		}
		else
		{
			Flags = 0;
			ZeroMemory(&(PerIoData->wsaOverlapped), sizeof(WSAOVERLAPPED));

			PerIoData->wsaBuf.len = 1000;
			WSARecv(PerHandleData->Socket, &(PerIoData->wsaBuf), 1, &RecvBytes, &Flags, &(PerIoData->wsaOverlapped), NULL);
		}
	}

	return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	char log_str[128];

	WSADATA WsaDat;
	WSAStartup(MAKEWORD(2, 2), &WsaDat);

	// Step 1 - Create an I/O completion port.
	HANDLE hCompletionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);

	// Step 2 - Find how many processors.
	SYSTEM_INFO systemInfo;
	GetSystemInfo(&systemInfo);

	//OutputDebugString(systemInfo.dwNumberOfProcessors);

	// Step 3 - Create worker threads.
	for (int i = 0; i < (int)systemInfo.dwNumberOfProcessors; i++)
	{
		HANDLE hThread = CreateThread(NULL, 0, ClientWorkerThread, hCompletionPort, 0, NULL);
		CloseHandle(hThread);
	}

	// Step 4 - Create a socket.
	SOCKET Socket = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);

	PER_HANDLE_DATA *pPerHandleData = new PER_HANDLE_DATA;
	pPerHandleData->Socket = Socket;

	struct hostent *host;
	host = gethostbyname("localhost");

	SOCKADDR_IN SockAddr;
	SockAddr.sin_family = AF_INET;
	SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
	SockAddr.sin_port = htons(8888);

	// Step 5 - Associate the socket with the I/O completion port.
	CreateIoCompletionPort((HANDLE)Socket, hCompletionPort, (DWORD)pPerHandleData, 0);

	WSAConnect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr), NULL, NULL, NULL, NULL);

	static char buffer[1024];
	memset(buffer, 0, 1023);

	PER_IO_DATA *pPerIoData = new PER_IO_DATA;

	pPerIoData->wsaBuf.buf = buffer;
	pPerIoData->wsaBuf.len = sizeof(buffer);

	DWORD dwSendBytes = 0;
	DWORD dwReceivedBytes = 0;
	DWORD dwFlags = 0;

	SecureZeroMemory((PVOID)&pPerIoData->wsaOverlapped, sizeof(pPerIoData->wsaOverlapped));
	pPerIoData->wsaOverlapped.hEvent = WSACreateEvent();

	WSARecv(Socket, &pPerIoData->wsaBuf, 1, &dwReceivedBytes, &dwFlags, &pPerIoData->wsaOverlapped, NULL);
	std::cout << pPerIoData->wsaBuf.buf;

	for (;;)
	{
		int nError = WSAGetLastError();
		if (nError != WSAEWOULDBLOCK && nError != 0)
		{
			sprintf(log_str, "Winsock error code: %d.\nServer disconnected!\n", nError);
			OutputDebugString(log_str);

			shutdown(Socket, SD_SEND);
			closesocket(Socket);

			exit(-1);
		}

		Sleep(1000);
	}

	delete pPerHandleData;
	delete pPerIoData;
	WSACleanup();

	return 0;
}

<commit_msg>some debug output.<commit_after>//created by goodje

#include "launcher.h"

typedef struct _PER_HANDLE_DATA
{
	SOCKET Socket;
} PER_HANDLE_DATA, *LPPER_HANDLE_DATA;

typedef struct
{
	WSAOVERLAPPED wsaOverlapped;
	WSABUF wsaBuf;
	int OperationType;
} PER_IO_DATA, *LPPER_IO_DATA;

static DWORD WINAPI ClientWorkerThread(LPVOID lpParameter)
{
	HANDLE hCompletionPort = (HANDLE)lpParameter;
	DWORD bytesCopied = 0;
	OVERLAPPED *overlapped = 0;
	LPPER_HANDLE_DATA PerHandleData;
	LPPER_IO_DATA PerIoData;
	DWORD SendBytes, RecvBytes;
	DWORD Flags;
	BOOL bRet;
	char log_str[128];

	while (TRUE)
	{
		bRet = GetQueuedCompletionStatus(hCompletionPort, &bytesCopied, (LPDWORD)&PerHandleData, (LPOVERLAPPED*)&PerIoData, INFINITE);

		if (bytesCopied == 0)
		{
			break;
		}
		else
		{
			Flags = 0;
			ZeroMemory(&(PerIoData->wsaOverlapped), sizeof(WSAOVERLAPPED));

			PerIoData->wsaBuf.len = 1000;
			WSARecv(PerHandleData->Socket, &(PerIoData->wsaBuf), 1, &RecvBytes, &Flags, &(PerIoData->wsaOverlapped), NULL);
			sprintf(log_str, "receive data: %s\n", PerIoData->wsaBuf);
			OutputDebugString(log_str);
		}
	}

	return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	char motise_host[128] = "192.168.13.231";
	unsigned int motise_port = 6424;

	char log_str[128];

	WSADATA WsaDat;
	WSAStartup(MAKEWORD(2, 2), &WsaDat);

	// Step 1 - Create an I/O completion port.
	HANDLE hCompletionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);

	// Step 2 - Find how many processors.
	SYSTEM_INFO systemInfo;
	GetSystemInfo(&systemInfo);

	// Step 3 - Create worker threads.
	for (int i = 0; i < (int)systemInfo.dwNumberOfProcessors; i++)
	{
		HANDLE hThread = CreateThread(NULL, 0, ClientWorkerThread, hCompletionPort, 0, NULL);
		CloseHandle(hThread);
	}

	// Step 4 - Create a socket.
	SOCKET Socket = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);

	PER_HANDLE_DATA *pPerHandleData = new PER_HANDLE_DATA;
	pPerHandleData->Socket = Socket;

	struct hostent *host;
	host = gethostbyname(motise_host);

	SOCKADDR_IN SockAddr;
	SockAddr.sin_family = AF_INET;
	SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
	SockAddr.sin_port = htons(motise_port);

	// Step 5 - Associate the socket with the I/O completion port.
	CreateIoCompletionPort((HANDLE)Socket, hCompletionPort, (DWORD)pPerHandleData, 0);

	WSAConnect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr), NULL, NULL, NULL, NULL);

	static char buffer[1024];
	memset(buffer, 0, 1023);

	PER_IO_DATA *pPerIoData = new PER_IO_DATA;

	pPerIoData->wsaBuf.buf = buffer;
	pPerIoData->wsaBuf.len = sizeof(buffer);

	DWORD dwSendBytes = 0;
	DWORD dwReceivedBytes = 0;
	DWORD dwFlags = 0;

	SecureZeroMemory((PVOID)&pPerIoData->wsaOverlapped, sizeof(pPerIoData->wsaOverlapped));
	pPerIoData->wsaOverlapped.hEvent = WSACreateEvent();

	WSARecv(Socket, &pPerIoData->wsaBuf, 1, &dwReceivedBytes, &dwFlags, &pPerIoData->wsaOverlapped, NULL);
	std::cout << pPerIoData->wsaBuf.buf;

	for (;;)
	{
		int nError = WSAGetLastError();
		if (nError != WSAEWOULDBLOCK && nError != 0)
		{
			sprintf(log_str, "Winsock error code: %d.\nServer disconnected!\n", nError);
			OutputDebugString(log_str);

			shutdown(Socket, SD_SEND);
			closesocket(Socket);

			exit(-1);
		}

		Sleep(1000);
	}

	delete pPerHandleData;
	delete pPerIoData;
	WSACleanup();

	return 0;
}

<|endoftext|>


<commit_before>#include <Arduino.h>
#include <avr/pgmspace.h>

#include "settings.h"
#include "settings_eeprom.h"
#include "receiver.h"
#include "receiver_spi.h"
#include "channels.h"

static void updateRssiLimits();
static void writeSerialData();

namespace Receiver {
    uint8_t activeReceiver = RECEIVER_A;
    uint8_t activeChannel = 0;

    uint8_t rssiA = 0;
    uint16_t rssiARaw = 0;
    uint8_t rssiALast[RECEIVER_LAST_DATA_SIZE] = { 0 };
    #ifdef USE_DIVERSITY
        uint8_t rssiB = 0;
        uint16_t rssiBRaw = 0;
        uint8_t rssiBLast[RECEIVER_LAST_DATA_SIZE] = { 0 };
    #endif

    uint32_t lastChannelSwitchTime = 0;
    uint32_t lastRssiLogTime = 0;
    #ifdef USE_SERIAL_OUT
        static uint32_t lastSerialWriteTime = 0;
    #endif

    void setChannel(uint8_t channel)
    {
        ReceiverSpi::setSynthRegisterB(Channels::getSynthRegisterB(channel));

        lastChannelSwitchTime = millis();
        activeChannel = channel;
    }

    void setActiveReceiver(uint8_t receiver) {
        #ifdef USE_DIVERSITY
            digitalWrite(PIN_LED_A, receiver == RECEIVER_A);
            digitalWrite(PIN_LED_B, receiver == RECEIVER_B);
        #else
            digitalWrite(PIN_LED_A, HIGH);
        #endif

        activeReceiver = receiver;
    }

    //
    // Blocks until MIN_TUNE_TIME has been reached since last channel switch.
    //
    void waitForStableRssi() {
        uint16_t timeSinceChannelSwitch = millis() - lastChannelSwitchTime;
        if (timeSinceChannelSwitch < MIN_TUNE_TIME) {
            delay(MIN_TUNE_TIME - timeSinceChannelSwitch);
        }
    }

    uint16_t updateRssi() {
        waitForStableRssi();

        rssiARaw = 0;
        #ifdef USE_DIVERSITY
            rssiBRaw = 0;
        #endif

        for (uint8_t i = 0; i < RSSI_READS; i++) {
            rssiARaw += analogRead(PIN_RSSI_A);
            #ifdef USE_DIVERSITY
                rssiBRaw += analogRead(PIN_RSSI_B);
            #endif
        }

        rssiARaw = rssiARaw / RSSI_READS;
        #ifdef USE_DIVERSITY
            rssiBRaw = rssiBRaw / RSSI_READS;
        #endif

        updateRssiLimits();

        rssiA = map(
            rssiARaw,
            EepromSettings.rssiAMin,
            EepromSettings.rssiAMax,
            1,
            100);

        #ifdef USE_DIVERSITY
            rssiB = map(
                rssiBRaw,
                EepromSettings.rssiBMin,
                EepromSettings.rssiBMax,
                1,
                100);
        #endif

        if (millis() >= lastRssiLogTime + RECEIVER_LAST_DELAY) {
            for (uint8_t i = 0; i < RECEIVER_LAST_DATA_SIZE - 1; i++) {
                rssiALast[i] = rssiALast[i + 1];

                #ifdef USE_DIVERSITY
                    rssiBLast[i] = rssiBLast[i + 1];
                #endif
            }

            rssiALast[RECEIVER_LAST_DATA_SIZE - 1] = rssiA;
            #ifdef USE_DIVERSITY
                rssiBLast[RECEIVER_LAST_DATA_SIZE - 1] = rssiB;
            #endif

            lastRssiLogTime = millis();
        }
    }

    void setDiversityMode(uint8_t mode) {
        EepromSettings.diversityMode = mode;
        switchDiversity();
    }

    void switchDiversity() {
        static uint8_t diversityCheckTick = 0;
        uint8_t bestReceiver = activeReceiver;

        if (EepromSettings.diversityMode == DIVERSITY_AUTO) {
            uint8_t rssiDiff =
                (int) abs(((rssiA - rssiB) / (float) rssiB) * 100.0f);

            if (rssiDiff >= DIVERSITY_CUTOVER) {
                if(rssiA > rssiB && diversityCheckTick > 0)
                    diversityCheckTick--;

                if(rssiA < rssiB && diversityCheckTick < DIVERSITY_MAX_CHECKS)
                    diversityCheckTick++;

                // Have we reached the maximum number of checks to switch
                // receivers?
                if (diversityCheckTick == 0 ||
                    diversityCheckTick >= DIVERSITY_MAX_CHECKS
                ) {
                    bestReceiver =
                        (diversityCheckTick == 0) ?
                        RECEIVER_A :
                        RECEIVER_B;
                }
            }
        } else {
            switch (EepromSettings.diversityMode) {
                case DIVERSITY_FORCE_A:
                    bestReceiver = RECEIVER_A;
                    break;

                case DIVERSITY_FORCE_B:
                    bestReceiver = RECEIVER_B;
                    break;
            }
        }

        setActiveReceiver(bestReceiver);
    }

    void setup() {
        #ifdef DISABLE_AUDIO
            ReceiverSpi::setPowerDownRegister(0b00010000110111110011);
        #endif
    }

    void update() {
        updateRssi();

        #ifdef USE_SERIAL_OUT
            writeSerialData();
        #endif

        #ifdef USE_DIVERSITY
            switchDiversity();
        #endif
    }
}

static void updateRssiLimits() {
    // TEMP: Until logic for setting RSSI max is rewritten.

    if (Receiver::rssiARaw > EepromSettings.rssiAMax)
        EepromSettings.rssiAMax = Receiver::rssiARaw;

    if (Receiver::rssiARaw < EepromSettings.rssiAMin)
        EepromSettings.rssiAMin = Receiver::rssiARaw;

    #ifdef USE_DIVERSITY
        if (Receiver::rssiBRaw > EepromSettings.rssiBMax)
            EepromSettings.rssiBMax = Receiver::rssiBRaw;

        if (Receiver::rssiBRaw < EepromSettings.rssiBMin)
            EepromSettings.rssiBMin = Receiver::rssiBRaw;
    #endif
}

#ifdef USE_SERIAL_OUT
static void writeSerialData() {
    uint16_t timeSinceWrite = millis() - Receiver::lastSerialWriteTime;
    if (timeSinceWrite >= 20) {
        Serial.print(Receiver::activeChannel, DEC);
        Serial.print("\t");
        Serial.print(Receiver::rssiA, DEC);
        Serial.print("\t");
        Serial.print(Receiver::rssiARaw, DEC);
        Serial.print("\t");
        Serial.print(Receiver::rssiB, DEC);
        Serial.print("\t");
        Serial.println(Receiver::rssiBRaw, DEC);

        Receiver::lastSerialWriteTime = millis();
    }
}
#endif
<commit_msg>Only need to do one read (+ one fake) for valid RSSI<commit_after>#include <Arduino.h>
#include <avr/pgmspace.h>

#include "settings.h"
#include "settings_eeprom.h"
#include "receiver.h"
#include "receiver_spi.h"
#include "channels.h"

static void updateRssiLimits();
static void writeSerialData();

namespace Receiver {
    uint8_t activeReceiver = RECEIVER_A;
    uint8_t activeChannel = 0;

    uint8_t rssiA = 0;
    uint16_t rssiARaw = 0;
    uint8_t rssiALast[RECEIVER_LAST_DATA_SIZE] = { 0 };
    #ifdef USE_DIVERSITY
        uint8_t rssiB = 0;
        uint16_t rssiBRaw = 0;
        uint8_t rssiBLast[RECEIVER_LAST_DATA_SIZE] = { 0 };
    #endif

    uint32_t lastChannelSwitchTime = 0;
    uint32_t lastRssiLogTime = 0;
    #ifdef USE_SERIAL_OUT
        static uint32_t lastSerialWriteTime = 0;
    #endif

    void setChannel(uint8_t channel)
    {
        ReceiverSpi::setSynthRegisterB(Channels::getSynthRegisterB(channel));

        lastChannelSwitchTime = millis();
        activeChannel = channel;
    }

    void setActiveReceiver(uint8_t receiver) {
        #ifdef USE_DIVERSITY
            digitalWrite(PIN_LED_A, receiver == RECEIVER_A);
            digitalWrite(PIN_LED_B, receiver == RECEIVER_B);
        #else
            digitalWrite(PIN_LED_A, HIGH);
        #endif

        activeReceiver = receiver;
    }

    //
    // Blocks until MIN_TUNE_TIME has been reached since last channel switch.
    //
    void waitForStableRssi() {
        uint16_t timeSinceChannelSwitch = millis() - lastChannelSwitchTime;
        if (timeSinceChannelSwitch < MIN_TUNE_TIME) {
            delay(MIN_TUNE_TIME - timeSinceChannelSwitch);
        }
    }

    uint16_t updateRssi() {
        waitForStableRssi();

        rssiARaw = 0;
        #ifdef USE_DIVERSITY
            rssiBRaw = 0;
        #endif

        analogRead(PIN_RSSI_A); // Fake read to let ADC settle.
        rssiARaw = analogRead(PIN_RSSI_A);
        #ifdef USE_DIVERSITY
            analogRead(PIN_RSSI_B);
            rssiBRaw = analogRead(PIN_RSSI_B);
        #endif

        updateRssiLimits();

        rssiA = map(
            rssiARaw,
            EepromSettings.rssiAMin,
            EepromSettings.rssiAMax,
            1,
            100);
        #ifdef USE_DIVERSITY
            rssiB = map(
                rssiBRaw,
                EepromSettings.rssiBMin,
                EepromSettings.rssiBMax,
                1,
                100);
        #endif

        if (millis() >= lastRssiLogTime + RECEIVER_LAST_DELAY) {
            for (uint8_t i = 0; i < RECEIVER_LAST_DATA_SIZE - 1; i++) {
                rssiALast[i] = rssiALast[i + 1];
                #ifdef USE_DIVERSITY
                    rssiBLast[i] = rssiBLast[i + 1];
                #endif
            }

            rssiALast[RECEIVER_LAST_DATA_SIZE - 1] = rssiA;
            #ifdef USE_DIVERSITY
                rssiBLast[RECEIVER_LAST_DATA_SIZE - 1] = rssiB;
            #endif

            lastRssiLogTime = millis();
        }
    }

    void setDiversityMode(uint8_t mode) {
        EepromSettings.diversityMode = mode;
        switchDiversity();
    }

    void switchDiversity() {
        static uint8_t diversityCheckTick = 0;
        uint8_t bestReceiver = activeReceiver;

        if (EepromSettings.diversityMode == DIVERSITY_AUTO) {
            uint8_t rssiDiff =
                (int) abs(((rssiA - rssiB) / (float) rssiB) * 100.0f);

            if (rssiDiff >= DIVERSITY_CUTOVER) {
                if(rssiA > rssiB && diversityCheckTick > 0)
                    diversityCheckTick--;

                if(rssiA < rssiB && diversityCheckTick < DIVERSITY_MAX_CHECKS)
                    diversityCheckTick++;

                // Have we reached the maximum number of checks to switch
                // receivers?
                if (diversityCheckTick == 0 ||
                    diversityCheckTick >= DIVERSITY_MAX_CHECKS
                ) {
                    bestReceiver =
                        (diversityCheckTick == 0) ?
                        RECEIVER_A :
                        RECEIVER_B;
                }
            }
        } else {
            switch (EepromSettings.diversityMode) {
                case DIVERSITY_FORCE_A:
                    bestReceiver = RECEIVER_A;
                    break;

                case DIVERSITY_FORCE_B:
                    bestReceiver = RECEIVER_B;
                    break;
            }
        }

        setActiveReceiver(bestReceiver);
    }

    void setup() {
        #ifdef DISABLE_AUDIO
            ReceiverSpi::setPowerDownRegister(0b00010000110111110011);
        #endif
    }

    void update() {
        updateRssi();

        #ifdef USE_SERIAL_OUT
            writeSerialData();
        #endif

        #ifdef USE_DIVERSITY
            switchDiversity();
        #endif
    }
}

static void updateRssiLimits() {
    // TEMP: Until logic for setting RSSI max is rewritten.

    if (Receiver::rssiARaw > EepromSettings.rssiAMax)
        EepromSettings.rssiAMax = Receiver::rssiARaw;

    if (Receiver::rssiARaw < EepromSettings.rssiAMin)
        EepromSettings.rssiAMin = Receiver::rssiARaw;

    #ifdef USE_DIVERSITY
        if (Receiver::rssiBRaw > EepromSettings.rssiBMax)
            EepromSettings.rssiBMax = Receiver::rssiBRaw;

        if (Receiver::rssiBRaw < EepromSettings.rssiBMin)
            EepromSettings.rssiBMin = Receiver::rssiBRaw;
    #endif
}

#ifdef USE_SERIAL_OUT
static void writeSerialData() {
    uint16_t timeSinceWrite = millis() - Receiver::lastSerialWriteTime;
    if (timeSinceWrite >= 20) {
        Serial.print(Receiver::activeChannel, DEC);
        Serial.print("\t");
        Serial.print(Receiver::rssiA, DEC);
        Serial.print("\t");
        Serial.print(Receiver::rssiARaw, DEC);
        Serial.print("\t");
        Serial.print(Receiver::rssiB, DEC);
        Serial.print("\t");
        Serial.println(Receiver::rssiBRaw, DEC);

        Receiver::lastSerialWriteTime = millis();
    }
}
#endif
<|endoftext|>


<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */

#include <sys/stat.h>
#include <iostream>
#include <string>
using namespace std;

#include "config.h"

#include "client/Client.h"
#include "client/fuse.h"
#include "client/fuse_ll.h"

#include "msg/SimpleMessenger.h"

#include "mon/MonClient.h"

#include "common/Timer.h"
#include "common/common_init.h"

#ifndef DARWIN
#include <envz.h>
#endif // DARWIN

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

int main(int argc, const char **argv, const char *envp[]) {

  //cerr << "cfuse starting " << myrank << "/" << world << std::endl;
  vector<const char*> args;
  argv_to_vec(argc, argv, args);
  env_to_vec(args);
  common_init(args);

  // args for fuse
  vec_to_argv(args, argc, argv);

  // FUSE will chdir("/"); be ready.
  g_conf.chdir_root = true;

  if (g_conf.clock_tare) g_clock.tare();

  // check for 32-bit arch
  if (sizeof(long) == 4) {
    cerr << std::endl;
    cerr << "WARNING: Ceph inode numbers are 64 bits wide, and FUSE on 32-bit kernels does" << std::endl;
    cerr << "         not cope well with that situation.  Expect to crash shortly." << std::endl;
    cerr << std::endl;
  }

  // get monmap
  MonMap monmap;
  MonClient mc;
  if (mc.get_monmap(&monmap) < 0)
    return -1;

  // start up network
  rank.bind();
  cout << "bound to " << rank.get_rank_addr() << ", mounting ceph" << std::endl;
  rank.start();

  rank.set_policy(entity_name_t::TYPE_MON, Rank::Policy::lossy_fast_fail());
  rank.set_policy(entity_name_t::TYPE_MDS, Rank::Policy::lossless());
  rank.set_policy(entity_name_t::TYPE_OSD, Rank::Policy::lossless());

  // start client
  Client *client = new Client(rank.register_entity(entity_name_t::CLIENT()), &monmap);
  client->init();

  // start up fuse
  // use my argc, argv (make sure you pass a mount point!)
  client->mount();

  _dout_create_courtesy_output_symlink("client", client->get_nodeid());
  cout << "starting fuse" << std::endl;

  //cerr << "starting fuse on pid " << getpid() << std::endl;
  if (g_conf.fuse_ll)
    ceph_fuse_ll_main(client, argc, argv);
  else
    ceph_fuse_main(client, argc, argv);
  //cerr << "fuse finished on pid " << getpid() << std::endl;

  cout << "fuse finished, unmounting ceph" << std::endl;
  client->unmount();
  cout << "unmounted" << std::endl;
  client->shutdown();

  delete client;

  // wait for messenger to finish
  rank.wait();

  return 0;
}

<commit_msg>cfuse: fix startup<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */

#include <sys/stat.h>
#include <iostream>
#include <string>
using namespace std;

#include "config.h"

#include "client/Client.h"
#include "client/fuse.h"
#include "client/fuse_ll.h"

#include "msg/SimpleMessenger.h"

#include "mon/MonClient.h"

#include "common/Timer.h"
#include "common/common_init.h"

#ifndef DARWIN
#include <envz.h>
#endif // DARWIN

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

int main(int argc, const char **argv, const char *envp[]) {

  //cerr << "cfuse starting " << myrank << "/" << world << std::endl;
  vector<const char*> args;
  argv_to_vec(argc, argv, args);
  env_to_vec(args);
  common_init(args);

  // args for fuse
  vec_to_argv(args, argc, argv);

  // FUSE will chdir("/"); be ready.
  g_conf.chdir_root = true;

  if (g_conf.clock_tare) g_clock.tare();

  // check for 32-bit arch
  if (sizeof(long) == 4) {
    cerr << std::endl;
    cerr << "WARNING: Ceph inode numbers are 64 bits wide, and FUSE on 32-bit kernels does" << std::endl;
    cerr << "         not cope well with that situation.  Expect to crash shortly." << std::endl;
    cerr << std::endl;
  }

  // get monmap
  MonMap monmap;
  MonClient mc;
  if (mc.get_monmap(&monmap) < 0)
    return -1;

  // start up network
  rank.bind();
  cout << "bound to " << rank.get_rank_addr() << ", mounting ceph" << std::endl;

  Client *client = new Client(rank.register_entity(entity_name_t::CLIENT()), &monmap);

  rank.start();

  rank.set_policy(entity_name_t::TYPE_MON, Rank::Policy::lossy_fast_fail());
  rank.set_policy(entity_name_t::TYPE_MDS, Rank::Policy::lossless());
  rank.set_policy(entity_name_t::TYPE_OSD, Rank::Policy::lossless());

  // start client
  client->init();

  // start up fuse
  // use my argc, argv (make sure you pass a mount point!)
  client->mount();

  _dout_create_courtesy_output_symlink("client", client->get_nodeid());
  cout << "starting fuse" << std::endl;

  //cerr << "starting fuse on pid " << getpid() << std::endl;
  if (g_conf.fuse_ll)
    ceph_fuse_ll_main(client, argc, argv);
  else
    ceph_fuse_main(client, argc, argv);
  //cerr << "fuse finished on pid " << getpid() << std::endl;

  cout << "fuse finished, unmounting ceph" << std::endl;
  client->unmount();
  cout << "unmounted" << std::endl;
  client->shutdown();

  delete client;

  // wait for messenger to finish
  rank.wait();

  return 0;
}

<|endoftext|>