<commit_before>#include "UASQuickTabView.h"
#include "ui_UASQuickTabView.h"
#include <QTextCodec>
#include <QDebug>
#include <QTableWidget>
#include <QtGui>

UASQuickTabView::UASQuickTabView(QWidget *parent) :
    ui(new Ui::UASQuickTabView)
{
    ui->setupUi(this);
//    this->setLayout(ui->gridLayout);
//    ui->gridLayout->setContentsMargins(0,0,0,0);
//    ui->gridLayout->setHorizontalSpacing(0);
//    ui->gridLayout->setVerticalSpacing(0);
//    ui->gridLayout->setSpacing(0);
//    ui->gridLayout->setMargin(0);

	QStringList nameList;// = new QStringList();
//	nameList.append("Широта:");
//	nameList.append("Долгота:");
//	nameList.append("Высота:");
//	nameList.append("Курс:");
//	nameList.append("Крен:");
//	nameList.append("Тангаж:");

    nameList.append(tr("Latitude:"));
    nameList.append(tr("Longitude:"));
    nameList.append(tr("Altitude:"));
    nameList.append(tr("Roll:"));
    nameList.append(tr("Pitch:"));
    nameList.append(tr("Yaw:"));

    fieldNameList << "M24:GLOBAL_POSITION_INT.lat"
                  << "M24:GLOBAL_POSITION_INT.lon"
                  << "M24:GLOBAL_POSITION_INT.alt"
                  << "M24:ATTITUDE.roll"
                  << "M24:ATTITUDE.pitch"
                  << "M24:ATTITUDE.yaw";

    foreach(QString str, fieldNameList){
        uasPropertyValueMap.insert(str, 0.0);
    }

	QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
	ui->tableWidget->setColumnCount(2);
    ui->tableWidget->setRowCount(nameList.count());
    ui->tableWidget->setLineWidth(1);
    ui->tableWidget->setFrameStyle(QFrame::NoFrame);
    //ui->tableWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    ui->tableWidget->setStyleSheet("gridline-color : dimgray");
    ui->tableWidget->setWindowFlags(/*ui->tableWidget->windowFlags()*/Qt::Widget | Qt::FramelessWindowHint);

    //tableFont = new QFont("Times New Roman", 14, 3);
//    tableFont.setFamily("Times New Roman");
    tableFont.setPixelSize(14);
    tableFont.setBold(3);

    for(int i = 0; i < nameList.count(); i++) {
        /* Add first column that shows lable names.*/
        QTableWidgetItem* item = new QTableWidgetItem();
        Q_ASSERT(item);
        if (item) {
            item->setText(nameList.at(i));
            tableNameList.append(item);
            item->setFont(tableFont);
            item->setFlags(item->flags() ^ Qt::ItemIsEditable ^ Qt::ItemIsSelectable);
            ui->tableWidget->setItem(i, 0, item);
        }

        /* Add column with values.*/
        item = new QTableWidgetItem();
        Q_ASSERT(item);
        if (item) {
            tableValueList.append(item);
            item->setFont(tableFont);
            item->setText("0.0");
            item->setFlags(item->flags() ^ Qt::ItemIsEditable ^ Qt::ItemIsSelectable);
            ui->tableWidget->setItem(i, 1, item);
        }
    }

    setTableGeometry();

    updateTimer = new QTimer(this);
    connect(updateTimer,SIGNAL(timeout()),this,SLOT(updateTimerTick()));
    updateTimer->start(1000);

//    testTimerValue = true;
//    testTimer = new QTimer(this);
//    testTimer->setSingleShot(false);
//    connect(testTimer,SIGNAL(timeout()),this,SLOT(testTimerExpired()));
//    testTimer->start(750);

}

UASQuickTabView::~UASQuickTabView()
{
    delete ui;
    foreach (QTableWidgetItem* item, tableNameList) {
        delete item;
    }
    foreach (QTableWidgetItem* item, tableValueList) {
        delete item;
    }
    delete updateTimer;
}

void UASQuickTabView::addSource(MAVLinkDecoder *decoder)
{
    connect(decoder,SIGNAL(valueChanged(int,QString,QString,QVariant,quint64)),this,SLOT(valueChanged(int,QString,QString,QVariant,quint64)));
}

void UASQuickTabView::valueChanged(const int uasId, const QString& name, const QString& unit, const QVariant &variant, const quint64 msec)
{
    Q_UNUSED(uasId);
    Q_UNUSED(unit);
    Q_UNUSED(msec);

    bool ok;
    double value = variant.toDouble(&ok);
    QMetaType::Type metaType = static_cast<QMetaType::Type>(variant.type());
    if(!ok || metaType == QMetaType::QString || metaType == QMetaType::QByteArray)
        return;
    //qDebug()<<name<<" "<<value;
//    if (!uasPropertyValueMap.contains(name))
//    {
//        if (quickViewSelectDialog)
//        {
//            quickViewSelectDialog->addItem(name);
//        }
//    }

    if((name == "M24:GLOBAL_POSITION_INT.lat")||(name == "M24:GLOBAL_POSITION_INT.lon"))
        uasPropertyValueMap[name] = value/10000000;
    else if(name == "M24:GLOBAL_POSITION_INT.alt")
        uasPropertyValueMap[name] = value/1000;
    else if((name == "M24:ATTITUDE.roll")||(name == "M24:ATTITUDE.pitch")||(name == "M24:ATTITUDE.yaw"))
        uasPropertyValueMap[name] = value/M_PI*180;
}

void UASQuickTabView::updateTimerTick()
{
    for(int i = 0; i < fieldNameList.size(); i++){
        //QString str = QString::number(uasPropertyValueMap[fieldNameList.at(i)]);
        QString str = formText(fieldNameList.at(i), uasPropertyValueMap[fieldNameList.at(i)]);
        ui->tableWidget->item(i,1)->setText(str);
    }
}

//void UASQuickTabView::testTimerExpired(){
//    if(testTimerValue == true){
//        valueChanged(0,"M24:GLOBAL_POSITION_INT.lat","unit",538893530,0);
//        valueChanged(0,"M24:GLOBAL_POSITION_INT.lon","unit",275296780,0);
//        valueChanged(0,"M24:GLOBAL_POSITION_INT.alt","unit",272000,0);
//        valueChanged(0,"M24:ATTITUDE.roll","unit",0.36814,0);
//        valueChanged(0,"M24:ATTITUDE.pitch","unit",0.56715,0);
//        valueChanged(0,"M24:ATTITUDE.yaw","unit",0.24715,0);
//        testTimerValue = false;
//    }
//    else{
//        valueChanged(0,"M24:GLOBAL_POSITION_INT.lat","unit",-549993530,0);
//        valueChanged(0,"M24:GLOBAL_POSITION_INT.lon","unit",-277796780,0);
//        valueChanged(0,"M24:GLOBAL_POSITION_INT.alt","unit",284000,0);
//        valueChanged(0,"M24:ATTITUDE.roll","unit",0.35614,0);
//        valueChanged(0,"M24:ATTITUDE.pitch","unit",0.46815,0);
//        valueChanged(0,"M24:ATTITUDE.yaw","unit",0.67895,0);
//        testTimerValue = true;
//    }
//}

void UASQuickTabView::setTableGeometry(){

    int rowCount = ui->tableWidget->rowCount();

    //ui->tableWidget->setWi

    //ui->tableWidget->verticalHeader()->sectionResized();

    ui->tableWidget->resize(this->width(), this->height());

//    ui->tableWidget->setColumnWidth(0, (int)((double)(ui->tableWidget->width())/2.0));
//    ui->tableWidget->setColumnWidth(1, (int)((double)(ui->tableWidget->width())/2.0));

    ui->tableWidget->setColumnWidth(0, ((ui->tableWidget->width())/2));
    ui->tableWidget->setColumnWidth(1, ((ui->tableWidget->width())/2 + (ui->tableWidget->width())%2));

    for(int i = 0; i < ui->tableWidget->rowCount() - 1; i++) {

        ui->tableWidget->setRowHeight(i, (ui->tableWidget->height())/rowCount);
        //ui->tableWidget->setRowHeight(i, (ui->tableWidget->height())/6);
    }
    ui->tableWidget->setRowHeight(ui->tableWidget->rowCount() - 1, ((ui->tableWidget->height())/rowCount) + ((ui->tableWidget->height())%rowCount));

}

QString UASQuickTabView::formText(QString name, double value){

    QString str;

    if(name == "M24:GLOBAL_POSITION_INT.lat"){
        if(value >= 0){
            str = QString::number(value,'f',5);
            str += 0x00B0;
             str += tr(" N");
        }
        else if(value < 0){
            value *=-1;
            str = QString::number(value,'f',5);
            str += 0x00B0;
            str += tr(" S");
        }
    }

    else if(name == "M24:GLOBAL_POSITION_INT.lon"){
        if(value >= 0){
            str = QString::number(value,'f',5);
            str += 0x00B0;
             str += tr(" E");
        }
        else if(value < 0){
            value *=-1;
            str = QString::number(value,'f',5);
            str += 0x00B0;
            str += tr(" W");
        }
    }

    else if(name == "M24:GLOBAL_POSITION_INT.alt"){
        str = QString::number(value,'f',1);
        str +=tr(" m.");
    }
    else if((name == "M24:ATTITUDE.roll")||(name == "M24:ATTITUDE.pitch")||(name == "M24:ATTITUDE.yaw")){
        str = QString::number(value,'f',2);
        str += 0x00B0;
    }
    return str;
}

void UASQuickTabView::resizeEvent(QResizeEvent *event){
    setTableGeometry();
}

<commit_msg>Minor fixes. Cleaned up code.<commit_after>#include "UASQuickTabView.h"
#include "ui_UASQuickTabView.h"
#include <QTextCodec>
#include <QDebug>
#include <QTableWidget>
#include <QtGui>

