<commit_before>#include "ribbonanalysis.h"
#include "ui_ribbonanalysis.h"

#include <QMenu>
#include <QDebug>

RibbonAnalysis::RibbonAnalysis(QWidget *parent) :
	RibbonWidget(parent),
	ui(new Ui::RibbonAnalysis)
{
	ui->setupUi(this);

	ui->bayesianPanel->hide();
	//ui->bayesianSeparator->hide();

	connect(ui->Descriptives, SIGNAL(clicked()), this, SLOT(itemSelected()));

	QMenu *menu;

	menu = new QMenu(this);
	menu->addAction(QString("Independent Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestIndependentSamples");
	menu->addAction(QString("Paired Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestPairedSamples");
	menu->addAction(QString("One Sample T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestOneSample");

	menu->addSeparator();

	menu->addAction(QString("Bayesian Independent Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestBayesianIndependentSamples");
	menu->addAction(QString("Bayesian Paired Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestBayesianPairedSamples");
	menu->addAction(QString("Bayesian One Sample T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestBayesianOneSample");

	ui->classicalTTestButton->setMenu(menu);

	menu = new QMenu(this);

	menu->addAction(QString("ANOVA"), this, SLOT(itemSelected()))->setObjectName("Anova");
	menu->addAction(QString("Repeated Measures ANOVA"), this, SLOT(itemSelected()))->setObjectName("AnovaRepeatedMeasuresShort");
	menu->addAction(QString("ANCOVA"), this, SLOT(itemSelected()))->setObjectName("Ancova");

	menu->addSeparator();

	menu->addAction(QString("Bayesian ANOVA"), this, SLOT(itemSelected()))->setObjectName("AnovaBayesian");
	menu->addAction(QString("Bayesian Repeated Measures ANOVA"), this, SLOT(itemSelected()))->setObjectName("AnovaRepeatedMeasuresBayesian");
	menu->addAction(QString("Bayesian ANCOVA"), this, SLOT(itemSelected()))->setObjectName("AncovaBayesian");

	ui->classicalAnovaButton->setMenu(menu);

	menu = new QMenu(this);

	menu->addAction(QString("Correlation Matrix"), this, SLOT(itemSelected()))->setObjectName("Correlation");
#ifdef QT_DEBUG
	menu->addAction(QString("Partial Correlation"), this, SLOT(itemSelected()))->setObjectName("CorrelationPartial");
#endif
	menu->addAction(QString("Linear Regression"), this, SLOT(itemSelected()))->setObjectName("RegressionLinear");

	menu->addSeparator();

	menu->addAction(QString("Bayesian Correlation Matrix"), this, SLOT(itemSelected()))->setObjectName("CorrelationBayesian");
#ifdef QT_DEBUG
	menu->addAction(QString("Bayesian Correlation Pairs"), this, SLOT(itemSelected()))->setObjectName("CorrelationBayesianPairs");
#endif
	menu->addAction(QString("Bayesian Linear Regression"), this, SLOT(itemSelected()))->setObjectName("RegressionLinearBayesian");

	ui->classicalRegressionButton->setMenu(menu);

	menu = new QMenu(this);

	menu->addAction(QString("Contingency Tables"), this, SLOT(itemSelected()))->setObjectName("Crosstabs");
	menu->addSeparator();
	menu->addAction(QString("Bayesian Contingency Tables"), this, SLOT(itemSelected()))->setObjectName("CrosstabsBayesian");

	ui->classicalCrosstabsButton->setMenu(menu);
}

RibbonAnalysis::~RibbonAnalysis()
{
	delete ui;
}
<commit_msg>B Corr. Pairs: Enabling in release<commit_after>#include "ribbonanalysis.h"
#include "ui_ribbonanalysis.h"

#include <QMenu>
#include <QDebug>

RibbonAnalysis::RibbonAnalysis(QWidget *parent) :
	RibbonWidget(parent),
	ui(new Ui::RibbonAnalysis)
{
	ui->setupUi(this);

	ui->bayesianPanel->hide();
	//ui->bayesianSeparator->hide();

	connect(ui->Descriptives, SIGNAL(clicked()), this, SLOT(itemSelected()));

	QMenu *menu;

	menu = new QMenu(this);
	menu->addAction(QString("Independent Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestIndependentSamples");
	menu->addAction(QString("Paired Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestPairedSamples");
	menu->addAction(QString("One Sample T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestOneSample");

	menu->addSeparator();

	menu->addAction(QString("Bayesian Independent Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestBayesianIndependentSamples");
	menu->addAction(QString("Bayesian Paired Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestBayesianPairedSamples");
	menu->addAction(QString("Bayesian One Sample T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestBayesianOneSample");

	ui->classicalTTestButton->setMenu(menu);

	menu = new QMenu(this);

	menu->addAction(QString("ANOVA"), this, SLOT(itemSelected()))->setObjectName("Anova");
	menu->addAction(QString("Repeated Measures ANOVA"), this, SLOT(itemSelected()))->setObjectName("AnovaRepeatedMeasuresShort");
	menu->addAction(QString("ANCOVA"), this, SLOT(itemSelected()))->setObjectName("Ancova");

	menu->addSeparator();

	menu->addAction(QString("Bayesian ANOVA"), this, SLOT(itemSelected()))->setObjectName("AnovaBayesian");
	menu->addAction(QString("Bayesian Repeated Measures ANOVA"), this, SLOT(itemSelected()))->setObjectName("AnovaRepeatedMeasuresBayesian");
	menu->addAction(QString("Bayesian ANCOVA"), this, SLOT(itemSelected()))->setObjectName("AncovaBayesian");

	ui->classicalAnovaButton->setMenu(menu);

	menu = new QMenu(this);

	menu->addAction(QString("Correlation Matrix"), this, SLOT(itemSelected()))->setObjectName("Correlation");
#ifdef QT_DEBUG
	menu->addAction(QString("Partial Correlation"), this, SLOT(itemSelected()))->setObjectName("CorrelationPartial");
#endif
	menu->addAction(QString("Linear Regression"), this, SLOT(itemSelected()))->setObjectName("RegressionLinear");

	menu->addSeparator();

	menu->addAction(QString("Bayesian Correlation Matrix"), this, SLOT(itemSelected()))->setObjectName("CorrelationBayesian");
	menu->addAction(QString("Bayesian Correlation Pairs"), this, SLOT(itemSelected()))->setObjectName("CorrelationBayesianPairs");
	menu->addAction(QString("Bayesian Linear Regression"), this, SLOT(itemSelected()))->setObjectName("RegressionLinearBayesian");

	ui->classicalRegressionButton->setMenu(menu);

	menu = new QMenu(this);

	menu->addAction(QString("Contingency Tables"), this, SLOT(itemSelected()))->setObjectName("Crosstabs");
	menu->addSeparator();
	menu->addAction(QString("Bayesian Contingency Tables"), this, SLOT(itemSelected()))->setObjectName("CrosstabsBayesian");

	ui->classicalCrosstabsButton->setMenu(menu);
}

RibbonAnalysis::~RibbonAnalysis()
{
	delete ui;
}
<|endoftext|>


<commit_before>/*
 * Accounts and contacts model
 * This file is based on TelepathyQt4Yell Models
 *
 * Copyright (C) 2010 Collabora Ltd. <info@collabora.co.uk>
 * Copyright (C) 2011 Martin Klapetek <martin dot klapetek at gmail dot com>
 *
 * 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 "accounts-model.h"

#include <TelepathyQt4/ContactManager>
#include <TelepathyQt4/PendingReady>

#include "accounts-model-item.h"
#include "contact-model-item.h"

struct AccountsModel::Private
{
    Private(const Tp::AccountManagerPtr &am)
        : mAM(am)
    {
    }

    TreeNode *node(const QModelIndex &index) const;

    Tp::AccountManagerPtr mAM;
    TreeNode *mTree;
};

TreeNode *AccountsModel::Private::node(const QModelIndex &index) const
{
    TreeNode *node = reinterpret_cast<TreeNode *>(index.internalPointer());
    return node ? node : mTree;
}

AccountsModel::AccountsModel(const Tp::AccountManagerPtr &am, QObject *parent)
    : QAbstractItemModel(parent),
      mPriv(new AccountsModel::Private(am))
{
    mPriv->mTree = new TreeNode;
    connect(mPriv->mTree,
            SIGNAL(changed(TreeNode*)),
            SLOT(onItemChanged(TreeNode*)));

    connect(mPriv->mTree,
            SIGNAL(childrenAdded(TreeNode*,QList<TreeNode*>)),
            SLOT(onItemsAdded(TreeNode*,QList<TreeNode*>)));

    connect(mPriv->mTree,
            SIGNAL(childrenRemoved(TreeNode*,int,int)),
            SLOT(onItemsRemoved(TreeNode*,int,int)));

    foreach (Tp::AccountPtr account, mPriv->mAM->allAccounts()) {
        AccountsModelItem *item = new AccountsModelItem(account);
        connect(item, SIGNAL(connectionStatusChanged(QString,int)),
                this, SIGNAL(accountConnectionStatusChanged(QString,int)));
        mPriv->mTree->addChild(item);
    }

    connect(mPriv->mAM.data(),
            SIGNAL(newAccount(Tp::AccountPtr)),
            SLOT(onNewAccount(Tp::AccountPtr)));

    QHash<int, QByteArray> roles;
    roles[ItemRole] = "item";
    roles[IdRole] = "id";
    roles[ValidRole] = "valid";
    roles[EnabledRole] = "enabled";
    roles[ConnectionManagerNameRole] = "connectionManager";
    roles[ProtocolNameRole] = "protocol";
    roles[DisplayNameRole] = "displayName";
    roles[IconRole] = "icon";
    roles[NicknameRole] = "nickname";
    roles[ConnectsAutomaticallyRole] = "connectsAutomatically";
    roles[ChangingPresenceRole] = "changingPresence";
    roles[AutomaticPresenceRole] = "automaticStatus";
    roles[AutomaticPresenceTypeRole] = "automaticStatusType";
    roles[AutomaticPresenceStatusMessageRole] = "automaticStatusMessage";
    roles[CurrentPresenceRole] = "status";
    roles[CurrentPresenceTypeRole] = "statusType";
    roles[CurrentPresenceStatusMessageRole] = "statusMessage";
    roles[RequestedPresenceRole] = "requestedStatus";
    roles[RequestedPresenceTypeRole] = "requestedStatusType";
    roles[RequestedPresenceStatusMessageRole] = "requestedStatusMessage";
    roles[ConnectionStatusRole] = "connectionStatus";
    roles[ConnectionStatusReasonRole] = "connectionStatusReason";
    roles[AliasRole] = "aliasName";
    roles[AvatarRole] = "avatar";
    roles[PresenceStatusRole] = "presenceStatus";
    roles[PresenceTypeRole] = "presenceType";
    roles[PresenceMessageRole] = "presenceMessage";
    roles[SubscriptionStateRole] = "subscriptionState";
    roles[PublishStateRole] = "publishState";
    roles[BlockedRole] = "blocked";
    roles[GroupsRole] = "groups";
    roles[TextChatCapabilityRole] = "textChat";
    roles[MediaCallCapabilityRole] = "mediaCall";
    roles[AudioCallCapabilityRole] = "audioCall";
    roles[VideoCallCapabilityRole] = "videoCall";
    roles[UpgradeCallCapabilityRole] = "upgradeCall";
    roles[FileTransferCapabilityRole] = "fileTransfer";
    setRoleNames(roles);
}

AccountsModel::~AccountsModel()
{
    mPriv->mTree->deleteLater();
    delete mPriv;
}

void AccountsModel::onNewAccount(const Tp::AccountPtr &account)
{
    AccountsModelItem *accountNode = new AccountsModelItem(account);

    connect(accountNode, SIGNAL(connectionStatusChanged(QString,int)),
            this, SIGNAL(accountConnectionStatusChanged(QString,int)));

    onItemsAdded(mPriv->mTree, QList<TreeNode *>() << accountNode);
}

void AccountsModel::onItemChanged(TreeNode *node)
{
    if (node->parent()) {
        //if it is a group item
        if (node->parent() == mPriv->mTree) {
            qobject_cast<AccountsModelItem*>(node)->countOnlineContacts();
        } else {
            qobject_cast<AccountsModelItem*>(node->parent())->countOnlineContacts();
            emit dataChanged(index(node->parent()), index(node->parent()));
        }
    }
    QModelIndex accountIndex = index(node);
    emit dataChanged(accountIndex, accountIndex);
}

void AccountsModel::onItemsAdded(TreeNode *parent, const QList<TreeNode *> &nodes)
{
    QModelIndex parentIndex = index(parent);
    int currentSize = rowCount(parentIndex);
    beginInsertRows(parentIndex, currentSize, currentSize + nodes.size() - 1);
    foreach (TreeNode *node, nodes) {
        parent->addChild(node);
    }
    endInsertRows();
    emit accountCountChanged();
}

void AccountsModel::onItemsRemoved(TreeNode *parent, int first, int last)
{
    QModelIndex parentIndex = index(parent);
    QList<TreeNode *> removedItems;
    beginRemoveRows(parentIndex, first, last);
    for (int i = last; i >= first; i--) {
        parent->childAt(i)->remove();
    }
    endRemoveRows();

    emit accountCountChanged();
}

int AccountsModel::accountCount() const
{
    return mPriv->mTree->size();
}

QObject *AccountsModel::accountItemForId(const QString &id) const
{
    for (int i = 0; i < mPriv->mTree->size(); ++i) {
        AccountsModelItem *item = qobject_cast<AccountsModelItem*>(mPriv->mTree->childAt(i));
        if (!item) {
            continue;
        }

        if (item->data(IdRole) == id) {
            return item;
        }
    }

    return 0;
}

QObject *AccountsModel::contactItemForId(const QString &accountId, const QString &contactId) const
{
    AccountsModelItem *accountItem = qobject_cast<AccountsModelItem*>(accountItemForId(accountId));
    if (!accountItem) {
        return 0;
    }

    for (int i = 0; i < accountItem->size(); ++i) {
        ContactModelItem *item = qobject_cast<ContactModelItem*>(accountItem->childAt(i));
        if (!item) {
            continue;
        }

        if (item->data(IdRole) == contactId) {
            return item;
        }
    }

    return 0;
}

int AccountsModel::columnCount(const QModelIndex &parent) const
{
    return 1;
}

int AccountsModel::rowCount(const QModelIndex &parent) const
{
    return mPriv->node(parent)->size();
}

QVariant AccountsModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid()) {
        return QVariant();
    }

    return mPriv->node(index)->data(role);
}

Tp::AccountPtr AccountsModel::accountForContactItem(ContactModelItem *contactItem) const
{
    AccountsModelItem *accountItem = qobject_cast<AccountsModelItem*>(contactItem->parent());
    if (accountItem) {
        return accountItem->account();
    } else {
        return Tp::AccountPtr();
    }
}

Qt::ItemFlags AccountsModel::flags(const QModelIndex &index) const
{
    if (index.isValid()) {
        bool isContact = index.data(AccountsModel::ItemRole).userType() == qMetaTypeId<ContactModelItem*>();
        if (isContact) {
            return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled;
        } else {
            return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDropEnabled;
        }
    }

    return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}

bool AccountsModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (index.isValid()) {
        mPriv->node(index)->setData(role, value);
    }

    return false;
}

QModelIndex AccountsModel::index(int row, int column, const QModelIndex &parent) const
{
    TreeNode *parentNode = mPriv->node(parent);
    Q_ASSERT(parentNode);
    if (row < parentNode->size()) {
        return createIndex(row, column, parentNode->childAt(row));
    }

    return QModelIndex();
}

QModelIndex AccountsModel::index(TreeNode *node) const
{
    if (node->parent()) {
        return createIndex(node->parent()->indexOf(node), 0, node);
    } else {
        return QModelIndex();
    }
}

QModelIndex AccountsModel::parent(const QModelIndex &index) const
{
    if (!index.isValid()) {
        return QModelIndex();
    }

    TreeNode *currentNode = mPriv->node(index);
    if (currentNode->parent()) {
        return AccountsModel::index(currentNode->parent());
    } else {
        // no parent: return root node
        return QModelIndex();
    }
}

QStringList AccountsModel::mimeTypes() const
{
    QStringList types;
    types << "application/vnd.telepathy.contact";
    return types;
}

QMimeData* AccountsModel::mimeData(const QModelIndexList& indexes) const
{
    QMimeData *mimeData = new QMimeData();
    QByteArray encodedData;

    QDataStream stream(&encodedData, QIODevice::WriteOnly);

    foreach (const QModelIndex &index, indexes) {
        if (index.isValid()) {
            ContactModelItem *c = data(index, AccountsModel::ItemRole).value<ContactModelItem*>();
            //We put a contact ID and its account ID to the stream, so we can later recreate the contact using AccountsModel
            stream << c->contact().data()->id() << accountForContactItem(c).data()->uniqueIdentifier();
        }
    }

    mimeData->setData("application/vnd.telepathy.contact", encodedData);
    return mimeData;
}

#include "accounts-model.moc"
<commit_msg>AccountsModel: Add name for the DesktopSharingCapabilityRole.<commit_after>/*
 * Accounts and contacts model
 * This file is based on TelepathyQt4Yell Models
 *
 * Copyright (C) 2010 Collabora Ltd. <info@collabora.co.uk>
 * Copyright (C) 2011 Martin Klapetek <martin dot klapetek at gmail dot com>
 *
 * 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 "accounts-model.h"

#include <TelepathyQt4/ContactManager>
#include <TelepathyQt4/PendingReady>

#include "accounts-model-item.h"
#include "contact-model-item.h"

struct AccountsModel::Private
{
    Private(const Tp::AccountManagerPtr &am)
        : mAM(am)
    {
    }

    TreeNode *node(const QModelIndex &index) const;

    Tp::AccountManagerPtr mAM;
    TreeNode *mTree;
};

TreeNode *AccountsModel::Private::node(const QModelIndex &index) const
{
    TreeNode *node = reinterpret_cast<TreeNode *>(index.internalPointer());
    return node ? node : mTree;
}

AccountsModel::AccountsModel(const Tp::AccountManagerPtr &am, QObject *parent)
    : QAbstractItemModel(parent),
      mPriv(new AccountsModel::Private(am))
{
    mPriv->mTree = new TreeNode;
    connect(mPriv->mTree,
            SIGNAL(changed(TreeNode*)),
            SLOT(onItemChanged(TreeNode*)));

    connect(mPriv->mTree,
            SIGNAL(childrenAdded(TreeNode*,QList<TreeNode*>)),
            SLOT(onItemsAdded(TreeNode*,QList<TreeNode*>)));

    connect(mPriv->mTree,
            SIGNAL(childrenRemoved(TreeNode*,int,int)),
            SLOT(onItemsRemoved(TreeNode*,int,int)));

    foreach (Tp::AccountPtr account, mPriv->mAM->allAccounts()) {
        AccountsModelItem *item = new AccountsModelItem(account);
        connect(item, SIGNAL(connectionStatusChanged(QString,int)),
                this, SIGNAL(accountConnectionStatusChanged(QString,int)));
        mPriv->mTree->addChild(item);
    }

    connect(mPriv->mAM.data(),
            SIGNAL(newAccount(Tp::AccountPtr)),
            SLOT(onNewAccount(Tp::AccountPtr)));

    QHash<int, QByteArray> roles;
    roles[ItemRole] = "item";
    roles[IdRole] = "id";
    roles[ValidRole] = "valid";
    roles[EnabledRole] = "enabled";
    roles[ConnectionManagerNameRole] = "connectionManager";
    roles[ProtocolNameRole] = "protocol";
    roles[DisplayNameRole] = "displayName";
    roles[IconRole] = "icon";
    roles[NicknameRole] = "nickname";
    roles[ConnectsAutomaticallyRole] = "connectsAutomatically";
    roles[ChangingPresenceRole] = "changingPresence";
    roles[AutomaticPresenceRole] = "automaticStatus";
    roles[AutomaticPresenceTypeRole] = "automaticStatusType";
    roles[AutomaticPresenceStatusMessageRole] = "automaticStatusMessage";
    roles[CurrentPresenceRole] = "status";
    roles[CurrentPresenceTypeRole] = "statusType";
    roles[CurrentPresenceStatusMessageRole] = "statusMessage";
    roles[RequestedPresenceRole] = "requestedStatus";
    roles[RequestedPresenceTypeRole] = "requestedStatusType";
    roles[RequestedPresenceStatusMessageRole] = "requestedStatusMessage";
    roles[ConnectionStatusRole] = "connectionStatus";
    roles[ConnectionStatusReasonRole] = "connectionStatusReason";
    roles[AliasRole] = "aliasName";
    roles[AvatarRole] = "avatar";
    roles[PresenceStatusRole] = "presenceStatus";
    roles[PresenceTypeRole] = "presenceType";
    roles[PresenceMessageRole] = "presenceMessage";
    roles[SubscriptionStateRole] = "subscriptionState";
    roles[PublishStateRole] = "publishState";
    roles[BlockedRole] = "blocked";
    roles[GroupsRole] = "groups";
    roles[TextChatCapabilityRole] = "textChat";
    roles[MediaCallCapabilityRole] = "mediaCall";
    roles[AudioCallCapabilityRole] = "audioCall";
    roles[VideoCallCapabilityRole] = "videoCall";
    roles[UpgradeCallCapabilityRole] = "upgradeCall";
    roles[FileTransferCapabilityRole] = "fileTransfer";
    roles[DesktopSharingCapabilityRole] = "desktopSharing";
    setRoleNames(roles);
}

AccountsModel::~AccountsModel()
{
    mPriv->mTree->deleteLater();
    delete mPriv;
}

void AccountsModel::onNewAccount(const Tp::AccountPtr &account)
{
    AccountsModelItem *accountNode = new AccountsModelItem(account);

    connect(accountNode, SIGNAL(connectionStatusChanged(QString,int)),
            this, SIGNAL(accountConnectionStatusChanged(QString,int)));

    onItemsAdded(mPriv->mTree, QList<TreeNode *>() << accountNode);
}

void AccountsModel::onItemChanged(TreeNode *node)
{
    if (node->parent()) {
        //if it is a group item
        if (node->parent() == mPriv->mTree) {
            qobject_cast<AccountsModelItem*>(node)->countOnlineContacts();
        } else {
            qobject_cast<AccountsModelItem*>(node->parent())->countOnlineContacts();
            emit dataChanged(index(node->parent()), index(node->parent()));
        }
    }
    QModelIndex accountIndex = index(node);
    emit dataChanged(accountIndex, accountIndex);
}

void AccountsModel::onItemsAdded(TreeNode *parent, const QList<TreeNode *> &nodes)
{
    QModelIndex parentIndex = index(parent);
    int currentSize = rowCount(parentIndex);
    beginInsertRows(parentIndex, currentSize, currentSize + nodes.size() - 1);
    foreach (TreeNode *node, nodes) {
        parent->addChild(node);
    }
    endInsertRows();
    emit accountCountChanged();
}

void AccountsModel::onItemsRemoved(TreeNode *parent, int first, int last)
{
    QModelIndex parentIndex = index(parent);
    QList<TreeNode *> removedItems;
    beginRemoveRows(parentIndex, first, last);
    for (int i = last; i >= first; i--) {
        parent->childAt(i)->remove();
    }
    endRemoveRows();

    emit accountCountChanged();
}

int AccountsModel::accountCount() const
{
    return mPriv->mTree->size();
}

QObject *AccountsModel::accountItemForId(const QString &id) const
{
    for (int i = 0; i < mPriv->mTree->size(); ++i) {
        AccountsModelItem *item = qobject_cast<AccountsModelItem*>(mPriv->mTree->childAt(i));
        if (!item) {
            continue;
        }

        if (item->data(IdRole) == id) {
            return item;
        }
    }

    return 0;
}

QObject *AccountsModel::contactItemForId(const QString &accountId, const QString &contactId) const
{
    AccountsModelItem *accountItem = qobject_cast<AccountsModelItem*>(accountItemForId(accountId));
    if (!accountItem) {
        return 0;
    }

    for (int i = 0; i < accountItem->size(); ++i) {
        ContactModelItem *item = qobject_cast<ContactModelItem*>(accountItem->childAt(i));
        if (!item) {
            continue;
        }

        if (item->data(IdRole) == contactId) {
            return item;
        }
    }

    return 0;
}

int AccountsModel::columnCount(const QModelIndex &parent) const
{
    return 1;
}

int AccountsModel::rowCount(const QModelIndex &parent) const
{
    return mPriv->node(parent)->size();
}

QVariant AccountsModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid()) {
        return QVariant();
    }

    return mPriv->node(index)->data(role);
}

Tp::AccountPtr AccountsModel::accountForContactItem(ContactModelItem *contactItem) const
{
    AccountsModelItem *accountItem = qobject_cast<AccountsModelItem*>(contactItem->parent());
    if (accountItem) {
        return accountItem->account();
    } else {
        return Tp::AccountPtr();
    }
}

Qt::ItemFlags AccountsModel::flags(const QModelIndex &index) const
{
    if (index.isValid()) {
        bool isContact = index.data(AccountsModel::ItemRole).userType() == qMetaTypeId<ContactModelItem*>();
        if (isContact) {
            return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled;
        } else {
            return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDropEnabled;
        }
    }

    return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}

bool AccountsModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (index.isValid()) {
        mPriv->node(index)->setData(role, value);
    }

    return false;
}

QModelIndex AccountsModel::index(int row, int column, const QModelIndex &parent) const
{
    TreeNode *parentNode = mPriv->node(parent);
    Q_ASSERT(parentNode);
    if (row < parentNode->size()) {
        return createIndex(row, column, parentNode->childAt(row));
    }

    return QModelIndex();
}

QModelIndex AccountsModel::index(TreeNode *node) const
{
    if (node->parent()) {
        return createIndex(node->parent()->indexOf(node), 0, node);
    } else {
        return QModelIndex();
    }
}

QModelIndex AccountsModel::parent(const QModelIndex &index) const
{
    if (!index.isValid()) {
        return QModelIndex();
    }

    TreeNode *currentNode = mPriv->node(index);
    if (currentNode->parent()) {
        return AccountsModel::index(currentNode->parent());
    } else {
        // no parent: return root node
        return QModelIndex();
    }
}

QStringList AccountsModel::mimeTypes() const
{
    QStringList types;
    types << "application/vnd.telepathy.contact";
    return types;
}

QMimeData* AccountsModel::mimeData(const QModelIndexList& indexes) const
{
    QMimeData *mimeData = new QMimeData();
    QByteArray encodedData;

    QDataStream stream(&encodedData, QIODevice::WriteOnly);

    foreach (const QModelIndex &index, indexes) {
        if (index.isValid()) {
            ContactModelItem *c = data(index, AccountsModel::ItemRole).value<ContactModelItem*>();
            //We put a contact ID and its account ID to the stream, so we can later recreate the contact using AccountsModel
            stream << c->contact().data()->id() << accountForContactItem(c).data()->uniqueIdentifier();
        }
    }

    mimeData->setData("application/vnd.telepathy.contact", encodedData);
    return mimeData;
}

#include "accounts-model.moc"
<|endoftext|>


<commit_before>/* License: Apache 2.0. See LICENSE file in root directory.
Copyright(c) 2017 Intel Corporation. All Rights Reserved. */

#include "python.hpp"
#include "../include/librealsense2/hpp/rs_sensor.hpp"
#include "calibrated-sensor.h"

void init_sensor(py::module &m) {
    /** rs_sensor.hpp **/
    py::class_<rs2::notification> notification(m, "notification"); // No docstring in C++
    notification.def(py::init<>())
        .def("get_category", &rs2::notification::get_category,
             "Retrieve the notification's category.")
        .def_property_readonly("category", &rs2::notification::get_category,
             "The notification's category. Identical to calling get_category.")
        .def("get_description", &rs2::notification::get_description,
             "Retrieve the notification's description.")
        .def_property_readonly("description", &rs2::notification::get_description,
             "The notification's description. Identical to calling get_description.")
        .def("get_timestamp", &rs2::notification::get_timestamp,
             "Retrieve the notification's arrival timestamp.")
        .def_property_readonly("timestamp", &rs2::notification::get_timestamp,
             "The notification's arrival timestamp. Identical to calling get_timestamp.")
        .def("get_severity", &rs2::notification::get_severity,
             "Retrieve the notification's severity.")
        .def_property_readonly("severity", &rs2::notification::get_severity,
             "The notification's severity. Identical to calling get_severity.")
        .def("get_serialized_data", &rs2::notification::get_severity,
             "Retrieve the notification's serialized data.")
        .def_property_readonly("serialized_data", &rs2::notification::get_serialized_data,
             "The notification's serialized data. Identical to calling get_serialized_data.")
        .def("__repr__", [](const rs2::notification &n) {
            return n.get_description();
        });

    // not binding notifications_callback, templated

    py::class_<rs2::sensor, rs2::options> sensor(m, "sensor"); // No docstring in C++
    sensor.def("open", (void (rs2::sensor::*)(const rs2::stream_profile&) const) &rs2::sensor::open,
               "Open sensor for exclusive access, by commiting to a configuration", "profile"_a)
        .def("supports", (bool (rs2::sensor::*)(rs2_camera_info) const) &rs2::sensor::supports,
             "Check if specific camera info is supported.", "info")
        .def("supports", (bool (rs2::sensor::*)(rs2_option) const) &rs2::options::supports,
             "Check if specific camera info is supported.", "info")
        .def("get_info", &rs2::sensor::get_info, "Retrieve camera specific information, "
             "like versions of various internal components.", "info"_a)
        .def("set_notifications_callback", [](const rs2::sensor& self, std::function<void(rs2::notification)> callback) {
            self.set_notifications_callback(callback);
        }, "Register Notifications callback", "callback"_a)
        .def("open", (void (rs2::sensor::*)(const std::vector<rs2::stream_profile>&) const) &rs2::sensor::open,
             "Open sensor for exclusive access, by committing to a composite configuration, specifying one or "
             "more stream profiles.", "profiles"_a)
        .def("close", &rs2::sensor::close, "Close sensor for exclusive access.", py::call_guard<py::gil_scoped_release>())
        .def("start", [](const rs2::sensor& self, std::function<void(rs2::frame)> callback) {
            self.start(callback);
        }, "Start passing frames into user provided callback.", "callback"_a)
        .def("start", [](const rs2::sensor& self, rs2::syncer& syncer) {
            self.start(syncer);
        }, "Start passing frames into user provided syncer.", "syncer"_a)
        .def("start", [](const rs2::sensor& self, rs2::frame_queue& queue) {
            self.start(queue);
        }, "start passing frames into specified frame_queue", "queue"_a)
        .def("stop", &rs2::sensor::stop, "Stop streaming.", py::call_guard<py::gil_scoped_release>())
        .def("get_stream_profiles", &rs2::sensor::get_stream_profiles, "Retrieves the list of stream profiles supported by the sensor.")
        .def("get_active_streams", &rs2::sensor::get_active_streams, "Retrieves the list of stream profiles currently streaming on the sensor.")
        .def_property_readonly("profiles", &rs2::sensor::get_stream_profiles, "The list of stream profiles supported by the sensor. Identical to calling get_stream_profiles")
        .def("get_recommended_filters", &rs2::sensor::get_recommended_filters, "Return the recommended list of filters by the sensor.")
        .def(py::init<>())
        .def("__nonzero__", &rs2::sensor::operator bool) // No docstring in C++
        .def(BIND_DOWNCAST(sensor, roi_sensor))
        .def(BIND_DOWNCAST(sensor, depth_sensor))
        .def(BIND_DOWNCAST(sensor, color_sensor))
        .def(BIND_DOWNCAST(sensor, motion_sensor))
        .def(BIND_DOWNCAST(sensor, fisheye_sensor))
        .def(BIND_DOWNCAST(sensor, pose_sensor))
        .def(BIND_DOWNCAST(sensor, calibrated_sensor))
        .def(BIND_DOWNCAST(sensor, wheel_odometer));

    // rs2::sensor_from_frame [frame.def("get_sensor", ...)?
    // rs2::sensor==sensor?

    py::class_<rs2::roi_sensor, rs2::sensor> roi_sensor(m, "roi_sensor"); // No docstring in C++
    roi_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("set_region_of_interest", &rs2::roi_sensor::set_region_of_interest, "roi"_a) // No docstring in C++
        .def("get_region_of_interest", &rs2::roi_sensor::get_region_of_interest) // No docstring in C++
        .def("__nonzero__", &rs2::roi_sensor::operator bool); // No docstring in C++

    py::class_<rs2::depth_sensor, rs2::sensor> depth_sensor(m, "depth_sensor"); // No docstring in C++
    depth_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("get_depth_scale", &rs2::depth_sensor::get_depth_scale,
             "Retrieves mapping between the units of the depth image and meters.")
        .def("__nonzero__", &rs2::depth_sensor::operator bool); // No docstring in C++

    py::class_<rs2::color_sensor, rs2::sensor> color_sensor(m, "color_sensor"); // No docstring in C++
    color_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("__nonzero__", &rs2::color_sensor::operator bool); // No docstring in C++

    py::class_<rs2::motion_sensor, rs2::sensor> motion_sensor(m, "motion_sensor"); // No docstring in C++
    motion_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("__nonzero__", &rs2::motion_sensor::operator bool); // No docstring in C++

    py::class_<rs2::fisheye_sensor, rs2::sensor> fisheye_sensor(m, "fisheye_sensor"); // No docstring in C++
    fisheye_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("__nonzero__", &rs2::fisheye_sensor::operator bool); // No docstring in C++

    py::class_<rs2::calibrated_sensor, rs2::sensor> cal_sensor( m, "calibrated_sensor" );
    cal_sensor.def( py::init<rs2::sensor>(), "sensor"_a )
        .def( "override_intrinsics", &rs2::calibrated_sensor::override_intrinsics, "intrinsics"_a )
        .def( "override_extrinsics", &rs2::calibrated_sensor::override_extrinsics, "extrinsics"_a )
        .def( "get_dsm_params", &rs2::calibrated_sensor::get_dsm_params )
        .def( "override_dsm_params", &rs2::calibrated_sensor::override_dsm_params, "dsm_params"_a )
        .def( "reset_calibration", &rs2::calibrated_sensor::reset_calibration )
        .def( "__nonzero__", &rs2::calibrated_sensor::operator bool );

    // rs2::depth_stereo_sensor
    py::class_<rs2::depth_stereo_sensor, rs2::depth_sensor> depth_stereo_sensor(m, "depth_stereo_sensor"); // No docstring in C++
    depth_stereo_sensor.def(py::init<rs2::sensor>())
        .def("get_stereo_baseline", &rs2::depth_stereo_sensor::get_stereo_baseline, "Retrieve the stereoscopic baseline value from the sensor.");

    py::class_<rs2::pose_sensor, rs2::sensor> pose_sensor(m, "pose_sensor"); // No docstring in C++
    pose_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("import_localization_map", &rs2::pose_sensor::import_localization_map,
             "Load relocalization map onto device. Only one relocalization map can be imported at a time; "
             "any previously existing map will be overwritten.\n"
             "The imported map exists simultaneously with the map created during the most recent tracking "
             "session after start(),"
             "and they are merged after the imported map is relocalized.\n"
             "This operation must be done before start().", "lmap_buf"_a)
        .def("export_localization_map", &rs2::pose_sensor::export_localization_map,
             "Get relocalization map that is currently on device, created and updated during most "
             "recent tracking session.\n"
             "Can be called before or after stop().")
        .def("set_static_node", &rs2::pose_sensor::set_static_node,
             "Creates a named virtual landmark in the current map, known as static node.\n"
             "The static node's pose is provided relative to the origin of current coordinate system of device poses.\n"
             "This function fails if the current tracker confidence is below 3 (high confidence).",
             "guid"_a, "pos"_a, "orient"_a)
        .def("get_static_node", [](const rs2::pose_sensor& self, const std::string& guid) {
            rs2_vector pos;
            rs2_quaternion orient;
            bool res = self.get_static_node(guid, pos, orient);
            return std::make_tuple(res, pos, orient);
        }, "Gets the current pose of a static node that was created in the current map or in an imported map.\n"
           "Static nodes of imported maps are available after relocalizing the imported map.\n"
           "The static node's pose is returned relative to the current origin of coordinates of device poses.\n"
           "Thus, poses of static nodes of an imported map are consistent with current device poses after relocalization.\n"
           "This function fails if the current tracker confidence is below 3 (high confidence).",
           "guid"_a)
        .def("remove_static_node", &rs2::pose_sensor::remove_static_node,
             "Removes a named virtual landmark in the current map, known as static node.\n"
             "guid"_a)
        .def("__nonzero__", &rs2::pose_sensor::operator bool); // No docstring in C++

    py::class_<rs2::wheel_odometer, rs2::sensor> wheel_odometer(m, "wheel_odometer"); // No docstring in C++
    wheel_odometer.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("load_wheel_odometery_config", &rs2::wheel_odometer::load_wheel_odometery_config,
             "Load Wheel odometer settings from host to device.", "odometry_config_buf"_a)
        .def("send_wheel_odometry", &rs2::wheel_odometer::send_wheel_odometry,
             "Send wheel odometry data for each individual sensor (wheel)",
             "wo_sensor_id"_a, "frame_num"_a, "translational_velocity"_a)
        .def("__nonzero__", &rs2::wheel_odometer::operator bool);
    /** end rs_sensor.hpp **/
}
<commit_msg>PR #7076 from Eran: fix GIL locks in calibrated_sensor APIs which can cause frame drops<commit_after>/* License: Apache 2.0. See LICENSE file in root directory.
Copyright(c) 2017 Intel Corporation. All Rights Reserved. */

#include "python.hpp"
#include "../include/librealsense2/hpp/rs_sensor.hpp"
#include "calibrated-sensor.h"

void init_sensor(py::module &m) {
    /** rs_sensor.hpp **/
    py::class_<rs2::notification> notification(m, "notification"); // No docstring in C++
    notification.def(py::init<>())
        .def("get_category", &rs2::notification::get_category,
             "Retrieve the notification's category.")
        .def_property_readonly("category", &rs2::notification::get_category,
             "The notification's category. Identical to calling get_category.")
        .def("get_description", &rs2::notification::get_description,
             "Retrieve the notification's description.")
        .def_property_readonly("description", &rs2::notification::get_description,
             "The notification's description. Identical to calling get_description.")
        .def("get_timestamp", &rs2::notification::get_timestamp,
             "Retrieve the notification's arrival timestamp.")
        .def_property_readonly("timestamp", &rs2::notification::get_timestamp,
             "The notification's arrival timestamp. Identical to calling get_timestamp.")
        .def("get_severity", &rs2::notification::get_severity,
             "Retrieve the notification's severity.")
        .def_property_readonly("severity", &rs2::notification::get_severity,
             "The notification's severity. Identical to calling get_severity.")
        .def("get_serialized_data", &rs2::notification::get_severity,
             "Retrieve the notification's serialized data.")
        .def_property_readonly("serialized_data", &rs2::notification::get_serialized_data,
             "The notification's serialized data. Identical to calling get_serialized_data.")
        .def("__repr__", [](const rs2::notification &n) {
            return n.get_description();
        });

    // not binding notifications_callback, templated

    py::class_<rs2::sensor, rs2::options> sensor(m, "sensor"); // No docstring in C++
    sensor.def("open", (void (rs2::sensor::*)(const rs2::stream_profile&) const) &rs2::sensor::open,
               "Open sensor for exclusive access, by commiting to a configuration", "profile"_a)
        .def("supports", (bool (rs2::sensor::*)(rs2_camera_info) const) &rs2::sensor::supports,
             "Check if specific camera info is supported.", "info")
        .def("supports", (bool (rs2::sensor::*)(rs2_option) const) &rs2::options::supports,
             "Check if specific camera info is supported.", "info")
        .def("get_info", &rs2::sensor::get_info, "Retrieve camera specific information, "
             "like versions of various internal components.", "info"_a)
        .def("set_notifications_callback", [](const rs2::sensor& self, std::function<void(rs2::notification)> callback) {
            self.set_notifications_callback(callback);
        }, "Register Notifications callback", "callback"_a)
        .def("open", (void (rs2::sensor::*)(const std::vector<rs2::stream_profile>&) const) &rs2::sensor::open,
             "Open sensor for exclusive access, by committing to a composite configuration, specifying one or "
             "more stream profiles.", "profiles"_a)
        .def("close", &rs2::sensor::close, "Close sensor for exclusive access.", py::call_guard<py::gil_scoped_release>())
        .def("start", [](const rs2::sensor& self, std::function<void(rs2::frame)> callback) {
            self.start(callback);
        }, "Start passing frames into user provided callback.", "callback"_a)
        .def("start", [](const rs2::sensor& self, rs2::syncer& syncer) {
            self.start(syncer);
        }, "Start passing frames into user provided syncer.", "syncer"_a)
        .def("start", [](const rs2::sensor& self, rs2::frame_queue& queue) {
            self.start(queue);
        }, "start passing frames into specified frame_queue", "queue"_a)
        .def("stop", &rs2::sensor::stop, "Stop streaming.", py::call_guard<py::gil_scoped_release>())
        .def("get_stream_profiles", &rs2::sensor::get_stream_profiles, "Retrieves the list of stream profiles supported by the sensor.")
        .def("get_active_streams", &rs2::sensor::get_active_streams, "Retrieves the list of stream profiles currently streaming on the sensor.")
        .def_property_readonly("profiles", &rs2::sensor::get_stream_profiles, "The list of stream profiles supported by the sensor. Identical to calling get_stream_profiles")
        .def("get_recommended_filters", &rs2::sensor::get_recommended_filters, "Return the recommended list of filters by the sensor.")
        .def(py::init<>())
        .def("__nonzero__", &rs2::sensor::operator bool) // No docstring in C++
        .def(BIND_DOWNCAST(sensor, roi_sensor))
        .def(BIND_DOWNCAST(sensor, depth_sensor))
        .def(BIND_DOWNCAST(sensor, color_sensor))
        .def(BIND_DOWNCAST(sensor, motion_sensor))
        .def(BIND_DOWNCAST(sensor, fisheye_sensor))
        .def(BIND_DOWNCAST(sensor, pose_sensor))
        .def(BIND_DOWNCAST(sensor, calibrated_sensor))
        .def(BIND_DOWNCAST(sensor, wheel_odometer));

    // rs2::sensor_from_frame [frame.def("get_sensor", ...)?
    // rs2::sensor==sensor?

    py::class_<rs2::roi_sensor, rs2::sensor> roi_sensor(m, "roi_sensor"); // No docstring in C++
    roi_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("set_region_of_interest", &rs2::roi_sensor::set_region_of_interest, "roi"_a) // No docstring in C++
        .def("get_region_of_interest", &rs2::roi_sensor::get_region_of_interest) // No docstring in C++
        .def("__nonzero__", &rs2::roi_sensor::operator bool); // No docstring in C++

    py::class_<rs2::depth_sensor, rs2::sensor> depth_sensor(m, "depth_sensor"); // No docstring in C++
    depth_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("get_depth_scale", &rs2::depth_sensor::get_depth_scale,
             "Retrieves mapping between the units of the depth image and meters.")
        .def("__nonzero__", &rs2::depth_sensor::operator bool); // No docstring in C++

    py::class_<rs2::color_sensor, rs2::sensor> color_sensor(m, "color_sensor"); // No docstring in C++
    color_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("__nonzero__", &rs2::color_sensor::operator bool); // No docstring in C++

    py::class_<rs2::motion_sensor, rs2::sensor> motion_sensor(m, "motion_sensor"); // No docstring in C++
    motion_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("__nonzero__", &rs2::motion_sensor::operator bool); // No docstring in C++

    py::class_<rs2::fisheye_sensor, rs2::sensor> fisheye_sensor(m, "fisheye_sensor"); // No docstring in C++
    fisheye_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("__nonzero__", &rs2::fisheye_sensor::operator bool); // No docstring in C++

    py::class_<rs2::calibrated_sensor, rs2::sensor> cal_sensor( m, "calibrated_sensor" );
    cal_sensor.def( py::init<rs2::sensor>(), "sensor"_a )
        .def( "override_intrinsics",
              &rs2::calibrated_sensor::override_intrinsics,
              "intrinsics"_a,
              py::call_guard< py::gil_scoped_release >() )
        .def( "override_extrinsics",
              &rs2::calibrated_sensor::override_extrinsics,
              "extrinsics"_a,
              py::call_guard< py::gil_scoped_release >() )
        .def( "get_dsm_params",
              &rs2::calibrated_sensor::get_dsm_params,
              py::call_guard< py::gil_scoped_release >() )
        .def( "override_dsm_params",
              &rs2::calibrated_sensor::override_dsm_params,
              "dsm_params"_a,
              py::call_guard< py::gil_scoped_release >() )
        .def( "reset_calibration",
              &rs2::calibrated_sensor::reset_calibration,
              py::call_guard< py::gil_scoped_release >() )
        .def( "__nonzero__", &rs2::calibrated_sensor::operator bool );

    // rs2::depth_stereo_sensor
    py::class_<rs2::depth_stereo_sensor, rs2::depth_sensor> depth_stereo_sensor(m, "depth_stereo_sensor"); // No docstring in C++
    depth_stereo_sensor.def(py::init<rs2::sensor>())
        .def("get_stereo_baseline", &rs2::depth_stereo_sensor::get_stereo_baseline, "Retrieve the stereoscopic baseline value from the sensor.");

    py::class_<rs2::pose_sensor, rs2::sensor> pose_sensor(m, "pose_sensor"); // No docstring in C++
    pose_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("import_localization_map", &rs2::pose_sensor::import_localization_map,
             "Load relocalization map onto device. Only one relocalization map can be imported at a time; "
             "any previously existing map will be overwritten.\n"
             "The imported map exists simultaneously with the map created during the most recent tracking "
             "session after start(),"
             "and they are merged after the imported map is relocalized.\n"
             "This operation must be done before start().", "lmap_buf"_a)
        .def("export_localization_map", &rs2::pose_sensor::export_localization_map,
             "Get relocalization map that is currently on device, created and updated during most "
             "recent tracking session.\n"
             "Can be called before or after stop().")
        .def("set_static_node", &rs2::pose_sensor::set_static_node,
             "Creates a named virtual landmark in the current map, known as static node.\n"
             "The static node's pose is provided relative to the origin of current coordinate system of device poses.\n"
             "This function fails if the current tracker confidence is below 3 (high confidence).",
             "guid"_a, "pos"_a, "orient"_a)
        .def("get_static_node", [](const rs2::pose_sensor& self, const std::string& guid) {
            rs2_vector pos;
            rs2_quaternion orient;
            bool res = self.get_static_node(guid, pos, orient);
            return std::make_tuple(res, pos, orient);
        }, "Gets the current pose of a static node that was created in the current map or in an imported map.\n"
           "Static nodes of imported maps are available after relocalizing the imported map.\n"
           "The static node's pose is returned relative to the current origin of coordinates of device poses.\n"
           "Thus, poses of static nodes of an imported map are consistent with current device poses after relocalization.\n"
           "This function fails if the current tracker confidence is below 3 (high confidence).",
           "guid"_a)
        .def("remove_static_node", &rs2::pose_sensor::remove_static_node,
             "Removes a named virtual landmark in the current map, known as static node.\n"
             "guid"_a)
        .def("__nonzero__", &rs2::pose_sensor::operator bool); // No docstring in C++

    py::class_<rs2::wheel_odometer, rs2::sensor> wheel_odometer(m, "wheel_odometer"); // No docstring in C++
    wheel_odometer.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("load_wheel_odometery_config", &rs2::wheel_odometer::load_wheel_odometery_config,
             "Load Wheel odometer settings from host to device.", "odometry_config_buf"_a)
        .def("send_wheel_odometry", &rs2::wheel_odometer::send_wheel_odometry,
             "Send wheel odometry data for each individual sensor (wheel)",
             "wo_sensor_id"_a, "frame_num"_a, "translational_velocity"_a)
        .def("__nonzero__", &rs2::wheel_odometer::operator bool);
    /** end rs_sensor.hpp **/
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: formsimp.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 14:11:01 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif

#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif

#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif

#ifndef _XMLOFF_ANIMIMP_HXX
#include "formsimp.hxx"
#endif

using namespace ::rtl;

TYPEINIT1( XMLFormsContext, SvXMLImportContext );

XMLFormsContext::XMLFormsContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLocalName )
: SvXMLImportContext(rImport, nPrfx, rLocalName)
{
}

XMLFormsContext::~XMLFormsContext()
{
}

SvXMLImportContext * XMLFormsContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
    return GetImport().GetFormImport()->createContext( nPrefix, rLocalName, xAttrList );
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.4.158); FILE MERGED 2006/09/01 17:59:40 kaib 1.4.158.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: formsimp.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 10:36:16 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif

#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif

#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif

#ifndef _XMLOFF_ANIMIMP_HXX
#include "formsimp.hxx"
#endif

using namespace ::rtl;

TYPEINIT1( XMLFormsContext, SvXMLImportContext );

XMLFormsContext::XMLFormsContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLocalName )
: SvXMLImportContext(rImport, nPrfx, rLocalName)
{
}

XMLFormsContext::~XMLFormsContext()
{
}

SvXMLImportContext * XMLFormsContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
    return GetImport().GetFormImport()->createContext( nPrefix, rLocalName, xAttrList );
}
<|endoftext|>


<commit_before>/*-----------------------------------------------------------------------------------------------
The MIT License (MIT)

Copyright (c) 2015-2021 OSRE ( Open Source Render Engine ) by Kim Kulling

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-----------------------------------------------------------------------------------------------*/
#include <osre/Common/EventTriggerer.h>
#include <osre/Platform/PlatformInterface.h>
#include <osre/RenderBackend/RenderBackendService.h>
#include <src/Engine/Platform/win32/Win32EventQueue.h>
#include <src/Engine/Platform/win32/Win32Window.h>

#include <Windowsx.h>

namespace OSRE {
namespace Platform {

using namespace ::OSRE::Common;

static const c8 *Tag = "Win32Eventhandler";

// The interface for the event update.
struct AbstractInputUpdate {
    virtual ~AbstractInputUpdate() {
        // empty
    }

    virtual bool update(MSG &rProgram) = 0;
};

struct Win32GetInputUpdate : public AbstractInputUpdate {
    Win32GetInputUpdate() {
        // empty
    }

    ~Win32GetInputUpdate() override {
        // empty
    }

    bool update(MSG &program) override {
        if (1 == ::GetMessage(&program, NULL, 0, 0)) {
            return true;
        }

        return false;
    }
};

struct Win32PeekInputUpdate : public AbstractInputUpdate {
    Win32PeekInputUpdate() {
        // empty
    }

    ~Win32PeekInputUpdate() override {
        // empty
    }

    bool update(MSG &rProgram) override {
        if (1 == ::PeekMessage(&rProgram, NULL, 0, 0, PM_REMOVE)) {
            return true;
        }
        return false;
    }
};

static void getXYPosFromLParam(LPARAM lparam, i32 &x, i32 &y) {
    x = GET_X_LPARAM(lparam);
    y = GET_Y_LPARAM(lparam);
}

Win32EventQueue::WindowServerMap Win32EventQueue::s_WindowsServerMap;
Win32EventQueue::MenuFuncMap Win32EventQueue::s_MenuFunctorMap;

Win32EventQueue::Win32EventQueue(AbstractWindow *rootWindow) :
        AbstractPlatformEventQueue(),
        m_updateInstance(nullptr),
        m_eventTriggerer(nullptr),
        m_rootWindow(rootWindow),
        m_shutdownRequested(false),
        m_isPolling(true) {
    OSRE_ASSERT(nullptr != rootWindow);

    enablePolling(m_isPolling);
    m_eventTriggerer = new EventTriggerer;
    m_eventTriggerer->addTriggerableEvent(KeyboardButtonDownEvent);
    m_eventTriggerer->addTriggerableEvent(KeyboardButtonUpEvent);
    m_eventTriggerer->addTriggerableEvent(MouseButtonDownEvent);
    m_eventTriggerer->addTriggerableEvent(MouseButtonUpEvent);
    m_eventTriggerer->addTriggerableEvent(MouseMoveEvent);
    m_eventTriggerer->addTriggerableEvent(WindowsResizeEvent);
    m_eventTriggerer->addTriggerableEvent(QuitEvent);
    m_eventTriggerer->addTriggerableEvent(AppFocusEvent);
}

Win32EventQueue::~Win32EventQueue() {
    unregisterAllMenuCommands();

    m_rootWindow = nullptr;

    delete m_eventTriggerer;
    m_eventTriggerer = nullptr;

    delete m_updateInstance;
    m_updateInstance = nullptr;
}

bool Win32EventQueue::update() {
    EventDataList *activeEventQueue = getActiveEventDataList();
    if (nullptr == activeEventQueue) {
        return false;
    }
    MSG Program;
    if (!m_shutdownRequested && m_updateInstance->update(Program)) {
        switch (Program.message) {
            case WM_ACTIVATE: {
                Common::EventData *data = new Common::EventData(AppFocusEvent, m_eventTriggerer);
                activeEventQueue->addBack(data);
            } break;

            case WM_QUIT:
            case WM_CLOSE: {
                onQuit();
                m_shutdownRequested = true;
            } break;

            case WM_SYSCOMMAND: {
                switch (Program.wParam) {
                    case SC_SCREENSAVE:
                    case SC_MONITORPOWER:
                        return true;

                    default:
                        return false;
                }
            } break;

            case WM_LBUTTONDOWN: {
                MouseButtonEventData *data = new MouseButtonEventData(true, m_eventTriggerer);
                data->m_Button = MouseButtonEventData::LeftButton;
                getXYPosFromLParam(Program.lParam, data->m_AbsX, data->m_AbsY);
                activeEventQueue->addBack(data);
            } break;

            case WM_LBUTTONUP: {
                MouseButtonEventData *data = new MouseButtonEventData(false, m_eventTriggerer);
                data->m_Button = MouseButtonEventData::LeftButton;
                getXYPosFromLParam(Program.lParam, data->m_AbsX, data->m_AbsY);
                activeEventQueue->addBack(data);
            } break;

            case WM_MBUTTONDOWN: {
                MouseButtonEventData *data = new MouseButtonEventData(true, m_eventTriggerer);
                data->m_Button = MouseButtonEventData::MiddleButton;
                getXYPosFromLParam(Program.lParam, data->m_AbsX, data->m_AbsY);
                activeEventQueue->addBack(data);
            } break;

            case WM_MBUTTONUP: {
                MouseButtonEventData *data = new MouseButtonEventData(false, m_eventTriggerer);
                data->m_Button = MouseButtonEventData::MiddleButton;
                getXYPosFromLParam(Program.lParam, data->m_AbsX, data->m_AbsY);
                activeEventQueue->addBack(data);
            } break;

            case WM_RBUTTONDOWN: {
                MouseButtonEventData *data = new MouseButtonEventData(true, m_eventTriggerer);
                data->m_Button = MouseButtonEventData::RightButton;
                getXYPosFromLParam(Program.lParam, data->m_AbsX, data->m_AbsY);
                activeEventQueue->addBack(data);
            } break;

            case WM_RBUTTONUP: {
                MouseButtonEventData *data = new MouseButtonEventData(false, m_eventTriggerer);
                data->m_Button = MouseButtonEventData::RightButton;
                getXYPosFromLParam(Program.lParam, data->m_AbsX, data->m_AbsY);
                activeEventQueue->addBack(data);
            } break;

            case WM_MOUSEMOVE: {
                MouseMoveEventData *data = new MouseMoveEventData(m_eventTriggerer);
                getXYPosFromLParam(Program.lParam, data->m_absX, data->m_absY);
                activeEventQueue->addBack(data);
            } break;

            case WM_KEYDOWN:
            case WM_KEYUP: {
                KeyboardButtonEventData *data = new KeyboardButtonEventData(Program.message == WM_KEYDOWN, m_eventTriggerer);
                data->m_key = (Key)Program.wParam;
                activeEventQueue->addBack(data);
            } break;

            case WM_PAINT:
            case WM_SIZE: {
                WindowsResizeEventData *data = new WindowsResizeEventData(m_eventTriggerer);
                RECT rcClient;
                Win32Window *s = (Win32Window *)m_rootWindow;
                RECT rSB;
                if (nullptr != s) {
                auto handle = s->getStatusBarHandle();
                    if (nullptr != handle) {
                        GetWindowRect(s->getStatusBarHandle(), &rSB);
                        SendMessage(s->getStatusBarHandle(), WM_SIZE, 0, 0);
                    }
                    GetClientRect(s->getHWnd(), &rcClient);
                    ui32 x = rcClient.left;
                    ui32 y = rcClient.top;
                    ui32 w = rcClient.right - rcClient.left;
                    ui32 h = rcClient.bottom - rcClient.top;
                    RenderBackend::RenderBackendService *rbSrv = getRenderBackendService();
                    if (nullptr != rbSrv) {
                        rbSrv->resize(x, y, w, h);
                    }
                    activeEventQueue->addBack(data);
                }
            } break;
        }

        processEvents(m_eventTriggerer);

        ::TranslateMessage(&Program);
        ::DispatchMessage(&Program);
    }

    return !m_shutdownRequested;
}

LRESULT Win32EventQueue::winproc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) {
    Win32EventQueue *pEventHandler = Win32EventQueue::getInstance(hWnd);
    switch (Message) {
        case WM_ACTIVATE: {
            return 0;
        }

        case WM_SYSCOMMAND: {
            switch (wParam) {
                case SC_SCREENSAVE:
                case SC_MONITORPOWER:
                    return 0;

                case WM_KEYDOWN:
                    return 0;
            }
            break;
        }

        case WM_CLOSE: {
            if (pEventHandler) {
                pEventHandler->onQuit();
            } else {
                osre_error(Tag, "Nullptr to event handler detected.");
            }
            ::PostQuitMessage(NULL);
            return 1;
        }

        case WM_COMMAND:
            ui32 id = LOWORD(wParam);
            std::map<ui32, MenuFunctor>::iterator it = s_MenuFunctorMap.find(id);
            if (it != s_MenuFunctorMap.end()) {
                (it->second)(id, nullptr);
            }
            break;
    }

    return ::DefWindowProc(hWnd, Message, wParam, lParam);
}

void Win32EventQueue::registerEventQueue(Win32EventQueue *server, HWND hWnd) {
    s_WindowsServerMap[hWnd] = server;
}

void Win32EventQueue::unregisterEventQueue(Win32EventQueue *server, HWND hWnd) {
    std::map<HWND, Win32EventQueue *>::iterator it = s_WindowsServerMap.find(hWnd);
    if (s_WindowsServerMap.end() != it) {
        if (server != it->second) {
            osre_debug(Tag, "Invalid assignment frin eventqueue to window handle.");
        }
        s_WindowsServerMap.erase(it);
    }
}

Win32EventQueue *Win32EventQueue::getInstance(HWND hWnd) {
    auto it = s_WindowsServerMap.find(hWnd);
    if (s_WindowsServerMap.end() != it) {
        return it->second;
    }

    return nullptr;
}

void Win32EventQueue::onQuit() {
    Common::EventData data(QuitEvent, m_eventTriggerer);
    m_eventTriggerer->triggerEvent(data.getEvent(), &data);
    m_shutdownRequested = true;
}

void Win32EventQueue::setRootSurface(AbstractWindow *pSurface) {
    if (!pSurface) {
        osre_debug(Tag, "Invalid window pointer.");
        return;
    }

    Win32Window *pWin32Surface = (Win32Window *)pSurface;
    registerEventQueue(this, pWin32Surface->getHWnd());

    m_rootWindow = pWin32Surface;
}

AbstractWindow *Win32EventQueue::getRootSurface() const {
    return m_rootWindow;
}

void Win32EventQueue::enablePolling(bool enabled) {
    if (m_updateInstance && enabled == m_isPolling) {
        return;
    }

    if (m_updateInstance) {
        delete m_updateInstance;
        m_updateInstance = nullptr;
    }

    m_isPolling = enabled;

    if (m_isPolling) {
        m_updateInstance = new Win32PeekInputUpdate;
    } else {
        m_updateInstance = new Win32GetInputUpdate;
    }
}

bool Win32EventQueue::isPolling() const {
    return m_isPolling;
}

void Win32EventQueue::registerEventListener(const EventPtrArray &events, OSEventListener *pListener) {
    OSRE_ASSERT(nullptr != m_eventTriggerer);

    if (nullptr == m_eventTriggerer) {
        osre_error(Tag, "Pointer to event-triggerer is nullptr.");
        return;
    }

    m_eventTriggerer->addEventListener(events, Common::EventFunctor::Make(pListener,
                                                       &OSEventListener::onOSEvent));
}

void Win32EventQueue::unregisterEventListener(const EventPtrArray &events, OSEventListener *pListener) {
    OSRE_ASSERT(nullptr != m_eventTriggerer);

    if (nullptr == m_eventTriggerer) {
        osre_error(Tag, "Pointer to event-triggerer is nullptr.");
        return;
    }

    m_eventTriggerer->removeEventListener(events, Common::EventFunctor::Make(pListener,
                                                          &OSEventListener::onOSEvent));
}

void Win32EventQueue::unregisterAllEventHandler(const EventPtrArray &events) {
    OSRE_ASSERT(nullptr != m_eventTriggerer);

    if (nullptr == m_eventTriggerer) {
        osre_error(Tag, "Pointer to event-triggerer is nullptr.");
        return;
    }

    m_eventTriggerer->removeAllEventListeners(events);
}

void Win32EventQueue::registerMenuCommand(ui32 id, MenuFunctor func) {
    s_MenuFunctorMap[id] = func;
    func.incRef();
}

void Win32EventQueue::unregisterAllMenuCommands() {
    s_MenuFunctorMap.clear();
}

} // Namespace Platform
} // Namespace OSRE
<commit_msg>Fix formatting<commit_after>/*-----------------------------------------------------------------------------------------------
The MIT License (MIT)

Copyright (c) 2015-2021 OSRE ( Open Source Render Engine ) by Kim Kulling

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-----------------------------------------------------------------------------------------------*/
#include <osre/Common/EventTriggerer.h>
#include <osre/Platform/PlatformInterface.h>
#include <osre/RenderBackend/RenderBackendService.h>
#include <src/Engine/Platform/win32/Win32EventQueue.h>
#include <src/Engine/Platform/win32/Win32Window.h>

#include <Windowsx.h>

namespace OSRE {
namespace Platform {

using namespace ::OSRE::Common;

static const c8 *Tag = "Win32Eventhandler";

// The interface for the event update.
struct AbstractInputUpdate {
    virtual ~AbstractInputUpdate() {
        // empty
    }

    virtual bool update(MSG &rProgram) = 0;
};

struct Win32GetInputUpdate : public AbstractInputUpdate {
    Win32GetInputUpdate() {
        // empty
    }

    ~Win32GetInputUpdate() override {
        // empty
    }

    bool update(MSG &program) override {
        if (1 == ::GetMessage(&program, NULL, 0, 0)) {
            return true;
        }

        return false;
    }
};

struct Win32PeekInputUpdate : public AbstractInputUpdate {
    Win32PeekInputUpdate() {
        // empty
    }

    ~Win32PeekInputUpdate() override {
        // empty
    }

    bool update(MSG &rProgram) override {
        if (1 == ::PeekMessage(&rProgram, NULL, 0, 0, PM_REMOVE)) {
            return true;
        }
        return false;
    }
};

static void getXYPosFromLParam(LPARAM lparam, i32 &x, i32 &y) {
    x = GET_X_LPARAM(lparam);
    y = GET_Y_LPARAM(lparam);
}

Win32EventQueue::WindowServerMap Win32EventQueue::s_WindowsServerMap;
Win32EventQueue::MenuFuncMap Win32EventQueue::s_MenuFunctorMap;

Win32EventQueue::Win32EventQueue(AbstractWindow *rootWindow) :
        AbstractPlatformEventQueue(),
        m_updateInstance(nullptr),
        m_eventTriggerer(nullptr),
        m_rootWindow(rootWindow),
        m_shutdownRequested(false),
        m_isPolling(true) {
    OSRE_ASSERT(nullptr != rootWindow);

    enablePolling(m_isPolling);
    m_eventTriggerer = new EventTriggerer;
    m_eventTriggerer->addTriggerableEvent(KeyboardButtonDownEvent);
    m_eventTriggerer->addTriggerableEvent(KeyboardButtonUpEvent);
    m_eventTriggerer->addTriggerableEvent(MouseButtonDownEvent);
    m_eventTriggerer->addTriggerableEvent(MouseButtonUpEvent);
    m_eventTriggerer->addTriggerableEvent(MouseMoveEvent);
    m_eventTriggerer->addTriggerableEvent(WindowsResizeEvent);
    m_eventTriggerer->addTriggerableEvent(QuitEvent);
    m_eventTriggerer->addTriggerableEvent(AppFocusEvent);
}

Win32EventQueue::~Win32EventQueue() {
    unregisterAllMenuCommands();

    m_rootWindow = nullptr;

    delete m_eventTriggerer;
    m_eventTriggerer = nullptr;

    delete m_updateInstance;
    m_updateInstance = nullptr;
}

bool Win32EventQueue::update() {
    EventDataList *activeEventQueue = getActiveEventDataList();
    if (nullptr == activeEventQueue) {
        return false;
    }
    MSG Program;
    if (!m_shutdownRequested && m_updateInstance->update(Program)) {
        switch (Program.message) {
            case WM_ACTIVATE: {
                Common::EventData *data = new Common::EventData(AppFocusEvent, m_eventTriggerer);
                activeEventQueue->addBack(data);
            } break;

            case WM_QUIT:
            case WM_CLOSE: {
                onQuit();
                m_shutdownRequested = true;
            } break;

            case WM_SYSCOMMAND: {
                switch (Program.wParam) {
                    case SC_SCREENSAVE:
                    case SC_MONITORPOWER:
                        return true;

                    default:
                        return false;
                }
            } break;

            case WM_LBUTTONDOWN: {
                MouseButtonEventData *data = new MouseButtonEventData(true, m_eventTriggerer);
                data->m_Button = MouseButtonEventData::LeftButton;
                getXYPosFromLParam(Program.lParam, data->m_AbsX, data->m_AbsY);
                activeEventQueue->addBack(data);
            } break;

            case WM_LBUTTONUP: {
                MouseButtonEventData *data = new MouseButtonEventData(false, m_eventTriggerer);
                data->m_Button = MouseButtonEventData::LeftButton;
                getXYPosFromLParam(Program.lParam, data->m_AbsX, data->m_AbsY);
                activeEventQueue->addBack(data);
            } break;

            case WM_MBUTTONDOWN: {
                MouseButtonEventData *data = new MouseButtonEventData(true, m_eventTriggerer);
                data->m_Button = MouseButtonEventData::MiddleButton;
                getXYPosFromLParam(Program.lParam, data->m_AbsX, data->m_AbsY);
                activeEventQueue->addBack(data);
            } break;

            case WM_MBUTTONUP: {
                MouseButtonEventData *data = new MouseButtonEventData(false, m_eventTriggerer);
                data->m_Button = MouseButtonEventData::MiddleButton;
                getXYPosFromLParam(Program.lParam, data->m_AbsX, data->m_AbsY);
                activeEventQueue->addBack(data);
            } break;

            case WM_RBUTTONDOWN: {
                MouseButtonEventData *data = new MouseButtonEventData(true, m_eventTriggerer);
                data->m_Button = MouseButtonEventData::RightButton;
                getXYPosFromLParam(Program.lParam, data->m_AbsX, data->m_AbsY);
                activeEventQueue->addBack(data);
            } break;

            case WM_RBUTTONUP: {
                MouseButtonEventData *data = new MouseButtonEventData(false, m_eventTriggerer);
                data->m_Button = MouseButtonEventData::RightButton;
                getXYPosFromLParam(Program.lParam, data->m_AbsX, data->m_AbsY);
                activeEventQueue->addBack(data);
            } break;

            case WM_MOUSEMOVE: {
                MouseMoveEventData *data = new MouseMoveEventData(m_eventTriggerer);
                getXYPosFromLParam(Program.lParam, data->m_absX, data->m_absY);
                activeEventQueue->addBack(data);
            } break;

            case WM_KEYDOWN:
            case WM_KEYUP: {
                KeyboardButtonEventData *data = new KeyboardButtonEventData(Program.message == WM_KEYDOWN, m_eventTriggerer);
                data->m_key = (Key)Program.wParam;
                activeEventQueue->addBack(data);
            } break;

            case WM_PAINT:
            case WM_SIZE: {
                WindowsResizeEventData *data = new WindowsResizeEventData(m_eventTriggerer);
                RECT rcClient;
                Win32Window *s = (Win32Window *)m_rootWindow;
                RECT rSB;
                if (nullptr != s) {
                    auto handle = s->getStatusBarHandle();
                    if (nullptr != handle) {
                        GetWindowRect(s->getStatusBarHandle(), &rSB);
                        SendMessage(s->getStatusBarHandle(), WM_SIZE, 0, 0);
                    }
                    GetClientRect(s->getHWnd(), &rcClient);
                    ui32 x = rcClient.left;
                    ui32 y = rcClient.top;
                    ui32 w = rcClient.right - rcClient.left;
                    ui32 h = rcClient.bottom - rcClient.top;
                    RenderBackend::RenderBackendService *rbSrv = getRenderBackendService();
                    if (nullptr != rbSrv) {
                        rbSrv->resize(x, y, w, h);
                    }
                    activeEventQueue->addBack(data);
                }
            } break;
        }

        processEvents(m_eventTriggerer);

        ::TranslateMessage(&Program);
        ::DispatchMessage(&Program);
    }

    return !m_shutdownRequested;
}

LRESULT Win32EventQueue::winproc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) {
    Win32EventQueue *pEventHandler = Win32EventQueue::getInstance(hWnd);
    switch (Message) {
        case WM_ACTIVATE: {
            return 0;
        }

        case WM_SYSCOMMAND: {
            switch (wParam) {
                case SC_SCREENSAVE:
                case SC_MONITORPOWER:
                    return 0;

                case WM_KEYDOWN:
                    return 0;
            }
            break;
        }

        case WM_CLOSE: {
            if (pEventHandler) {
                pEventHandler->onQuit();
            } else {
                osre_error(Tag, "Nullptr to event handler detected.");
            }
            ::PostQuitMessage(NULL);
            return 1;
        }

        case WM_COMMAND:
            ui32 id = LOWORD(wParam);
            std::map<ui32, MenuFunctor>::iterator it = s_MenuFunctorMap.find(id);
            if (it != s_MenuFunctorMap.end()) {
                (it->second)(id, nullptr);
            }
            break;
    }

    return ::DefWindowProc(hWnd, Message, wParam, lParam);
}

void Win32EventQueue::registerEventQueue(Win32EventQueue *server, HWND hWnd) {
    s_WindowsServerMap[hWnd] = server;
}

void Win32EventQueue::unregisterEventQueue(Win32EventQueue *server, HWND hWnd) {
    std::map<HWND, Win32EventQueue *>::iterator it = s_WindowsServerMap.find(hWnd);
    if (s_WindowsServerMap.end() != it) {
        if (server != it->second) {
            osre_debug(Tag, "Invalid assignment frin eventqueue to window handle.");
        }
        s_WindowsServerMap.erase(it);
    }
}

Win32EventQueue *Win32EventQueue::getInstance(HWND hWnd) {
    auto it = s_WindowsServerMap.find(hWnd);
    if (s_WindowsServerMap.end() != it) {
        return it->second;
    }

    return nullptr;
}

void Win32EventQueue::onQuit() {
    Common::EventData data(QuitEvent, m_eventTriggerer);
    m_eventTriggerer->triggerEvent(data.getEvent(), &data);
    m_shutdownRequested = true;
}

void Win32EventQueue::setRootSurface(AbstractWindow *pSurface) {
    if (!pSurface) {
        osre_debug(Tag, "Invalid window pointer.");
        return;
    }

    Win32Window *pWin32Surface = (Win32Window *)pSurface;
    registerEventQueue(this, pWin32Surface->getHWnd());

    m_rootWindow = pWin32Surface;
}

AbstractWindow *Win32EventQueue::getRootSurface() const {
    return m_rootWindow;
}

void Win32EventQueue::enablePolling(bool enabled) {
    if (m_updateInstance && enabled == m_isPolling) {
        return;
    }

    if (m_updateInstance) {
        delete m_updateInstance;
        m_updateInstance = nullptr;
    }

    m_isPolling = enabled;

    if (m_isPolling) {
        m_updateInstance = new Win32PeekInputUpdate;
    } else {
        m_updateInstance = new Win32GetInputUpdate;
    }
}

bool Win32EventQueue::isPolling() const {
    return m_isPolling;
}

void Win32EventQueue::registerEventListener(const EventPtrArray &events, OSEventListener *pListener) {
    OSRE_ASSERT(nullptr != m_eventTriggerer);

    if (nullptr == m_eventTriggerer) {
        osre_error(Tag, "Pointer to event-triggerer is nullptr.");
        return;
    }

    m_eventTriggerer->addEventListener(events, Common::EventFunctor::Make(pListener,
                                                       &OSEventListener::onOSEvent));
}

void Win32EventQueue::unregisterEventListener(const EventPtrArray &events, OSEventListener *pListener) {
    OSRE_ASSERT(nullptr != m_eventTriggerer);

    if (nullptr == m_eventTriggerer) {
        osre_error(Tag, "Pointer to event-triggerer is nullptr.");
        return;
    }

    m_eventTriggerer->removeEventListener(events, Common::EventFunctor::Make(pListener,
                                                          &OSEventListener::onOSEvent));
}

void Win32EventQueue::unregisterAllEventHandler(const EventPtrArray &events) {
    OSRE_ASSERT(nullptr != m_eventTriggerer);

    if (nullptr == m_eventTriggerer) {
        osre_error(Tag, "Pointer to event-triggerer is nullptr.");
        return;
    }

    m_eventTriggerer->removeAllEventListeners(events);
}

void Win32EventQueue::registerMenuCommand(ui32 id, MenuFunctor func) {
    s_MenuFunctorMap[id] = func;
    func.incRef();
}

void Win32EventQueue::unregisterAllMenuCommands() {
    s_MenuFunctorMap.clear();
}

} // Namespace Platform
} // Namespace OSRE
<|endoftext|>


<commit_before>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

#include <gtest/gtest.h>

#include <DO/Geometry/Objects.hpp>

#include "TestPolygon.hpp"

using namespace std;
using namespace DO;

class TestTriangle : public TestPolygon {};

TEST_F(TestTriangle, test_constructor_and_area_computation)
{
  Triangle t1(Point2d(0,0), Point2d(100, 0), Point2d(100, 100));
  EXPECT_NEAR(area(t1), 1e4/2., 1e-10);

  Triangle t2(Point2d(100,0), Point2d(0, 0), Point2d(100, 100));
  EXPECT_NEAR(signedArea(t2), -1e4/2., 1e-10);
}

TEST_F(TestTriangle, test_point_inside_triangle)
{
  Triangle t3(Point2d(50, 73), Point2d(350, 400), Point2d(25, 200));

  double exactArea3 = area(t3);
  int pixelArea3 = sweep_pixel_count([&](Point2d& p) {
    return inside(p, t3);
  });

  double relError = fabs(exactArea3 - pixelArea3)/exactArea3;
  EXPECT_NEAR(relError, 0., 5e-2);
}

int main(int argc, char** argv)
{
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}<commit_msg>Fix typo in method calls and use `lower_case_naming_style`.<commit_after>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

#include <gtest/gtest.h>

#include <DO/Geometry/Objects.hpp>

#include "TestPolygon.hpp"

using namespace std;
using namespace DO;

class TestTriangle : public TestPolygon {};

TEST_F(TestTriangle, test_constructor_and_area_computation)
{
  Triangle t1(Point2d(0,0), Point2d(100, 0), Point2d(100, 100));
  EXPECT_NEAR(area(t1), 1e4/2., 1e-10);

  Triangle t2(Point2d(100,0), Point2d(0, 0), Point2d(100, 100));
  EXPECT_NEAR(signedArea(t2), -1e4/2., 1e-10);
}

TEST_F(TestTriangle, test_point_inside_triangle)
{
  Triangle t(Point2d(50, 73), Point2d(350, 400), Point2d(25, 200));

  double exact_area = area(t);
  int pixel_area = sweep_count_pixels([&](Point2d& p) {
    return inside(p, t);
  });

  double relError = fabs(exact_area - pixel_area) / exact_area;
  EXPECT_NEAR(relError, 0., 5e-2);
}

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


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/glue/webcursor.h"
#include "webkit/glue/webkit_resources.h"

#if defined(OS_WIN)
#include "base/gfx/gdi_util.h"
#endif

WebCursor::WebCursor()
    : type_(ARROW),
      hotspot_x_(0),
      hotspot_y_(0),
      bitmap_() {
}

WebCursor::WebCursor(Type cursor_type)
    : type_(cursor_type),
      hotspot_x_(0),
      hotspot_y_(0),
      bitmap_() {
}

WebCursor::WebCursor(const WebCursorBitmapPtr bitmap,
                     int hotspot_x,
                     int hotspot_y)
    : type_(ARROW),
      hotspot_x_(0),
      hotspot_y_(0) {
  if (bitmap) {
    type_ = CUSTOM;
    hotspot_x_ = hotspot_x;
    hotspot_y_ = hotspot_y;
#if defined(OS_MACOSX)
    CGImageRetain(bitmap_ = bitmap);
#else
    bitmap_ = *bitmap;
#endif
  } else {
#if defined(OS_MACOSX)
    bitmap_ = NULL;
#else
    memset(&bitmap_, 0, sizeof(bitmap_));
#endif
  }
}

WebCursor::~WebCursor() {
#if defined(OS_MACOSX)
  CGImageRelease(bitmap_);
#endif
}

WebCursor::WebCursor(const WebCursor& other) {
  type_ = other.type_;
  hotspot_x_ = other.hotspot_x_;
  hotspot_y_ = other.hotspot_y_;
#if defined(OS_MACOSX)
  bitmap_ = NULL;  // set_bitmap releases bitmap_.
#endif
  set_bitmap(other.bitmap_);
}

WebCursor& WebCursor::operator=(const WebCursor& other) {
  if (this != &other) {
    type_ = other.type_;
    hotspot_x_ = other.hotspot_x_;
    hotspot_y_ = other.hotspot_y_;
    set_bitmap(other.bitmap_);
  }
  return *this;
}

#if defined(OS_WIN)
HCURSOR WebCursor::GetCursor(HINSTANCE module_handle) const {
  if (type_ == CUSTOM)
    return NULL;

  static LPCWSTR cursor_resources[] = {
    IDC_ARROW,
    IDC_IBEAM,
    IDC_WAIT,
    IDC_CROSS,
    IDC_UPARROW,
    IDC_SIZE,
    IDC_ICON,
    IDC_SIZENWSE,
    IDC_SIZENESW,
    IDC_SIZEWE,
    IDC_SIZENS,
    IDC_SIZEALL,
    IDC_NO,
    IDC_HAND,
    IDC_APPSTARTING,
    IDC_HELP,
    // webkit resources
    MAKEINTRESOURCE(IDC_ALIAS),
    MAKEINTRESOURCE(IDC_CELL),
    MAKEINTRESOURCE(IDC_COLRESIZE),
    MAKEINTRESOURCE(IDC_COPYCUR),
    MAKEINTRESOURCE(IDC_ROWRESIZE),
    MAKEINTRESOURCE(IDC_VERTICALTEXT),
    MAKEINTRESOURCE(IDC_ZOOMIN),
    MAKEINTRESOURCE(IDC_ZOOMOUT)
  };

  HINSTANCE instance_to_use = NULL;
  if (type_ > HELP)
    instance_to_use = module_handle;

  HCURSOR cursor_handle = LoadCursor(instance_to_use,
                                     cursor_resources[type_]);
  return cursor_handle;
}

HCURSOR WebCursor::GetCustomCursor() const {
  if (type_ != CUSTOM)
    return NULL;

  BITMAPINFO cursor_bitmap_info = {0};
  gfx::CreateBitmapHeader(bitmap_.width(), bitmap_.height(),
                          reinterpret_cast<BITMAPINFOHEADER*>(&cursor_bitmap_info));
  HDC dc = ::GetDC(0);
  HDC workingDC = CreateCompatibleDC(dc);
  HBITMAP bitmap_handle = CreateDIBSection(dc, &cursor_bitmap_info,
                                           DIB_RGB_COLORS, 0, 0, 0);
  SkAutoLockPixels bitmap_lock(bitmap_);
  SetDIBits(0, bitmap_handle, 0, bitmap_.width(),
            bitmap_.getPixels(), &cursor_bitmap_info, DIB_RGB_COLORS);

  HBITMAP old_bitmap = reinterpret_cast<HBITMAP>(SelectObject(workingDC,
                                                              bitmap_handle));
  SetBkMode(workingDC, TRANSPARENT);
  SelectObject(workingDC, old_bitmap);

  HBITMAP mask = CreateBitmap(bitmap_.width(), bitmap_.height(),
                              1, 1, NULL);
  ICONINFO ii = {0};
  ii.fIcon = FALSE;
  ii.xHotspot = hotspot_x_;
  ii.yHotspot = hotspot_y_;
  ii.hbmMask = mask;
  ii.hbmColor = bitmap_handle;

  HCURSOR cursor_handle = CreateIconIndirect(&ii);

  DeleteObject(mask);
  DeleteObject(bitmap_handle);
  DeleteDC(workingDC);
  ::ReleaseDC(0, dc);
  return cursor_handle;
}
#endif

#if !defined(OS_MACOSX)
bool WebCursor::IsSameBitmap(const WebCursorBitmap& bitmap) const {
  SkAutoLockPixels new_bitmap_lock(bitmap);
  SkAutoLockPixels bitmap_lock(bitmap_);
  return (memcmp(bitmap_.getPixels(), bitmap.getPixels(),
                 bitmap_.getSize()) == 0);
}

bool WebCursor::IsEqual(const WebCursor& other) const {
  if (type_ != other.type_)
    return false;

  if(type_ == CUSTOM)
    return IsSameBitmap(other.bitmap_);
  return true;
}
#endif
<commit_msg>Fix a bug in cursor handling when the width and height of the image differ. We were using the width of the image, when the width is actually inferred by the Windows API call. Instead, we were supposed to pass the height.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/glue/webcursor.h"
#include "webkit/glue/webkit_resources.h"

#if defined(OS_WIN)
#include "base/gfx/gdi_util.h"
#endif

WebCursor::WebCursor()
    : type_(ARROW),
      hotspot_x_(0),
      hotspot_y_(0),
      bitmap_() {
}

WebCursor::WebCursor(Type cursor_type)
    : type_(cursor_type),
      hotspot_x_(0),
      hotspot_y_(0),
      bitmap_() {
}

WebCursor::WebCursor(const WebCursorBitmapPtr bitmap,
                     int hotspot_x,
                     int hotspot_y)
    : type_(ARROW),
      hotspot_x_(0),
      hotspot_y_(0) {
  if (bitmap) {
    type_ = CUSTOM;
    hotspot_x_ = hotspot_x;
    hotspot_y_ = hotspot_y;
#if defined(OS_MACOSX)
    CGImageRetain(bitmap_ = bitmap);
#else
    bitmap_ = *bitmap;
#endif
  } else {
#if defined(OS_MACOSX)
    bitmap_ = NULL;
#else
    memset(&bitmap_, 0, sizeof(bitmap_));
#endif
  }
}

WebCursor::~WebCursor() {
#if defined(OS_MACOSX)
  CGImageRelease(bitmap_);
#endif
}

WebCursor::WebCursor(const WebCursor& other) {
  type_ = other.type_;
  hotspot_x_ = other.hotspot_x_;
  hotspot_y_ = other.hotspot_y_;
#if defined(OS_MACOSX)
  bitmap_ = NULL;  // set_bitmap releases bitmap_.
#endif
  set_bitmap(other.bitmap_);
}

WebCursor& WebCursor::operator=(const WebCursor& other) {
  if (this != &other) {
    type_ = other.type_;
    hotspot_x_ = other.hotspot_x_;
    hotspot_y_ = other.hotspot_y_;
    set_bitmap(other.bitmap_);
  }
  return *this;
}

#if defined(OS_WIN)
HCURSOR WebCursor::GetCursor(HINSTANCE module_handle) const {
  if (type_ == CUSTOM)
    return NULL;

  static LPCWSTR cursor_resources[] = {
    IDC_ARROW,
    IDC_IBEAM,
    IDC_WAIT,
    IDC_CROSS,
    IDC_UPARROW,
    IDC_SIZE,
    IDC_ICON,
    IDC_SIZENWSE,
    IDC_SIZENESW,
    IDC_SIZEWE,
    IDC_SIZENS,
    IDC_SIZEALL,
    IDC_NO,
    IDC_HAND,
    IDC_APPSTARTING,
    IDC_HELP,
    // webkit resources
    MAKEINTRESOURCE(IDC_ALIAS),
    MAKEINTRESOURCE(IDC_CELL),
    MAKEINTRESOURCE(IDC_COLRESIZE),
    MAKEINTRESOURCE(IDC_COPYCUR),
    MAKEINTRESOURCE(IDC_ROWRESIZE),
    MAKEINTRESOURCE(IDC_VERTICALTEXT),
    MAKEINTRESOURCE(IDC_ZOOMIN),
    MAKEINTRESOURCE(IDC_ZOOMOUT)
  };

  HINSTANCE instance_to_use = NULL;
  if (type_ > HELP)
    instance_to_use = module_handle;

  HCURSOR cursor_handle = LoadCursor(instance_to_use,
                                     cursor_resources[type_]);
  return cursor_handle;
}

HCURSOR WebCursor::GetCustomCursor() const {
  if (type_ != CUSTOM)
    return NULL;

  BITMAPINFO cursor_bitmap_info = {0};
  gfx::CreateBitmapHeader(bitmap_.width(), bitmap_.height(),
                          reinterpret_cast<BITMAPINFOHEADER*>(&cursor_bitmap_info));
  HDC dc = ::GetDC(0);
  HDC workingDC = CreateCompatibleDC(dc);
  HBITMAP bitmap_handle = CreateDIBSection(dc, &cursor_bitmap_info,
                                           DIB_RGB_COLORS, 0, 0, 0);
  SkAutoLockPixels bitmap_lock(bitmap_);
  SetDIBits(0, bitmap_handle, 0, bitmap_.height(),
            bitmap_.getPixels(), &cursor_bitmap_info, DIB_RGB_COLORS);

  HBITMAP old_bitmap = reinterpret_cast<HBITMAP>(SelectObject(workingDC,
                                                              bitmap_handle));
  SetBkMode(workingDC, TRANSPARENT);
  SelectObject(workingDC, old_bitmap);

  HBITMAP mask = CreateBitmap(bitmap_.width(), bitmap_.height(),
                              1, 1, NULL);
  ICONINFO ii = {0};
  ii.fIcon = FALSE;
  ii.xHotspot = hotspot_x_;
  ii.yHotspot = hotspot_y_;
  ii.hbmMask = mask;
  ii.hbmColor = bitmap_handle;

  HCURSOR cursor_handle = CreateIconIndirect(&ii);

  DeleteObject(mask);
  DeleteObject(bitmap_handle);
  DeleteDC(workingDC);
  ::ReleaseDC(0, dc);
  return cursor_handle;
}
#endif

#if !defined(OS_MACOSX)
bool WebCursor::IsSameBitmap(const WebCursorBitmap& bitmap) const {
  SkAutoLockPixels new_bitmap_lock(bitmap);
  SkAutoLockPixels bitmap_lock(bitmap_);
  return (memcmp(bitmap_.getPixels(), bitmap.getPixels(),
                 bitmap_.getSize()) == 0);
}

bool WebCursor::IsEqual(const WebCursor& other) const {
  if (type_ != other.type_)
    return false;

  if(type_ == CUSTOM)
    return IsSameBitmap(other.bitmap_);
  return true;
}
#endif
<|endoftext|>