UASQuickTabView::UASQuickTabView(QWidget *parent) :
    ui(new Ui::UASQuickTabView)
{
    ui->setupUi(this);
//    this->setLayout(ui->gridLayout);
//    ui->gridLayout->setContentsMargins(0,0,0,0);
//    ui->gridLayout->setHorizontalSpacing(0);
//    ui->gridLayout->setVerticalSpacing(0);
//    ui->gridLayout->setSpacing(0);
//    ui->gridLayout->setMargin(0);

	QStringList nameList;// = new QStringList();
//	nameList.append("Широта:");
//	nameList.append("Долгота:");
//	nameList.append("Высота:");
//	nameList.append("Курс:");
//	nameList.append("Крен:");
//	nameList.append("Тангаж:");

    nameList.append(tr("Latitude:"));
    nameList.append(tr("Longitude:"));
    nameList.append(tr("Altitude:"));
    nameList.append(tr("Roll:"));
    nameList.append(tr("Pitch:"));
    nameList.append(tr("Yaw:"));

    fieldNameList << "M24:GLOBAL_POSITION_INT.lat"
                  << "M24:GLOBAL_POSITION_INT.lon"
                  << "M24:GLOBAL_POSITION_INT.alt"
                  << "M24:ATTITUDE.roll"
                  << "M24:ATTITUDE.pitch"
                  << "M24:ATTITUDE.yaw";

    foreach(QString str, fieldNameList){
        uasPropertyValueMap.insert(str, 0.0);
    }

	QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
	ui->tableWidget->setColumnCount(2);
    ui->tableWidget->setRowCount(nameList.count());
    ui->tableWidget->setLineWidth(1);
    ui->tableWidget->setFrameStyle(QFrame::NoFrame);
    //ui->tableWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    ui->tableWidget->setStyleSheet("gridline-color : dimgray");
    ui->tableWidget->setWindowFlags(/*ui->tableWidget->windowFlags()*/Qt::Widget | Qt::FramelessWindowHint);

    //tableFont = new QFont("Times New Roman", 14, 3);
//    tableFont.setFamily("Times New Roman");
    tableFont.setPixelSize(14);
    tableFont.setBold(3);

    for(int i = 0; i < nameList.count(); i++) {
        /* Add first column that shows lable names.*/
        QTableWidgetItem* item = new QTableWidgetItem();
        Q_ASSERT(item);
        if (item) {
            item->setText(nameList.at(i));
            tableNameList.append(item);
            item->setFont(tableFont);
            item->setFlags(item->flags() ^ Qt::ItemIsEditable ^ Qt::ItemIsSelectable);
            ui->tableWidget->setItem(i, 0, item);
        }

        /* Add column with values.*/
        item = new QTableWidgetItem();
        Q_ASSERT(item);
        if (item) {
            tableValueList.append(item);
            item->setFont(tableFont);
            item->setText("0.0");
            item->setFlags(item->flags() ^ Qt::ItemIsEditable ^ Qt::ItemIsSelectable);
            ui->tableWidget->setItem(i, 1, item);
        }
    }

    setTableGeometry();

    updateTimer = new QTimer(this);
    connect(updateTimer,SIGNAL(timeout()),this,SLOT(updateTimerTick()));
    updateTimer->start(1000);

//    testTimerValue = true;
//    testTimer = new QTimer(this);
//    testTimer->setSingleShot(false);
//    connect(testTimer,SIGNAL(timeout()),this,SLOT(testTimerExpired()));
//    testTimer->start(750);

}

UASQuickTabView::~UASQuickTabView()
{
    delete ui;
    foreach (QTableWidgetItem* item, tableNameList) {
        delete item;
    }
    foreach (QTableWidgetItem* item, tableValueList) {
        delete item;
    }
    delete updateTimer;
}

void UASQuickTabView::addSource(MAVLinkDecoder *decoder)
{
    connect(decoder,SIGNAL(valueChanged(int,QString,QString,QVariant,quint64)),this,SLOT(valueChanged(int,QString,QString,QVariant,quint64)));
}

void UASQuickTabView::valueChanged(const int uasId, const QString& name, const QString& unit, const QVariant &variant, const quint64 msec)
{
    Q_UNUSED(uasId);
    Q_UNUSED(unit);
    Q_UNUSED(msec);

    bool ok;
    double value = variant.toDouble(&ok);
    QMetaType::Type metaType = static_cast<QMetaType::Type>(variant.type());
    if(!ok || metaType == QMetaType::QString || metaType == QMetaType::QByteArray)
        return;
    //qDebug()<<name<<" "<<value;
//    if (!uasPropertyValueMap.contains(name))
//    {
//        if (quickViewSelectDialog)
//        {
//            quickViewSelectDialog->addItem(name);
//        }
//    }

    if((name == "M24:GLOBAL_POSITION_INT.lat")||(name == "M24:GLOBAL_POSITION_INT.lon"))
        uasPropertyValueMap[name] = value/10000000;
    else if(name == "M24:GLOBAL_POSITION_INT.alt")
        uasPropertyValueMap[name] = value/1000;
    else if((name == "M24:ATTITUDE.roll")||(name == "M24:ATTITUDE.pitch")||(name == "M24:ATTITUDE.yaw"))
        uasPropertyValueMap[name] = value/M_PI*180;
}

void UASQuickTabView::updateTimerTick()
{
    for(int i = 0; i < fieldNameList.size(); i++){
        //QString str = QString::number(uasPropertyValueMap[fieldNameList.at(i)]);
        QString str = formText(fieldNameList.at(i), uasPropertyValueMap[fieldNameList.at(i)]);
        ui->tableWidget->item(i,1)->setText(str);
    }
}

//void UASQuickTabView::testTimerExpired(){
//    if(testTimerValue == true){
//        valueChanged(0,"M24:GLOBAL_POSITION_INT.lat","unit",538893530,0);
//        valueChanged(0,"M24:GLOBAL_POSITION_INT.lon","unit",275296780,0);
//        valueChanged(0,"M24:GLOBAL_POSITION_INT.alt","unit",272000,0);
//        valueChanged(0,"M24:ATTITUDE.roll","unit",0.36814,0);
//        valueChanged(0,"M24:ATTITUDE.pitch","unit",0.56715,0);
//        valueChanged(0,"M24:ATTITUDE.yaw","unit",0.24715,0);
//        testTimerValue = false;
//    }
//    else{
//        valueChanged(0,"M24:GLOBAL_POSITION_INT.lat","unit",-549993530,0);
//        valueChanged(0,"M24:GLOBAL_POSITION_INT.lon","unit",-277796780,0);
//        valueChanged(0,"M24:GLOBAL_POSITION_INT.alt","unit",284000,0);
//        valueChanged(0,"M24:ATTITUDE.roll","unit",0.35614,0);
//        valueChanged(0,"M24:ATTITUDE.pitch","unit",0.46815,0);
//        valueChanged(0,"M24:ATTITUDE.yaw","unit",0.67895,0);
//        testTimerValue = true;
//    }
//}

void UASQuickTabView::setTableGeometry(){

    ui->tableWidget->resize(this->width(), this->height());

    ui->tableWidget->setColumnWidth(0, ((ui->tableWidget->width())/2));
    ui->tableWidget->setColumnWidth(1, ((ui->tableWidget->width())/2 + (ui->tableWidget->width())%2));

    int rowCount = ui->tableWidget->rowCount();
    for(int i = 0; i < rowCount - 1; i++) {

        ui->tableWidget->setRowHeight(i, (ui->tableWidget->height()) / rowCount);
        //ui->tableWidget->setRowHeight(i, (ui->tableWidget->height())/6);
    }
    ui->tableWidget->setRowHeight(rowCount - 1, ((ui->tableWidget->height()) / rowCount) + ((ui->tableWidget->height()) % rowCount));
}

QString UASQuickTabView::formText(QString name, double value){

    QString str;

    if(name == "M24:GLOBAL_POSITION_INT.lat"){
        if(value >= 0){
            str = QString::number(value,'f',5);
            str += 0x00B0;
             str += tr(" N");
        }
        else if(value < 0){
            value *=-1;
            str = QString::number(value,'f',5);
            str += 0x00B0;
            str += tr(" S");
        }
    }

    else if(name == "M24:GLOBAL_POSITION_INT.lon"){
        if(value >= 0){
            str = QString::number(value,'f',5);
            str += 0x00B0;
             str += tr(" E");
        }
        else if(value < 0){
            value *=-1;
            str = QString::number(value,'f',5);
            str += 0x00B0;
            str += tr(" W");
        }
    }

    else if(name == "M24:GLOBAL_POSITION_INT.alt"){
        str = QString::number(value,'f',1);
        str +=tr(" m.");
    }
    else if((name == "M24:ATTITUDE.roll")||(name == "M24:ATTITUDE.pitch")||(name == "M24:ATTITUDE.yaw")){
        str = QString::number(value,'f',2);
        str += 0x00B0;
    }
    return str;
}

void UASQuickTabView::resizeEvent(QResizeEvent *event){
    setTableGeometry();
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
 *   @author Andre Moreira Magalhaes <andre.magalhaes@collabora.co.uk>
 * Copyright (C) 2011 David Edmundson <kde@davidedmundson.co.uk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "sasl-auth-op.h"
#include "x-telepathy-password-auth-operation.h"

#include <TelepathyQt/PendingVariantMap>

#include <KDebug>
#include <KLocalizedString>

SaslAuthOp::SaslAuthOp(const Tp::AccountPtr &account,
        const Tp::ChannelPtr &channel)
    : Tp::PendingOperation(channel),
      m_account(account),
      m_channel(channel),
      m_saslIface(channel->interface<Tp::Client::ChannelInterfaceSASLAuthenticationInterface>())
{
    connect(m_saslIface->requestAllProperties(),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(gotProperties(Tp::PendingOperation*)));
}

SaslAuthOp::~SaslAuthOp()
{
}

void SaslAuthOp::gotProperties(Tp::PendingOperation *op)
{
    if (op->isError()) {
        kWarning() << "Unable to retrieve available SASL mechanisms";
        m_channel->requestClose();
        setFinishedWithError(op->errorName(), op->errorMessage());
        return;
    }

    Tp::PendingVariantMap *pvm = qobject_cast<Tp::PendingVariantMap*>(op);
    QVariantMap props = qdbus_cast<QVariantMap>(pvm->result());
    QStringList mechanisms = qdbus_cast<QStringList>(props.value("AvailableMechanisms"));
    kDebug() << mechanisms;

    if (mechanisms.contains(QLatin1String("X-TELEPATHY-PASSWORD"))) {
        // everything ok, we can return from handleChannels now
        emit ready(this);
        XTelepathyPasswordAuthOperation *authop = new XTelepathyPasswordAuthOperation(m_account, m_saslIface, qdbus_cast<bool>(props.value("CanTryAgain")));
        connect (authop, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAuthOperationFinished(Tp::PendingOperation*)));
        uint status = qdbus_cast<uint>(props.value("SASLStatus"));
        QString error = qdbus_cast<QString>(props.value("SASLError"));
        QVariantMap errorDetails = qdbus_cast<QVariantMap>(props.value("SASLErrorDetails"));
        authop->onSASLStatusChanged(status, error, errorDetails);
    } else {
        kWarning() << "X-TELEPATHY-PASSWORD is the only supported SASL mechanism and is not available:" << mechanisms;
        m_channel->requestClose();
        setFinishedWithError(TP_QT_ERROR_NOT_IMPLEMENTED,
                QLatin1String("X-TELEPATHY-PASSWORD is the only supported SASL mechanism and is not available"));
        return;
    }

}

void SaslAuthOp::onAuthOperationFinished(Tp::PendingOperation *op)
{
    m_channel->requestClose();
    if(op->isError()) {
        setFinishedWithError(op->errorName(), op->errorMessage());
    } else {
        setFinished();
    }
}

#include "sasl-auth-op.moc"
<commit_msg>Cleanup<commit_after>/*
 * Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
 *   @author Andre Moreira Magalhaes <andre.magalhaes@collabora.co.uk>
 * Copyright (C) 2011 David Edmundson <kde@davidedmundson.co.uk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "sasl-auth-op.h"
#include "x-telepathy-password-auth-operation.h"

#include <TelepathyQt/PendingVariantMap>

#include <KDebug>
#include <KLocalizedString>

SaslAuthOp::SaslAuthOp(const Tp::AccountPtr &account,
        const Tp::ChannelPtr &channel)
    : Tp::PendingOperation(channel),
      m_account(account),
      m_channel(channel),
      m_saslIface(channel->interface<Tp::Client::ChannelInterfaceSASLAuthenticationInterface>())
{
    connect(m_saslIface->requestAllProperties(),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(gotProperties(Tp::PendingOperation*)));
}

SaslAuthOp::~SaslAuthOp()
{
}

void SaslAuthOp::gotProperties(Tp::PendingOperation *op)
{
    if (op->isError()) {
        kWarning() << "Unable to retrieve available SASL mechanisms";
        m_channel->requestClose();
        setFinishedWithError(op->errorName(), op->errorMessage());
        return;
    }

    Tp::PendingVariantMap *pvm = qobject_cast<Tp::PendingVariantMap*>(op);
    QVariantMap props = qdbus_cast<QVariantMap>(pvm->result());
    QStringList mechanisms = qdbus_cast<QStringList>(props.value("AvailableMechanisms"));
    kDebug() << mechanisms;

    if (mechanisms.contains(QLatin1String("X-TELEPATHY-PASSWORD"))) {
        // everything ok, we can return from handleChannels now
        emit ready(this);
        XTelepathyPasswordAuthOperation *authop = new XTelepathyPasswordAuthOperation(m_account, m_saslIface, qdbus_cast<bool>(props.value("CanTryAgain")));
        connect (authop,
                 SIGNAL(finished(Tp::PendingOperation*)),
                 SLOT(onAuthOperationFinished(Tp::PendingOperation*)));
        uint status = qdbus_cast<uint>(props.value("SASLStatus"));
        QString error = qdbus_cast<QString>(props.value("SASLError"));
        QVariantMap errorDetails = qdbus_cast<QVariantMap>(props.value("SASLErrorDetails"));
        authop->onSASLStatusChanged(status, error, errorDetails);
    } else {
        kWarning() << "X-TELEPATHY-PASSWORD is the only supported SASL mechanism and is not available:" << mechanisms;
        m_channel->requestClose();
        setFinishedWithError(TP_QT_ERROR_NOT_IMPLEMENTED,
                QLatin1String("X-TELEPATHY-PASSWORD is the only supported SASL mechanism and is not available"));
        return;
    }
}

void SaslAuthOp::onAuthOperationFinished(Tp::PendingOperation *op)
{
    m_channel->requestClose();
    if(op->isError()) {
        setFinishedWithError(op->errorName(), op->errorMessage());
    } else {
        setFinished();
    }
}

#include "sasl-auth-op.moc"
<|endoftext|>


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

#include "Tests.h"

#include "IHistoryEntry.h"
#include "History.h"
#include "Media.h"

class HistoryTest : public Tests
{

};

TEST_F( HistoryTest, InsertMrl )
{
    ml->addToHistory( "upnp://stream" );
    auto hList = ml->history();
    ASSERT_EQ( 1u, hList.size() );
    auto h = hList[0];
    ASSERT_EQ( nullptr, h->media() );
    ASSERT_EQ( h->mrl(), "upnp://stream" );
    ASSERT_NE( 0u, h->insertionDate() );
}

TEST_F( HistoryTest, InsertMedia )
{
    auto media = ml->addFile( "media.mkv" );
    ml->addToHistory( media );
    auto hList = ml->history();
    ASSERT_EQ( 1u, hList.size() );
    auto h = hList[0];
    ASSERT_NE( nullptr, h->media() );
    ASSERT_EQ( media->id(), h->media()->id() );
    ASSERT_EQ( h->mrl(), "" );
    ASSERT_NE( 0u, h->insertionDate() );
}

TEST_F( HistoryTest, MaxEntries )
{
    for ( auto i = 0u; i < History::MaxEntries; ++i )
    {
        ml->addToHistory( std::to_string( i ) );
    }
    auto hList = ml->history();
    ASSERT_EQ( History::MaxEntries, hList.size() );
    ml->addToHistory( "new-media" );
    hList = ml->history();
    ASSERT_EQ( History::MaxEntries, hList.size() );
    ASSERT_EQ( "1", hList[99]->mrl() );
}

TEST_F( HistoryTest, Ordering )
{
    ml->addToHistory( "first-stream" );
    std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
    ml->addToHistory( "second-stream" );
    auto hList = ml->history();
    ASSERT_EQ( 2u, hList.size() );
    ASSERT_EQ( hList[0]->mrl(), "second-stream" );
    ASSERT_EQ( hList[1]->mrl(), "first-stream" );
}

TEST_F( HistoryTest, UpdateInsertionDate )
{
    ml->addToHistory( "stream" );
    auto hList = ml->history();
    ASSERT_EQ( 1u, hList.size() );
    auto date = hList[0]->insertionDate();
    std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
    ml->addToHistory( "stream" );
    hList = ml->history();
    ASSERT_EQ( 1u, hList.size() );
    ASSERT_NE( date, hList[0]->insertionDate() );
}

TEST_F( HistoryTest, DeleteMedia )
{
    auto m = ml->addFile( "media.mkv" );
    ml->addToHistory( m );
    auto hList = ml->history();
    ASSERT_EQ( 1u, hList.size() );
    auto f = m->files()[0];
    m->removeFile( static_cast<File&>( *f ) );
    hList = ml->history();
    ASSERT_EQ( 0u, hList.size() );
}
<commit_msg>HistoryTests: Remove impossible to predict assertion<commit_after>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#include "Tests.h"

#include "IHistoryEntry.h"
#include "History.h"
#include "Media.h"

class HistoryTest : public Tests
{

};

TEST_F( HistoryTest, InsertMrl )
{
    ml->addToHistory( "upnp://stream" );
    auto hList = ml->history();
    ASSERT_EQ( 1u, hList.size() );
    auto h = hList[0];
    ASSERT_EQ( nullptr, h->media() );
    ASSERT_EQ( h->mrl(), "upnp://stream" );
    ASSERT_NE( 0u, h->insertionDate() );
}

TEST_F( HistoryTest, InsertMedia )
{
    auto media = ml->addFile( "media.mkv" );
    ml->addToHistory( media );
    auto hList = ml->history();
    ASSERT_EQ( 1u, hList.size() );
    auto h = hList[0];
    ASSERT_NE( nullptr, h->media() );
    ASSERT_EQ( media->id(), h->media()->id() );
    ASSERT_EQ( h->mrl(), "" );
    ASSERT_NE( 0u, h->insertionDate() );
}

TEST_F( HistoryTest, MaxEntries )
{
    for ( auto i = 0u; i < History::MaxEntries; ++i )
    {
        ml->addToHistory( std::to_string( i ) );
    }
    auto hList = ml->history();
    ASSERT_EQ( History::MaxEntries, hList.size() );
    ml->addToHistory( "new-media" );
    hList = ml->history();
    ASSERT_EQ( History::MaxEntries, hList.size() );
}

TEST_F( HistoryTest, Ordering )
{
    ml->addToHistory( "first-stream" );
    std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
    ml->addToHistory( "second-stream" );
    auto hList = ml->history();
    ASSERT_EQ( 2u, hList.size() );
    ASSERT_EQ( hList[0]->mrl(), "second-stream" );
    ASSERT_EQ( hList[1]->mrl(), "first-stream" );
}

TEST_F( HistoryTest, UpdateInsertionDate )
{
    ml->addToHistory( "stream" );
    auto hList = ml->history();
    ASSERT_EQ( 1u, hList.size() );
    auto date = hList[0]->insertionDate();
    std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
    ml->addToHistory( "stream" );
    hList = ml->history();
    ASSERT_EQ( 1u, hList.size() );
    ASSERT_NE( date, hList[0]->insertionDate() );
}

TEST_F( HistoryTest, DeleteMedia )
{
    auto m = ml->addFile( "media.mkv" );
    ml->addToHistory( m );
    auto hList = ml->history();
    ASSERT_EQ( 1u, hList.size() );
    auto f = m->files()[0];
    m->removeFile( static_cast<File&>( *f ) );
    hList = ml->history();
    ASSERT_EQ( 0u, hList.size() );
}
<|endoftext|>


<commit_before>#include "gtest/gtest.h"

TEST(FooTest, HandleNoneZeroInput) {
  EXPECT_EQ(2, 2);
  EXPECT_EQ(6, 3 + 3);
}

int main(int argc, char *argv[]) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>unit test<commit_after>#include "gtest/gtest.h"
#include "socket.h"
#include "ioloop.h"

TEST(FooTest, HandleNoneZeroInput) {
  EXPECT_EQ(2, 2);
  EXPECT_EQ(6, 3 + 3);
}

#define SOCKET_CONTINER_CAPACITY 10

class SocketUnittest: public testing::Test {
  protected:
  virtual void SetUp() {
    m_io = NULL;
    memset(m_sockets, 0, sizeof(m_sockets));
  }
  virtual void TearDown() {
    m_io->Release();
    for (int i = 0; i < SOCKET_CONTINER_CAPACITY; ++i) {
      if (m_sockets[i]) {
        delete m_sockets[i];
        m_sockets[i] = NULL;
      }
      delete m_sockets;
    }
  }

  IOLoop* m_io;
  Socket* m_sockets[SOCKET_CONTINER_CAPACITY];
};

int main(int argc, char *argv[]) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "keystore.h"
#include "script.h"

bool CKeyStore::GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const
{
    CKey key;
    if (!GetKey(address, key))
        return false;
    vchPubKeyOut = key.GetPubKey();
    return true;
}

bool CBasicKeyStore::AddKey(const CKey& key)
{
    bool fCompressed = false;
    CSecret secret = key.GetSecret(fCompressed);
    {
        LOCK(cs_KeyStore);
        mapKeys[key.GetPubKey().GetID()] = make_pair(secret, fCompressed);
    }
    return true;
}

bool CBasicKeyStore::AddCScript(const CScript& redeemScript)
{
    {
        LOCK(cs_KeyStore);
        mapScripts[redeemScript.GetID()] = redeemScript;
    }
    return true;
}

bool CBasicKeyStore::HaveCScript(const CScriptID& hash) const
{
    bool result;
    {
        LOCK(cs_KeyStore);
        result = (mapScripts.count(hash) > 0);
    }
    return result;
}

bool CBasicKeyStore::GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const
{
    {
        LOCK(cs_KeyStore);
        ScriptMap::const_iterator mi = mapScripts.find(hash);
        if (mi != mapScripts.end())
        {
            redeemScriptOut = (*mi).second;
            return true;
        }
    }
    return false;
}

bool CCryptoKeyStore::SetCrypted()
{
    {
        LOCK(cs_KeyStore);
        if (fUseCrypto)
            return true;
        if (!mapKeys.empty())
            return false;
        fUseCrypto = true;
    }
    return true;
}

bool CCryptoKeyStore::Lock()
{
    if (!SetCrypted())
        return false;

    {
        LOCK(cs_KeyStore);
        vMasterKey.clear();
    }

    NotifyStatusChanged(this);
    return true;
}

bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
{
    {
        LOCK(cs_KeyStore);
        if (!SetCrypted())
            return false;

        CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
        for (; mi != mapCryptedKeys.end(); ++mi)
        {
            const CPubKey &vchPubKey = (*mi).second.first;
            const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
            CSecret vchSecret;
            if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
                return false;
            if (vchSecret.size() != 32)
                return false;
            CKey key;
            key.SetPubKey(vchPubKey);
            key.SetSecret(vchSecret);
            if (key.GetPubKey() == vchPubKey)
                break;
            return false;
        }
        vMasterKey = vMasterKeyIn;
    }
    NotifyStatusChanged(this);
    return true;
}

bool CCryptoKeyStore::AddKey(const CKey& key)
{
    {
        LOCK(cs_KeyStore);
        if (!IsCrypted())
            return CBasicKeyStore::AddKey(key);

        if (IsLocked())
            return false;

        std::vector<unsigned char> vchCryptedSecret;
        CPubKey vchPubKey = key.GetPubKey();
        bool fCompressed;
        if (!EncryptSecret(vMasterKey, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret))
            return false;

        if (!AddCryptedKey(key.GetPubKey(), vchCryptedSecret))
            return false;
    }
    return true;
}

bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
    {
        LOCK(cs_KeyStore);
        if (!SetCrypted())
            return false;

        mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
    }
    return true;
}

bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const
{
    {
        LOCK(cs_KeyStore);
        if (!IsCrypted())
            return CBasicKeyStore::GetKey(address, keyOut);

        CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
        if (mi != mapCryptedKeys.end())
        {
            const CPubKey &vchPubKey = (*mi).second.first;
            const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
            CSecret vchSecret;
            if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
                return false;
            if (vchSecret.size() != 32)
                return false;
            keyOut.SetPubKey(vchPubKey);
            keyOut.SetSecret(vchSecret);
            return true;
        }
    }
    return false;
}

bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
{
    {
        LOCK(cs_KeyStore);
        if (!IsCrypted())
            return CKeyStore::GetPubKey(address, vchPubKeyOut);

        CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
        if (mi != mapCryptedKeys.end())
        {
            vchPubKeyOut = (*mi).second.first;
            return true;
        }
    }
    return false;
}

bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
{
    {
        LOCK(cs_KeyStore);
        if (!mapCryptedKeys.empty() || IsCrypted())
            return false;

        fUseCrypto = true;
        BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys)
        {
            CKey key;
            if (!key.SetSecret(mKey.second.first, mKey.second.second))
                return false;
            const CPubKey vchPubKey = key.GetPubKey();
            std::vector<unsigned char> vchCryptedSecret;
            bool fCompressed;
            if (!EncryptSecret(vMasterKeyIn, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret))
                return false;
            if (!AddCryptedKey(vchPubKey, vchCryptedSecret))
                return false;
        }
        mapKeys.clear();
    }
    return true;
}
<commit_msg>Update to v3<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Copyright (c) 2013-2014 Memorycoin Dev Team
#include "keystore.h"
#include "script.h"

bool CKeyStore::GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const
{
    CKey key;
    if (!GetKey(address, key))
        return false;
    vchPubKeyOut = key.GetPubKey();
    return true;
}

bool CBasicKeyStore::AddKey(const CKey& key)
{
    bool fCompressed = false;
    CSecret secret = key.GetSecret(fCompressed);
    {
        LOCK(cs_KeyStore);
        mapKeys[key.GetPubKey().GetID()] = make_pair(secret, fCompressed);
    }
    return true;
}

bool CBasicKeyStore::AddCScript(const CScript& redeemScript)
{
    {
        LOCK(cs_KeyStore);
        mapScripts[redeemScript.GetID()] = redeemScript;
    }
    return true;
}

bool CBasicKeyStore::HaveCScript(const CScriptID& hash) const
{
    bool result;
    {
        LOCK(cs_KeyStore);
        result = (mapScripts.count(hash) > 0);
    }
    return result;
}

bool CBasicKeyStore::GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const
{
    {
        LOCK(cs_KeyStore);
        ScriptMap::const_iterator mi = mapScripts.find(hash);
        if (mi != mapScripts.end())
        {
            redeemScriptOut = (*mi).second;
            return true;
        }
    }
    return false;
}

bool CCryptoKeyStore::SetCrypted()
{
    {
        LOCK(cs_KeyStore);
        if (fUseCrypto)
            return true;
        if (!mapKeys.empty())
            return false;
        fUseCrypto = true;
    }
    return true;
}

bool CCryptoKeyStore::Lock()
{
    if (!SetCrypted())
        return false;

    {
        LOCK(cs_KeyStore);
        vMasterKey.clear();
    }

    NotifyStatusChanged(this);
    return true;
}

bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
{
    {
        LOCK(cs_KeyStore);
        if (!SetCrypted())
            return false;

        CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
        for (; mi != mapCryptedKeys.end(); ++mi)
        {
            const CPubKey &vchPubKey = (*mi).second.first;
            const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
            CSecret vchSecret;
            if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
                return false;
            if (vchSecret.size() != 32)
                return false;
            CKey key;
            key.SetPubKey(vchPubKey);
            key.SetSecret(vchSecret);
            if (key.GetPubKey() == vchPubKey)
                break;
            return false;
        }
        vMasterKey = vMasterKeyIn;
    }
    NotifyStatusChanged(this);
    return true;
}

bool CCryptoKeyStore::AddKey(const CKey& key)
{
    {
        LOCK(cs_KeyStore);
        if (!IsCrypted())
            return CBasicKeyStore::AddKey(key);

        if (IsLocked())
            return false;

        std::vector<unsigned char> vchCryptedSecret;
        CPubKey vchPubKey = key.GetPubKey();
        bool fCompressed;
        if (!EncryptSecret(vMasterKey, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret))
            return false;

        if (!AddCryptedKey(key.GetPubKey(), vchCryptedSecret))
            return false;
    }
    return true;
}

bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
    {
        LOCK(cs_KeyStore);
        if (!SetCrypted())
            return false;

        mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
    }
    return true;
}

bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const
{
    {
        LOCK(cs_KeyStore);
        if (!IsCrypted())
            return CBasicKeyStore::GetKey(address, keyOut);

        CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
        if (mi != mapCryptedKeys.end())
        {
            const CPubKey &vchPubKey = (*mi).second.first;
            const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
            CSecret vchSecret;
            if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
                return false;
            if (vchSecret.size() != 32)
                return false;
            keyOut.SetPubKey(vchPubKey);
            keyOut.SetSecret(vchSecret);
            return true;
        }
    }
    return false;
}

bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
{
    {
        LOCK(cs_KeyStore);
        if (!IsCrypted())
            return CKeyStore::GetPubKey(address, vchPubKeyOut);

        CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
        if (mi != mapCryptedKeys.end())
        {
            vchPubKeyOut = (*mi).second.first;
            return true;
        }
    }
    return false;
}

bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
{
    {
        LOCK(cs_KeyStore);
        if (!mapCryptedKeys.empty() || IsCrypted())
            return false;

        fUseCrypto = true;
        BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys)
        {
            CKey key;
            if (!key.SetSecret(mKey.second.first, mKey.second.second))
                return false;
            const CPubKey vchPubKey = key.GetPubKey();
            std::vector<unsigned char> vchCryptedSecret;
            bool fCompressed;
            if (!EncryptSecret(vMasterKeyIn, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret))
                return false;
            if (!AddCryptedKey(vchPubKey, vchCryptedSecret))
                return false;
        }
        mapKeys.clear();
    }
    return true;
}
<|endoftext|>


<commit_before>// $Id$

// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This 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

// C++ includes

// Local Includes
#include "mesh_base.h"
#include "elem.h"
#include "tree.h"
#include "point_locator_tree.h"
#include "mesh_tools.h"

//------------------------------------------------------------------
// PointLocator methods
PointLocatorTree::PointLocatorTree (const MeshBase& mesh,
				    const PointLocatorBase* master) :
  PointLocatorBase (mesh,master),
  _tree            (NULL),
  _element         (NULL),
  _out_of_mesh_mode(false)
{
  this->init(Trees::NODES);
}

PointLocatorTree::PointLocatorTree (const MeshBase& mesh,
				    const Trees::BuildType build_type,
				    const PointLocatorBase* master) :
  PointLocatorBase (mesh,master),
  _tree            (NULL),
  _element         (NULL),
  _out_of_mesh_mode(false)
{
  this->init(build_type);
}

PointLocatorTree::~PointLocatorTree ()
{
  this->clear ();
}

void PointLocatorTree::clear ()
{
  // only delete the tree when we are the master
  if (this->_tree != NULL)
    {
      if (this->_master == NULL)
	  // we own the tree
	  delete this->_tree;
      else
	  // someone else owns and therefore deletes the tree
	  this->_tree = NULL;
    }
}

void PointLocatorTree::init (const Trees::BuildType build_type)
{
  libmesh_assert (this->_tree == NULL);

  if (this->_initialized)
    {
      libMesh::err << "ERROR: Already initialized!  Will ignore this call..."
		    << std::endl;
    }

  else

    {

      if (this->_master == NULL)
        {
	  if (this->_mesh.mesh_dimension() == 3)
	    _tree = new Trees::OctTree (this->_mesh, 200, build_type);
	  else
	    {
	      // A 1D/2D mesh in 3D space needs special consideration.
	      // If the mesh is planar XY, we want to build a QuadTree
	      // to search efficiently.  If the mesh is truly a manifold,
	      // then we need an octree
	      bool is_planar_xy = false;

	      // Build the bounding box for the mesh.  If the delta-z bound is
	      // negligibly small then we can use a quadtree.
	      {
		MeshTools::BoundingBox bbox = MeshTools::bounding_box(this->_mesh);

		const Real
		  Dx = bbox.second(0) - bbox.first(0),
		  Dz = bbox.second(2) - bbox.first(2);

		if (std::abs(Dz/(Dx + 1.e-20)) < 1e-10)
		  is_planar_xy = true;
	      }

	      if (is_planar_xy)
		_tree = new Trees::QuadTree (this->_mesh, 200, build_type);
	      else
		_tree = new Trees::OctTree (this->_mesh, 200, build_type);
	    }
	}

      else

        {
	  // We are _not_ the master.  Let our Tree point to
	  // the master's tree.  But for this we first transform
	  // the master in a state for which we are friends.
	  // And make sure the master @e has a tree!
	  const PointLocatorTree* my_master =
	    libmesh_cast_ptr<const PointLocatorTree*>(this->_master);

	  if (my_master->initialized())
	    this->_tree = my_master->_tree;
	  else
	    {
	      libMesh::err << "ERROR: Initialize master first, then servants!"
			    << std::endl;
	      libmesh_error();
	    }
        }

      // Not all PointLocators may own a tree, but all of them
      // use their own element pointer.  Let the element pointer
      // be unique for every interpolator.
      // Suppose the interpolators are used concurrently
      // at different locations in the mesh, then it makes quite
      // sense to have unique start elements.
      this->_element = NULL;
    }

  // ready for take-off
  this->_initialized = true;
}

const Elem* PointLocatorTree::operator() (const Point& p) const
{
  libmesh_assert (this->_initialized);

  // First check the element from last time before asking the tree
  if (this->_element==NULL || !(this->_element->contains_point(p)))
    {
	// ask the tree
	this->_element = this->_tree->find_element (p);

	if (this->_element == NULL)
	  {
	    /* No element seems to contain this point.  If out-of-mesh
	       mode is enabled, just return NULL.  If not, however, we
	       have to perform a linear search before we call \p
	       libmesh_error() since in the case of curved elements, the
	       bounding box computed in \p TreeNode::insert(const
	       Elem*) might be slightly inaccurate.  */
	    if(!_out_of_mesh_mode)
	      {
		MeshBase::const_element_iterator       pos     = this->_mesh.active_elements_begin();
		const MeshBase::const_element_iterator end_pos = this->_mesh.active_elements_end();

		for ( ; pos != end_pos; ++pos)
		  if ((*pos)->contains_point(p))
		    return this->_element = (*pos);

		if (this->_element == NULL)
		  {
		    libMesh::err << std::endl
			          << " ******** Serious Problem.  Could not find an Element "
			          << "in the Mesh"
			          << std:: endl
			          << " ******** that contains the Point "
			          << p;
		    libmesh_error();
		  }
	      }
	  }
    }

  // the element should be active
  libmesh_assert (this->_element->active());

  // return the element
  return this->_element;
}

void PointLocatorTree::enable_out_of_mesh_mode (void)
{
  /* Out-of-mesh mode is currently only supported if all of the
     elements have affine mappings.  The reason is that for quadratic
     mappings, it is not easy to construct a relyable bounding box of
     the element, and thus, the fallback linear search in \p
     operator() is required.  Hence, out-of-mesh mode would be
     extremely slow.  */
  if(!_out_of_mesh_mode)
    {
#ifdef DEBUG
      MeshBase::const_element_iterator       pos     = this->_mesh.active_elements_begin();
      const MeshBase::const_element_iterator end_pos = this->_mesh.active_elements_end();
      for ( ; pos != end_pos; ++pos)
	if (!(*pos)->has_affine_map())
	  {
	    libMesh::err << "ERROR: Out-of-mesh mode is currently only supported if all elements have affine mappings." << std::endl;
	    libmesh_error();
	  }
#endif

      _out_of_mesh_mode = true;
    }
}

void PointLocatorTree::disable_out_of_mesh_mode (void)
{
  _out_of_mesh_mode = false;
}

<commit_msg>Fixed the overzealous assertion bug Yujie caught<commit_after>// $Id$

// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This 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

// C++ includes

// Local Includes
#include "mesh_base.h"
#include "elem.h"
#include "tree.h"
#include "point_locator_tree.h"
#include "mesh_tools.h"

//------------------------------------------------------------------
// PointLocator methods
PointLocatorTree::PointLocatorTree (const MeshBase& mesh,
				    const PointLocatorBase* master) :
  PointLocatorBase (mesh,master),
  _tree            (NULL),
  _element         (NULL),
  _out_of_mesh_mode(false)
{
  this->init(Trees::NODES);
}

PointLocatorTree::PointLocatorTree (const MeshBase& mesh,
				    const Trees::BuildType build_type,
				    const PointLocatorBase* master) :
  PointLocatorBase (mesh,master),
  _tree            (NULL),
  _element         (NULL),
  _out_of_mesh_mode(false)
{
  this->init(build_type);
}

PointLocatorTree::~PointLocatorTree ()
{
  this->clear ();
}

void PointLocatorTree::clear ()
{
  // only delete the tree when we are the master
  if (this->_tree != NULL)
    {
      if (this->_master == NULL)
	  // we own the tree
	  delete this->_tree;
      else
	  // someone else owns and therefore deletes the tree
	  this->_tree = NULL;
    }
}

void PointLocatorTree::init (const Trees::BuildType build_type)
{
  libmesh_assert (this->_tree == NULL);

  if (this->_initialized)
    {
      libMesh::err << "ERROR: Already initialized!  Will ignore this call..."
		    << std::endl;
    }

  else

    {

      if (this->_master == NULL)
        {
	  if (this->_mesh.mesh_dimension() == 3)
	    _tree = new Trees::OctTree (this->_mesh, 200, build_type);
	  else
	    {
	      // A 1D/2D mesh in 3D space needs special consideration.
	      // If the mesh is planar XY, we want to build a QuadTree
	      // to search efficiently.  If the mesh is truly a manifold,
	      // then we need an octree
	      bool is_planar_xy = false;

	      // Build the bounding box for the mesh.  If the delta-z bound is
	      // negligibly small then we can use a quadtree.
	      {
		MeshTools::BoundingBox bbox = MeshTools::bounding_box(this->_mesh);

		const Real
		  Dx = bbox.second(0) - bbox.first(0),
		  Dz = bbox.second(2) - bbox.first(2);

		if (std::abs(Dz/(Dx + 1.e-20)) < 1e-10)
		  is_planar_xy = true;
	      }

	      if (is_planar_xy)
		_tree = new Trees::QuadTree (this->_mesh, 200, build_type);
	      else
		_tree = new Trees::OctTree (this->_mesh, 200, build_type);
	    }
	}

      else

        {
	  // We are _not_ the master.  Let our Tree point to
	  // the master's tree.  But for this we first transform
	  // the master in a state for which we are friends.
	  // And make sure the master @e has a tree!
	  const PointLocatorTree* my_master =
	    libmesh_cast_ptr<const PointLocatorTree*>(this->_master);

	  if (my_master->initialized())
	    this->_tree = my_master->_tree;
	  else
	    {
	      libMesh::err << "ERROR: Initialize master first, then servants!"
			    << std::endl;
	      libmesh_error();
	    }
        }

      // Not all PointLocators may own a tree, but all of them
      // use their own element pointer.  Let the element pointer
      // be unique for every interpolator.
      // Suppose the interpolators are used concurrently
      // at different locations in the mesh, then it makes quite
      // sense to have unique start elements.
      this->_element = NULL;
    }

  // ready for take-off
  this->_initialized = true;
}

const Elem* PointLocatorTree::operator() (const Point& p) const
{
  libmesh_assert (this->_initialized);

  // First check the element from last time before asking the tree
  if (this->_element==NULL || !(this->_element->contains_point(p)))
    {
	// ask the tree
	this->_element = this->_tree->find_element (p);

	if (this->_element == NULL)
	  {
	    /* No element seems to contain this point.  If out-of-mesh
	       mode is enabled, just return NULL.  If not, however, we
	       have to perform a linear search before we call \p
	       libmesh_error() since in the case of curved elements, the
	       bounding box computed in \p TreeNode::insert(const
	       Elem*) might be slightly inaccurate.  */
	    if(!_out_of_mesh_mode)
	      {
		MeshBase::const_element_iterator       pos     = this->_mesh.active_elements_begin();
		const MeshBase::const_element_iterator end_pos = this->_mesh.active_elements_end();

		for ( ; pos != end_pos; ++pos)
		  if ((*pos)->contains_point(p))
		    return this->_element = (*pos);

		if (this->_element == NULL)
		  {
		    libMesh::err << std::endl
			          << " ******** Serious Problem.  Could not find an Element "
			          << "in the Mesh"
			          << std:: endl
			          << " ******** that contains the Point "
			          << p;
		    libmesh_error();
		  }
	      }
	  }
    }

  // If we found an element, it should be active
  libmesh_assert (!this->_element || this->_element->active());

  // return the element
  return this->_element;
}

void PointLocatorTree::enable_out_of_mesh_mode (void)
{
  /* Out-of-mesh mode is currently only supported if all of the
     elements have affine mappings.  The reason is that for quadratic
     mappings, it is not easy to construct a relyable bounding box of
     the element, and thus, the fallback linear search in \p
     operator() is required.  Hence, out-of-mesh mode would be
     extremely slow.  */
  if(!_out_of_mesh_mode)
    {
#ifdef DEBUG
      MeshBase::const_element_iterator       pos     = this->_mesh.active_elements_begin();
      const MeshBase::const_element_iterator end_pos = this->_mesh.active_elements_end();
      for ( ; pos != end_pos; ++pos)
	if (!(*pos)->has_affine_map())
	  {
	    libMesh::err << "ERROR: Out-of-mesh mode is currently only supported if all elements have affine mappings." << std::endl;
	    libmesh_error();
	  }
#endif

      _out_of_mesh_mode = true;
    }
}

void PointLocatorTree::disable_out_of_mesh_mode (void)
{
  _out_of_mesh_mode = false;
}

<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* 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 "LibVirtDriver.h"

#include "Nebula.h"
#include <sstream>
#include <fstream>
#include <libgen.h>

/* ************************************************************************** */
/* Virtual Network :: Database Access Functions                               */
/* ************************************************************************** */

const char * LibVirtDriver::vmware_vnm_name = "vmware";

int LibVirtDriver::deployment_description_vmware(
        const VirtualMachine *  vm,
        const string&           file_name) const
{
    ofstream                    file;

    int                         num;
    vector<const Attribute *>   attrs;

    string  vcpu;
    string  memory;

    int     memory_in_kb = 0;

    string  arch       = "";

    const VectorAttribute * disk;
    const VectorAttribute * context;

    string  type       = "";
    string  target     = "";
    string  bus        = "";
    string  ro         = "";
    string  source     = "";
    string  datastore  = "";
    string  driver     = "";
    string  default_driver = "";
    bool    readonly;

    const VectorAttribute * nic;

    string  network_id = "";
    string  mac        = "";
    string  bridge     = "";
    string  script     = "";
    string  model      = "";

    const VectorAttribute * raw;
    string data;

    // ------------------------------------------------------------------------

    file.open(file_name.c_str(), ios::out);

    if (file.fail() == true)
    {
        goto error_vmware_file;
    }

    // ------------------------------------------------------------------------
    // Starting XML document
    // ------------------------------------------------------------------------

    file << "<domain type='" << emulator << "'>" << endl;

    // ------------------------------------------------------------------------
    // Domain name
    // ------------------------------------------------------------------------

    file << "\t<name>one-" << vm->get_oid() << "</name>" << endl;

    // ------------------------------------------------------------------------
    // CPU
    // ------------------------------------------------------------------------

    vm->get_template_attribute("VCPU", vcpu);

    if(vcpu.empty())
    {
        get_default("VCPU", vcpu);
    }

    if (!vcpu.empty())
    {
        file << "\t<vcpu>" << vcpu << "</vcpu>" << endl;
    }

    // ------------------------------------------------------------------------
    // Memory
    // ------------------------------------------------------------------------

    vm->get_template_attribute("MEMORY",memory);

    if (memory.empty())
    {
        get_default("MEMORY",memory);
    }

    if (!memory.empty())
    {
        memory_in_kb = atoi(memory.c_str()) * 1024;

        file << "\t<memory>" << memory_in_kb << "</memory>" << endl;
    }
    else
    {
        goto error_vmware_memory;
    }

    // ------------------------------------------------------------------------
    //  OS and boot options
    // ------------------------------------------------------------------------

    num = vm->get_template_attribute("OS",attrs);

    // Get values & defaults
    if ( num > 0 )
    {
        const VectorAttribute * os;

        os = dynamic_cast<const VectorAttribute *>(attrs[0]);

        if( os != 0 )
        {
            arch = os->vector_value("ARCH");
        }
    }

    if ( arch.empty() )
    {
        get_default("OS","ARCH",arch);

        if (arch.empty())
        {
            goto error_vmware_arch;
        }
    }

    // Start writing to the file with the info we got

    file << "\t<os>" << endl;

    file << "\t\t<type arch='" << arch << "'>hvm</type>" << endl;

    file << "\t</os>" << endl;

    attrs.clear();

    // ------------------------------------------------------------------------
    // Disks
    // ------------------------------------------------------------------------

    file << "\t<devices>" << endl;

    get_default("DISK","DRIVER",default_driver);

    num = vm->get_template_attribute("DISK",attrs);

    if (num!=0)
    {
        get_default("DATASTORE", datastore);
    }

    for (int i=0; i < num ;i++)
    {
        disk = dynamic_cast<const VectorAttribute *>(attrs[i]);

        if ( disk == 0 )
        {
         continue;
        }

        type   = disk->vector_value("TYPE");
        target = disk->vector_value("TARGET");
        ro     = disk->vector_value("READONLY");
        bus    = disk->vector_value("BUS");
        source = disk->vector_value("SOURCE");
        driver = disk->vector_value("DRIVER");

        if (target.empty())
        {
            goto error_vmware_disk;
        }

        readonly = false;

        if ( !ro.empty() )
        {
            transform(ro.begin(),ro.end(),ro.begin(),(int(*)(int))toupper);

            if ( ro == "YES" )
            {
                readonly = true;
            }
        }

        if (type.empty() == false)
        {
            transform(type.begin(),type.end(),type.begin(),(int(*)(int))toupper);
        }

        if ( type == "BLOCK" )
        {
            file << "\t\t<disk type='block' device='disk'>" << endl;
            file << "\t\t\t<source file=[" <<  datastore << "] " << vm->get_oid()
                << "/images/disk."  << i << "'/>"  << endl;
        }
        else if ( type == "CDROM" )
        {
            file << "\t\t<disk type='file' device='cdrom'>" << endl;
            file << "\t\t\t<source file=[" <<  datastore << "] " << vm->get_oid()
                << "/images/disk."  << i << ".iso'/>"  << endl;
        }
        else
        {
            file << "\t\t<disk type='file' device='disk'>" << endl
                 << "\t\t\t<source file='[" <<  datastore <<"] " << vm->get_oid()
                 << "/images/disk." << i << "/disk.vmdk'/>" << endl;
        }

        file << "\t\t\t<target dev='" << target << "'";

        if (!bus.empty())
        {
            file << " bus='" << bus << "'/>" << endl;
        }
        else
        {
            file << "/>" << endl;
        }

        if ( !driver.empty() )
        {
            file << "\t\t\t<driver name='" << driver << "'/>" << endl;
        }
        else
        {
            if (!default_driver.empty())
            {
                file << "\t\t\t<driver name='" <<
                        default_driver << "'/>" << endl;
            }
        }

        if (readonly)
        {
            file << "\t\t\t<readonly/>" << endl;
        }

        file << "\t\t</disk>" << endl;
    }

    attrs.clear();

    // ------------------------------------------------------------------------
    // Context Device
    // ------------------------------------------------------------------------

    if ( vm->get_template_attribute("CONTEXT",attrs) == 1 )
    {
        context = dynamic_cast<const VectorAttribute *>(attrs[0]);
        target  = context->vector_value("TARGET");

        if ( !target.empty() )
        {
            file << "\t\t<disk type='file' device='cdrom'>" << endl;
            file << "\t\t\t<source file='[" <<  datastore <<"] " << vm->get_oid()
                 << "/disk." << num << ".iso'/>" << endl;
            file << "\t\t\t<target dev='" << target << "'/>" << endl;
            file << "\t\t\t<readonly/>" << endl;
            file << "\t\t</disk>" << endl;
        }
        else
        {
            vm->log("VMM", Log::WARNING, "Could not find target device to"
                " attach context, will continue without it.");
        }
    }

    attrs.clear();

    // ------------------------------------------------------------------------
    // Network interfaces
    // ------------------------------------------------------------------------

    num = vm->get_template_attribute("NIC",attrs);

    for(int i=0; i<num; i++)
    {
        nic = dynamic_cast<const VectorAttribute *>(attrs[i]);

        if ( nic == 0 )
        {
            continue;
        }

        network_id = nic->vector_value("NETWORK_ID");
        mac        = nic->vector_value("MAC");
        target     = nic->vector_value("TARGET");
        script     = nic->vector_value("SCRIPT");
        model      = nic->vector_value("MODEL");

        bridge     = "one-pg-";
        bridge.append(network_id);

        file << "\t\t<interface type='bridge'>" << endl;
        file << "\t\t\t<source bridge='" << bridge << "'/>" << endl;

        if( !mac.empty() )
        {
            file << "\t\t\t<mac address='" << mac << "'/>" << endl;
        }

        if( !target.empty() )
        {
            file << "\t\t\t<target dev='" << target << "'/>" << endl;
        }

        if( !script.empty() )
        {
            file << "\t\t\t<script path='" << script << "'/>" << endl;
        }

        if( !model.empty() )
        {
            file << "\t\t\t<model type='" << model << "'/>" << endl;
        }

        file << "\t\t</interface>" << endl;

    }

    attrs.clear();

    file << "\t</devices>" << endl;

    // ------------------------------------------------------------------------
    // Raw VMware attributes
    // ------------------------------------------------------------------------

    num = vm->get_template_attribute("RAW",attrs);

    for(int i=0; i<num;i++)
    {
        raw = dynamic_cast<const VectorAttribute *>(attrs[i]);

        if ( raw == 0 )
        {
            continue;
        }

        type = raw->vector_value("TYPE");

        transform(type.begin(),type.end(),type.begin(),(int(*)(int))toupper);

        if ( type == "VMWARE" )
        {
            data = raw->vector_value("DATA");
            file << "\t" << data << endl;
        }
    }

    file << "</domain>" << endl;

    file.close();

    return 0;

error_vmware_file:
    vm->log("VMM", Log::ERROR, "Could not open VMWARE deployment file.");
    return -1;

error_vmware_arch:
    vm->log("VMM", Log::ERROR, "No ARCH defined and no default provided.");
    file.close();
    return -1;

error_vmware_memory:
    vm->log("VMM", Log::ERROR, "No MEMORY defined and no default provided.");
    file.close();
    return -1;

error_vmware_disk:
    vm->log("VMM", Log::ERROR, "Wrong target value in DISK.");
    file.close();
    return -1;
}
<commit_msg>feature #1020: VMware networking traditional method also supported (dummy drivers)<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* 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 "LibVirtDriver.h"

#include "Nebula.h"
#include <sstream>
#include <fstream>
#include <libgen.h>

/* ************************************************************************** */
/* Virtual Network :: Database Access Functions                               */
/* ************************************************************************** */

const char * LibVirtDriver::vmware_vnm_name = "vmware";

int LibVirtDriver::deployment_description_vmware(
        const VirtualMachine *  vm,
        const string&           file_name) const
{
    ofstream                    file;

    int                         num;
    vector<const Attribute *>   attrs;

    string  vcpu;
    string  memory;

    int     memory_in_kb = 0;

    string  arch       = "";

    const VectorAttribute * disk;
    const VectorAttribute * context;

    string  type       = "";
    string  target     = "";
    string  bus        = "";
    string  ro         = "";
    string  source     = "";
    string  datastore  = "";
    string  driver     = "";
    string  default_driver = "";
    bool    readonly;

    const VectorAttribute * nic;

    string  network_id = "";
    string  mac        = "";
    string  bridge     = "";
    string  script     = "";
    string  model      = "";

    const VectorAttribute * raw;
    string data;

    // ------------------------------------------------------------------------

    file.open(file_name.c_str(), ios::out);

    if (file.fail() == true)
    {
        goto error_vmware_file;
    }

    // ------------------------------------------------------------------------
    // Starting XML document
    // ------------------------------------------------------------------------

    file << "<domain type='" << emulator << "'>" << endl;

    // ------------------------------------------------------------------------
    // Domain name
    // ------------------------------------------------------------------------

    file << "\t<name>one-" << vm->get_oid() << "</name>" << endl;

    // ------------------------------------------------------------------------
    // CPU
    // ------------------------------------------------------------------------

    vm->get_template_attribute("VCPU", vcpu);

    if(vcpu.empty())
    {
        get_default("VCPU", vcpu);
    }

    if (!vcpu.empty())
    {
        file << "\t<vcpu>" << vcpu << "</vcpu>" << endl;
    }

    // ------------------------------------------------------------------------
    // Memory
    // ------------------------------------------------------------------------

    vm->get_template_attribute("MEMORY",memory);

    if (memory.empty())
    {
        get_default("MEMORY",memory);
    }

    if (!memory.empty())
    {
        memory_in_kb = atoi(memory.c_str()) * 1024;

        file << "\t<memory>" << memory_in_kb << "</memory>" << endl;
    }
    else
    {
        goto error_vmware_memory;
    }

    // ------------------------------------------------------------------------
    //  OS and boot options
    // ------------------------------------------------------------------------

    num = vm->get_template_attribute("OS",attrs);

    // Get values & defaults
    if ( num > 0 )
    {
        const VectorAttribute * os;

        os = dynamic_cast<const VectorAttribute *>(attrs[0]);

        if( os != 0 )
        {
            arch = os->vector_value("ARCH");
        }
    }

    if ( arch.empty() )
    {
        get_default("OS","ARCH",arch);

        if (arch.empty())
        {
            goto error_vmware_arch;
        }
    }

    // Start writing to the file with the info we got

    file << "\t<os>" << endl;

    file << "\t\t<type arch='" << arch << "'>hvm</type>" << endl;

    file << "\t</os>" << endl;

    attrs.clear();

    // ------------------------------------------------------------------------
    // Disks
    // ------------------------------------------------------------------------

    file << "\t<devices>" << endl;

    get_default("DISK","DRIVER",default_driver);

    num = vm->get_template_attribute("DISK",attrs);

    if (num!=0)
    {
        get_default("DATASTORE", datastore);
    }

    for (int i=0; i < num ;i++)
    {
        disk = dynamic_cast<const VectorAttribute *>(attrs[i]);

        if ( disk == 0 )
        {
         continue;
        }

        type   = disk->vector_value("TYPE");
        target = disk->vector_value("TARGET");
        ro     = disk->vector_value("READONLY");
        bus    = disk->vector_value("BUS");
        source = disk->vector_value("SOURCE");
        driver = disk->vector_value("DRIVER");

        if (target.empty())
        {
            goto error_vmware_disk;
        }

        readonly = false;

        if ( !ro.empty() )
        {
            transform(ro.begin(),ro.end(),ro.begin(),(int(*)(int))toupper);

            if ( ro == "YES" )
            {
                readonly = true;
            }
        }

        if (type.empty() == false)
        {
            transform(type.begin(),type.end(),type.begin(),(int(*)(int))toupper);
        }

        if ( type == "BLOCK" )
        {
            file << "\t\t<disk type='block' device='disk'>" << endl;
            file << "\t\t\t<source file=[" <<  datastore << "] " << vm->get_oid()
                << "/images/disk."  << i << "'/>"  << endl;
        }
        else if ( type == "CDROM" )
        {
            file << "\t\t<disk type='file' device='cdrom'>" << endl;
            file << "\t\t\t<source file=[" <<  datastore << "] " << vm->get_oid()
                << "/images/disk."  << i << ".iso'/>"  << endl;
        }
        else
        {
            file << "\t\t<disk type='file' device='disk'>" << endl
                 << "\t\t\t<source file='[" <<  datastore <<"] " << vm->get_oid()
                 << "/images/disk." << i << "/disk.vmdk'/>" << endl;
        }

        file << "\t\t\t<target dev='" << target << "'";

        if (!bus.empty())
        {
            file << " bus='" << bus << "'/>" << endl;
        }
        else
        {
            file << "/>" << endl;
        }

        if ( !driver.empty() )
        {
            file << "\t\t\t<driver name='" << driver << "'/>" << endl;
        }
        else
        {
            if (!default_driver.empty())
            {
                file << "\t\t\t<driver name='" <<
                        default_driver << "'/>" << endl;
            }
        }

        if (readonly)
        {
            file << "\t\t\t<readonly/>" << endl;
        }

        file << "\t\t</disk>" << endl;
    }

    attrs.clear();

    // ------------------------------------------------------------------------
    // Context Device
    // ------------------------------------------------------------------------

    if ( vm->get_template_attribute("CONTEXT",attrs) == 1 )
    {
        context = dynamic_cast<const VectorAttribute *>(attrs[0]);
        target  = context->vector_value("TARGET");

        if ( !target.empty() )
        {
            file << "\t\t<disk type='file' device='cdrom'>" << endl;
            file << "\t\t\t<source file='[" <<  datastore <<"] " << vm->get_oid()
                 << "/disk." << num << ".iso'/>" << endl;
            file << "\t\t\t<target dev='" << target << "'/>" << endl;
            file << "\t\t\t<readonly/>" << endl;
            file << "\t\t</disk>" << endl;
        }
        else
        {
            vm->log("VMM", Log::WARNING, "Could not find target device to"
                " attach context, will continue without it.");
        }
    }

    attrs.clear();

    // ------------------------------------------------------------------------
    // Network interfaces
    // ------------------------------------------------------------------------

    num = vm->get_template_attribute("NIC",attrs);

    for(int i=0; i<num; i++)
    {
        nic = dynamic_cast<const VectorAttribute *>(attrs[i]);

        if ( nic == 0 )
        {
            continue;
        }

        network_id = nic->vector_value("NETWORK_ID");
        mac        = nic->vector_value("MAC");
        target     = nic->vector_value("TARGET");
        script     = nic->vector_value("SCRIPT");
        model      = nic->vector_value("MODEL");

        if (vm->get_vnm_mad() == LibVirtDriver::vmware_vnm_name)
        {
            bridge = "one-pg-";
            bridge.append(network_id);
        }
        else
        {
            bridge = nic->vector_value("BRIDGE");
        }

        file << "\t\t<interface type='bridge'>" << endl;
        file << "\t\t\t<source bridge='" << bridge << "'/>" << endl;

        if( !mac.empty() )
        {
            file << "\t\t\t<mac address='" << mac << "'/>" << endl;
        }

        if( !target.empty() )
        {
            file << "\t\t\t<target dev='" << target << "'/>" << endl;
        }

        if( !script.empty() )
        {
            file << "\t\t\t<script path='" << script << "'/>" << endl;
        }

        if( !model.empty() )
        {
            file << "\t\t\t<model type='" << model << "'/>" << endl;
        }

        file << "\t\t</interface>" << endl;

    }

    attrs.clear();

    file << "\t</devices>" << endl;

    // ------------------------------------------------------------------------
    // Raw VMware attributes
    // ------------------------------------------------------------------------

    num = vm->get_template_attribute("RAW",attrs);

    for(int i=0; i<num;i++)
    {
        raw = dynamic_cast<const VectorAttribute *>(attrs[i]);

        if ( raw == 0 )
        {
            continue;
        }

        type = raw->vector_value("TYPE");

        transform(type.begin(),type.end(),type.begin(),(int(*)(int))toupper);

        if ( type == "VMWARE" )
        {
            data = raw->vector_value("DATA");
            file << "\t" << data << endl;
        }
    }

    file << "</domain>" << endl;

    file.close();

    return 0;

error_vmware_file:
    vm->log("VMM", Log::ERROR, "Could not open VMWARE deployment file.");
    return -1;

error_vmware_arch:
    vm->log("VMM", Log::ERROR, "No ARCH defined and no default provided.");
    file.close();
    return -1;

error_vmware_memory:
    vm->log("VMM", Log::ERROR, "No MEMORY defined and no default provided.");
    file.close();
    return -1;

error_vmware_disk:
    vm->log("VMM", Log::ERROR, "Wrong target value in DISK.");
    file.close();
    return -1;
}
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Hunspell, based on MySpell.
 *
 * The Initial Developers of the Original Code are
 * Kevin Hendricks (MySpell) and Németh László (Hunspell).
 * Portions created by the Initial Developers are Copyright (C) 2002-2005
 * the Initial Developers. All Rights Reserved.
 *
 * Contributor(s): David Einstein, Davide Prina, Giuseppe Modugno,
 * Gianluca Turconi, Simon Brouwer, Noll János, Bíró Árpád,
 * Goldman Eleonóra, Sarlós Tamás, Bencsáth Boldizsár, Halácsy Péter,
 * Dvornik László, Gefferth András, Nagy Viktor, Varga Dániel, Chris Halls,
 * Rene Engelhard, Bram Moolenaar, Dafydd Jones, Harri Pitkänen
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#ifndef _ATYPES_HXX_
#define _ATYPES_HXX_

#ifndef HUNSPELL_WARNING
#include <stdio.h>
#ifdef HUNSPELL_WARNING_ON
#define HUNSPELL_WARNING fprintf
#else
// empty inline function to switch off warnings (instead of the C99 standard
// variadic macros)
static inline void HUNSPELL_WARNING(FILE*, const char*, ...) {}
#endif
#endif

// HUNSTEM def.
#define HUNSTEM

#include "hashmgr.hxx"
#include "w_char.hxx"
#include <algorithm>
#include <string>

#define SETSIZE 256
#define CONTSIZE 65536

// AffEntry options
#define aeXPRODUCT (1 << 0)
#define aeUTF8 (1 << 1)
#define aeALIASF (1 << 2)
#define aeALIASM (1 << 3)
#define aeLONGCOND (1 << 4)

// compound options
#define IN_CPD_NOT 0
#define IN_CPD_BEGIN 1
#define IN_CPD_END 2
#define IN_CPD_OTHER 3

// info options
#define SPELL_COMPOUND (1 << 0)
#define SPELL_FORBIDDEN (1 << 1)
#define SPELL_ALLCAP (1 << 2)
#define SPELL_NOCAP (1 << 3)
#define SPELL_INITCAP (1 << 4)
#define SPELL_ORIGCAP (1 << 5)
#define SPELL_WARN (1 << 6)

#define MAXLNLEN 8192

#define MINCPDLEN 3
#define MAXCOMPOUND 10
#define MAXCONDLEN 20
#define MAXCONDLEN_1 (MAXCONDLEN - sizeof(char*))

#define MAXACC 1000

#define FLAG unsigned short
#define FLAG_NULL 0x00
#define FREE_FLAG(a) a = 0

#define TESTAFF(a, b, c) (std::binary_search(a, a + c, b))

struct guessword {
  char* word;
  bool allow;
  char* orig;
};

typedef std::vector<std::string> mapentry;
typedef std::vector<FLAG> flagentry;

struct patentry {
  std::string pattern;
  std::string pattern2;
  std::string pattern3;
  FLAG cond;
  FLAG cond2;
  patentry()
    : cond(FLAG_NULL)
    , cond2(FLAG_NULL) {
  }
};

#endif
<commit_msg>MAXLNLEN removed from library constraints<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Hunspell, based on MySpell.
 *
 * The Initial Developers of the Original Code are
 * Kevin Hendricks (MySpell) and Németh László (Hunspell).
 * Portions created by the Initial Developers are Copyright (C) 2002-2005
 * the Initial Developers. All Rights Reserved.
 *
 * Contributor(s): David Einstein, Davide Prina, Giuseppe Modugno,
 * Gianluca Turconi, Simon Brouwer, Noll János, Bíró Árpád,
 * Goldman Eleonóra, Sarlós Tamás, Bencsáth Boldizsár, Halácsy Péter,
 * Dvornik László, Gefferth András, Nagy Viktor, Varga Dániel, Chris Halls,
 * Rene Engelhard, Bram Moolenaar, Dafydd Jones, Harri Pitkänen
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#ifndef _ATYPES_HXX_
#define _ATYPES_HXX_

#ifndef HUNSPELL_WARNING
#include <stdio.h>
#ifdef HUNSPELL_WARNING_ON
#define HUNSPELL_WARNING fprintf
#else
// empty inline function to switch off warnings (instead of the C99 standard
// variadic macros)
static inline void HUNSPELL_WARNING(FILE*, const char*, ...) {}
#endif
#endif

// HUNSTEM def.
#define HUNSTEM

#include "hashmgr.hxx"
#include "w_char.hxx"
#include <algorithm>
#include <string>

#define SETSIZE 256
#define CONTSIZE 65536

// AffEntry options
#define aeXPRODUCT (1 << 0)
#define aeUTF8 (1 << 1)
#define aeALIASF (1 << 2)
#define aeALIASM (1 << 3)
#define aeLONGCOND (1 << 4)

// compound options
#define IN_CPD_NOT 0
#define IN_CPD_BEGIN 1
#define IN_CPD_END 2
#define IN_CPD_OTHER 3

// info options
#define SPELL_COMPOUND (1 << 0)
#define SPELL_FORBIDDEN (1 << 1)
#define SPELL_ALLCAP (1 << 2)
#define SPELL_NOCAP (1 << 3)
#define SPELL_INITCAP (1 << 4)
#define SPELL_ORIGCAP (1 << 5)
#define SPELL_WARN (1 << 6)

#define MINCPDLEN 3
#define MAXCOMPOUND 10
#define MAXCONDLEN 20
#define MAXCONDLEN_1 (MAXCONDLEN - sizeof(char*))

#define MAXACC 1000

#define FLAG unsigned short
#define FLAG_NULL 0x00
#define FREE_FLAG(a) a = 0

#define TESTAFF(a, b, c) (std::binary_search(a, a + c, b))

struct guessword {
  char* word;
  bool allow;
  char* orig;
};

typedef std::vector<std::string> mapentry;
typedef std::vector<FLAG> flagentry;

struct patentry {
  std::string pattern;
  std::string pattern2;
  std::string pattern3;
  FLAG cond;
  FLAG cond2;
  patentry()
    : cond(FLAG_NULL)
    , cond2(FLAG_NULL) {
  }
};

#endif
<|endoftext|>