<commit_before>/*
 * Contact groups model
 * This file is based on TelepathyQt4Yell Models
 *
 * Copyright (C) 2010 Collabora Ltd. <http://www.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 <TelepathyQt4/ContactManager>
#include <TelepathyQt4/Contact>
#include <TelepathyQt4/PendingReady>

#include "groups-model.h"
#include "groups-model-item.h"
#include "proxy-tree-node.h"
#include "accounts-model.h"
#include "contact-model-item.h"

#include <KDebug>

struct GroupsModel::Private
{
    Private(AccountsModel *am)
        : mAM(am)
    {
    }

    TreeNode *node(const QModelIndex &index) const;

    AccountsModel *mAM;
    TreeNode *mTree;
};

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

GroupsModel::GroupsModel(AccountsModel *am, QObject *parent)
    : QAbstractItemModel(parent),
      mPriv(new GroupsModel::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)));

    loadAccountsModel();
    QHash<int, QByteArray> roles;
    roles[GroupNameRole] = "groupName";
    setRoleNames(roles);
}

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

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

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

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

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

Qt::ItemFlags GroupsModel::flags(const QModelIndex &index) const
{
    if (index.isValid()) {
        return Qt::ItemIsEnabled;
    }

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

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

    return false;
}

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

    return QModelIndex();
}

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

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

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

void GroupsModel::onItemChanged(TreeNode* node)
{
    emit dataChanged(index(node), index(node));
}

void GroupsModel::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();
}

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

void GroupsModel::onSourceItemsAdded(TreeNode *parent, const QList<TreeNode *> &nodes)
{
    kDebug() << "Adding" << nodes.size() << "nodes...";
    QModelIndex parentIndex = index(parent);
    int currentSize = rowCount(parentIndex);
    foreach (TreeNode *node, nodes) {
        ContactModelItem *contactItem = qobject_cast<ContactModelItem*>(node);
        QStringList groups = contactItem->contact()->groups();
        addContactToGroups(contactItem, groups);
    }
}

void GroupsModel::onSourceItemsRemoved(TreeNode* parent, int first, int last)
{

}

void GroupsModel::loadAccountsModel()
{
    for (int x = 0; x < mPriv->mAM->rowCount(); x++) {
        QModelIndex parent = mPriv->mAM->index(x, 0);
        for (int i = 0; i < mPriv->mAM->rowCount(parent); i++) {
            if (mPriv->mAM->data(mPriv->mAM->index(i, 0, parent),
                                 AccountsModel::ItemRole).userType() == qMetaTypeId<ContactModelItem*>()) {

                QStringList groups = mPriv->mAM->data(mPriv->mAM->index(i, 0, parent),
                                                      AccountsModel::GroupsRole).toStringList();

                ContactModelItem *contactItem = mPriv->mAM->data(mPriv->mAM->index(i, 0, parent),
                                                                 AccountsModel::ItemRole).value<ContactModelItem*>();

                addContactToGroups(contactItem, groups);
            }
        }

        //we need to connect accounts onItemsAdded/onItemsRemoved to watch for changes
        //and process them directly (directly add/remove the nodes)
        AccountsModelItem *accountItem = mPriv->mAM->data(parent, AccountsModel::ItemRole).value<AccountsModelItem*>();
        connect(accountItem, SIGNAL(childrenAdded(TreeNode*,QList<TreeNode*>)),
                this, SLOT(onSourceItemsAdded(TreeNode*,QList<TreeNode*>)));

        connect(accountItem, SIGNAL(childrenRemoved(TreeNode*,int,int)),
                this, SLOT(onSourceItemsRemoved(TreeNode*,int,int)));

        kDebug() << "Connecting" << accountItem->account()->displayName() << "to groups model";

    }
}

void GroupsModel::onContactAddedToGroup(const QString& group)
{
    addContactToGroups(qobject_cast<ProxyTreeNode*>(sender()), group);
}

void GroupsModel::onContactRemovedFromGroup(const QString& group)
{
    removeContactFromGroup(qobject_cast<ProxyTreeNode*>(sender()), group);
}

void GroupsModel::removeContactFromGroup(ProxyTreeNode* proxyNode, const QString& group)
{
    kDebug() << "Removing contact from" << group;

    QStringList contactGroups = proxyNode->data(AccountsModel::ItemRole).value<ContactModelItem*>()->contact()->groups();
    kDebug() << "Left groups are:" << contactGroups;

    contactGroups.removeOne(group);

    //if the contact really is in that group, remove it
    if (qobject_cast<GroupsModelItem*>(proxyNode->parent())->groupName() == group) {

        disconnect(proxyNode, SIGNAL(contactAddedToGroup(QString)), 0, 0);
        disconnect(proxyNode, SIGNAL(contactRemovedFromGroup(QString)), 0, 0);

        //if the the contact has no groups left, then put it in Ungroupped group
        if (contactGroups.isEmpty()) {
            addContactToGroups(proxyNode->data(AccountsModel::ItemRole).value<ContactModelItem*>(), contactGroups);
        }

//         beginRemoveRows(index(proxyNode->parent()), proxyNode->parent()->indexOf(proxyNode), proxyNode->parent()->indexOf(proxyNode));
        qobject_cast<GroupsModelItem*>(proxyNode->parent())->removeProxyContact(proxyNode);
//         endRemoveRows();
    }
}

void GroupsModel::addContactToGroups(ProxyTreeNode* proxyNode, const QString& group)
{
    addContactToGroups(proxyNode->data(AccountsModel::ItemRole).value<ContactModelItem*>(), group);
}

void GroupsModel::addContactToGroups(ContactModelItem* contactItem, const QString& group)
{
    addContactToGroups(contactItem, QStringList(group));
}

void GroupsModel::addContactToGroups(ContactModelItem* contactItem, QStringList groups)
{
    kDebug() << "Contact groups:" << groups;

    //check if the contact is in Ungroupped group, if it is, it needs to be removed from there
    bool checkUngroupped = false;
    //if the contact has no groups, create an 'Ungroupped' group for it
    if (groups.isEmpty()) {
        groups.append("Ungroupped"); //FIXME i18n
    } else {
        checkUngroupped = true;
    }

    groups.removeDuplicates();

    foreach (QString group, groups) {
        bool groupExists = false;
        GroupsModelItem *groupItem;

        kDebug() << "Adding" << contactItem->contact()->alias() << "to" << group;

        //check if the group already exists first
        for (int i = 0; i < mPriv->mTree->children().size(); i++) {
//         foreach (GroupsModelItem *savedGroupItem, mPriv->mTree->children()) {
            GroupsModelItem *savedGroupItem = qobject_cast<GroupsModelItem*>(mPriv->mTree->childAt(i));
            if (savedGroupItem->groupName() == group) {
                groupExists = true;
                kDebug() << "Existing group found for" << group;
                groupItem = savedGroupItem;

                if (!checkUngroupped) {
                    break;
                }
            }
            if (checkUngroupped) {
                if (savedGroupItem->groupName() == "Ungroupped") {
                    for (int i = 0; i < savedGroupItem->size(); i++) {
                        ProxyTreeNode *tmpNode = qobject_cast<ProxyTreeNode*>(savedGroupItem->childAt(i));
                        if (tmpNode->data(AccountsModel::ItemRole).value<ContactModelItem*>()->contact()->id() == contactItem->contact()->id()) {
                            removeContactFromGroup(tmpNode, QString("Ungroupped"));
                            if (groupExists) {
                                break;
                            }
                        }
                    }
                }
            }
        }

        if (!groupExists) {
            kDebug() << "Creating new group for" << group;
            groupItem = new GroupsModelItem(group);
            onItemsAdded(mPriv->mTree, QList<TreeNode *>() << groupItem);
        }

        ProxyTreeNode *proxyNode = new ProxyTreeNode(contactItem);
        groupItem->addProxyContact(proxyNode);

        connect(proxyNode, SIGNAL(contactAddedToGroup(QString)),
                this, SLOT(onContactAddedToGroup(QString)));

        connect(proxyNode, SIGNAL(contactRemovedFromGroup(QString)),
                this, SLOT(onContactRemovedFromGroup(QString)));

    }
}

<commit_msg>Fix typo<commit_after>/*
 * Contact groups model
 * This file is based on TelepathyQt4Yell Models
 *
 * Copyright (C) 2010 Collabora Ltd. <http://www.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 <TelepathyQt4/ContactManager>
#include <TelepathyQt4/Contact>
#include <TelepathyQt4/PendingReady>

#include "groups-model.h"
#include "groups-model-item.h"
#include "proxy-tree-node.h"
#include "accounts-model.h"
#include "contact-model-item.h"

#include <KDebug>

struct GroupsModel::Private
{
    Private(AccountsModel *am)
        : mAM(am)
    {
    }

    TreeNode *node(const QModelIndex &index) const;

    AccountsModel *mAM;
    TreeNode *mTree;
};

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

GroupsModel::GroupsModel(AccountsModel *am, QObject *parent)
    : QAbstractItemModel(parent),
      mPriv(new GroupsModel::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)));

    loadAccountsModel();
    QHash<int, QByteArray> roles;
    roles[GroupNameRole] = "groupName";
    setRoleNames(roles);
}

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

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

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

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

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

Qt::ItemFlags GroupsModel::flags(const QModelIndex &index) const
{
    if (index.isValid()) {
        return Qt::ItemIsEnabled;
    }

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

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

    return false;
}

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

    return QModelIndex();
}

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

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

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

void GroupsModel::onItemChanged(TreeNode* node)
{
    emit dataChanged(index(node), index(node));
}

void GroupsModel::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();
}

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

void GroupsModel::onSourceItemsAdded(TreeNode *parent, const QList<TreeNode *> &nodes)
{
    kDebug() << "Adding" << nodes.size() << "nodes...";
    QModelIndex parentIndex = index(parent);
    int currentSize = rowCount(parentIndex);
    foreach (TreeNode *node, nodes) {
        ContactModelItem *contactItem = qobject_cast<ContactModelItem*>(node);
        QStringList groups = contactItem->contact()->groups();
        addContactToGroups(contactItem, groups);
    }
}

void GroupsModel::onSourceItemsRemoved(TreeNode* parent, int first, int last)
{

}

void GroupsModel::loadAccountsModel()
{
    for (int x = 0; x < mPriv->mAM->rowCount(); x++) {
        QModelIndex parent = mPriv->mAM->index(x, 0);
        for (int i = 0; i < mPriv->mAM->rowCount(parent); i++) {
            if (mPriv->mAM->data(mPriv->mAM->index(i, 0, parent),
                                 AccountsModel::ItemRole).userType() == qMetaTypeId<ContactModelItem*>()) {

                QStringList groups = mPriv->mAM->data(mPriv->mAM->index(i, 0, parent),
                                                      AccountsModel::GroupsRole).toStringList();

                ContactModelItem *contactItem = mPriv->mAM->data(mPriv->mAM->index(i, 0, parent),
                                                                 AccountsModel::ItemRole).value<ContactModelItem*>();

                addContactToGroups(contactItem, groups);
            }
        }

        //we need to connect accounts onItemsAdded/onItemsRemoved to watch for changes
        //and process them directly (directly add/remove the nodes)
        AccountsModelItem *accountItem = mPriv->mAM->data(parent, AccountsModel::ItemRole).value<AccountsModelItem*>();
        connect(accountItem, SIGNAL(childrenAdded(TreeNode*,QList<TreeNode*>)),
                this, SLOT(onSourceItemsAdded(TreeNode*,QList<TreeNode*>)));

        connect(accountItem, SIGNAL(childrenRemoved(TreeNode*,int,int)),
                this, SLOT(onSourceItemsRemoved(TreeNode*,int,int)));

        kDebug() << "Connecting" << accountItem->account()->displayName() << "to groups model";

    }
}

void GroupsModel::onContactAddedToGroup(const QString& group)
{
    addContactToGroups(qobject_cast<ProxyTreeNode*>(sender()), group);
}

void GroupsModel::onContactRemovedFromGroup(const QString& group)
{
    removeContactFromGroup(qobject_cast<ProxyTreeNode*>(sender()), group);
}

void GroupsModel::removeContactFromGroup(ProxyTreeNode* proxyNode, const QString& group)
{
    kDebug() << "Removing contact from" << group;

    QStringList contactGroups = proxyNode->data(AccountsModel::ItemRole).value<ContactModelItem*>()->contact()->groups();
    kDebug() << "Left groups are:" << contactGroups;

    contactGroups.removeOne(group);

    //if the contact really is in that group, remove it
    if (qobject_cast<GroupsModelItem*>(proxyNode->parent())->groupName() == group) {

        disconnect(proxyNode, SIGNAL(contactAddedToGroup(QString)), 0, 0);
        disconnect(proxyNode, SIGNAL(contactRemovedFromGroup(QString)), 0, 0);

        //if the the contact has no groups left, then put it in Ungrouped group
        if (contactGroups.isEmpty()) {
            addContactToGroups(proxyNode->data(AccountsModel::ItemRole).value<ContactModelItem*>(), contactGroups);
        }

//         beginRemoveRows(index(proxyNode->parent()), proxyNode->parent()->indexOf(proxyNode), proxyNode->parent()->indexOf(proxyNode));
        qobject_cast<GroupsModelItem*>(proxyNode->parent())->removeProxyContact(proxyNode);
//         endRemoveRows();
    }
}

void GroupsModel::addContactToGroups(ProxyTreeNode* proxyNode, const QString& group)
{
    addContactToGroups(proxyNode->data(AccountsModel::ItemRole).value<ContactModelItem*>(), group);
}

void GroupsModel::addContactToGroups(ContactModelItem* contactItem, const QString& group)
{
    addContactToGroups(contactItem, QStringList(group));
}

void GroupsModel::addContactToGroups(ContactModelItem* contactItem, QStringList groups)
{
    kDebug() << "Contact groups:" << groups;

    //check if the contact is in Ungrouped group, if it is, it needs to be removed from there
    bool checkUngrouped = false;
    //if the contact has no groups, create an 'Ungrouped' group for it
    if (groups.isEmpty()) {
        groups.append("Ungrouped"); //FIXME i18n
    } else {
        checkUngrouped = true;
    }

    groups.removeDuplicates();

    foreach (QString group, groups) {
        bool groupExists = false;
        GroupsModelItem *groupItem;

        kDebug() << "Adding" << contactItem->contact()->alias() << "to" << group;

        //check if the group already exists first
        for (int i = 0; i < mPriv->mTree->children().size(); i++) {
//         foreach (GroupsModelItem *savedGroupItem, mPriv->mTree->children()) {
            GroupsModelItem *savedGroupItem = qobject_cast<GroupsModelItem*>(mPriv->mTree->childAt(i));
            if (savedGroupItem->groupName() == group) {
                groupExists = true;
                kDebug() << "Existing group found for" << group;
                groupItem = savedGroupItem;

                if (!checkUngrouped) {
                    break;
                }
            }
            if (checkUngrouped) {
                if (savedGroupItem->groupName() == "Ungrouped") {
                    for (int i = 0; i < savedGroupItem->size(); i++) {
                        ProxyTreeNode *tmpNode = qobject_cast<ProxyTreeNode*>(savedGroupItem->childAt(i));
                        if (tmpNode->data(AccountsModel::ItemRole).value<ContactModelItem*>()->contact()->id() == contactItem->contact()->id()) {
                            removeContactFromGroup(tmpNode, QString("Ungrouped"));
                            if (groupExists) {
                                break;
                            }
                        }
                    }
                }
            }
        }

        if (!groupExists) {
            kDebug() << "Creating new group for" << group;
            groupItem = new GroupsModelItem(group);
            onItemsAdded(mPriv->mTree, QList<TreeNode *>() << groupItem);
        }

        ProxyTreeNode *proxyNode = new ProxyTreeNode(contactItem);
        groupItem->addProxyContact(proxyNode);

        connect(proxyNode, SIGNAL(contactAddedToGroup(QString)),
                this, SLOT(onContactAddedToGroup(QString)));

        connect(proxyNode, SIGNAL(contactRemovedFromGroup(QString)),
                this, SLOT(onContactRemovedFromGroup(QString)));

    }
}

<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(URISUPPORT_HEADER_GUARD_1357924680)
#define URISUPPORT_HEADER_GUARD_1357924680

// Base include file.  Must be first.
#include <PlatformSupport/PlatformSupportDefinitions.hpp>

#include <memory>

#include <util/XMLURL.hpp>

#include <XalanDOM/XalanDOMString.hpp>

#include <PlatformSupport/XSLException.hpp>

class XALAN_PLATFORMSUPPORT_EXPORT URISupport
{
public:

#if defined(XALAN_NO_NAMESPACES)
	typedef auto_ptr<XMLURL>		URLAutoPtrType;
#else
	typedef std::auto_ptr<XMLURL>	URLAutoPtrType;
#endif

	/**
	 * Determine the fully qualified URI for a string.
	 *
	 * @param urlString string to qualify
	 * @return auto pointer to fully qualified URI
	 */
	static URLAutoPtrType
	getURLFromString(const XalanDOMString&	urlString);

	/**
	 * Determine the fully qualified URI for a string.
	 *
	 * @param urlString string to qualify
	 * @param base base location for URI
	 * @return auto pointer to fully qualified URI
	 */
	static URLAutoPtrType
	getURLFromString(
			const XalanDOMString&	urlString,
			const XalanDOMString&	base);

	/**
	 * Normalizes the string passed in, replacing
	 * \ with /.
	 *
	 * @param urlString string to qualify
	 * @return a reference to the passed parameter
	 */
	static XalanDOMString&
	NormalizeURIText(XalanDOMString&	uriString);

	class InvalidURIException : public XSLException
	{
	public:

		/**
		 * Construct an InvalidURIException.
		 *
		 * @param theMessage the error message
		 */
		InvalidURIException(const XalanDOMString&	theMessage);

		virtual
		~InvalidURIException();
	};
};

#endif	// URISUPPORT_HEADER_GUARD_1357924680
<commit_msg>New functions.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(URISUPPORT_HEADER_GUARD_1357924680)
#define URISUPPORT_HEADER_GUARD_1357924680

// Base include file.  Must be first.
#include <PlatformSupport/PlatformSupportDefinitions.hpp>

#include <memory>

#include <util/XMLURL.hpp>

#include <XalanDOM/XalanDOMString.hpp>

#include <PlatformSupport/XSLException.hpp>

class XALAN_PLATFORMSUPPORT_EXPORT URISupport
{
public:

#if defined(XALAN_NO_NAMESPACES)
	typedef auto_ptr<XMLURL>		URLAutoPtrType;
#else
	typedef std::auto_ptr<XMLURL>	URLAutoPtrType;
#endif

	/**
	 * Determine the fully qualified URI for a string.
	 *
	 * @param urlString string to qualify
	 * @return auto pointer to fully qualified URI
	 */
	static URLAutoPtrType
	getURLFromString(const XalanDOMString&	urlString);

	/**
	 * Determine the fully qualified URI for a string.
	 *
	 * @param urlString string to qualify
	 * @return string to fully qualified URI
	 */
	static XalanDOMString
	getURLStringFromString(
			const XalanDOMString&	urlString);

	/**
	 * Determine the fully qualified URI for a string.
	 *
	 * @param urlString string to qualify
	 * @param base base location for URI
	 * @return auto pointer to fully qualified URI
	 */
	static URLAutoPtrType
	getURLFromString(
			const XalanDOMString&	urlString,
			const XalanDOMString&	base);

	/**
	 * Determine the fully qualified URI for a string.
	 *
	 * @param urlString string to qualify
	 * @param base base location for URI
	 * @return string to fully qualified URI
	 */
	static XalanDOMString
	getURLStringFromString(
			const XalanDOMString&	urlString,
			const XalanDOMString&	base);

	/**
	 * Normalizes the string passed in, replacing
	 * \ with /.
	 *
	 * @param urlString string to qualify
	 * @return a reference to the passed parameter
	 */
	static XalanDOMString&
	NormalizeURIText(XalanDOMString&	uriString);

	class InvalidURIException : public XSLException
	{
	public:

		/**
		 * Construct an InvalidURIException.
		 *
		 * @param theMessage the error message
		 */
		InvalidURIException(const XalanDOMString&	theMessage);

		virtual
		~InvalidURIException();
	};
};

#endif	// URISUPPORT_HEADER_GUARD_1357924680
<|endoftext|>


<commit_before>#include "audio_facade.h"
#include "audio_engine.h"
#include "audio_handle_impl.h"
#include "audio_emitter_behaviour.h"
#include "halley/support/console.h"
#include "halley/support/logger.h"
#include "halley/core/resources/resources.h"
#include "audio_event.h"

using namespace Halley;

AudioFacade::AudioFacade(AudioOutputAPI& o, SystemAPI& system)
	: output(o)
	, system(system)
	, running(false)
	, ownAudioThread(o.needsAudioThread())
{
}

AudioFacade::~AudioFacade()
{
	AudioFacade::stopPlayback();
}

void AudioFacade::setResources(Resources& res)
{
	resources = &res;
}

void AudioFacade::init()
{
	std::cout << ConsoleColour(Console::GREEN) << "\nInitializing audio...\n" << ConsoleColour();
	std::cout << "Audio devices available:" << std::endl;
	int i = 0;
	for (auto& device: getAudioDevices()) {
		std::cout << "\t" << i++ << ": " << device->getName() << std::endl;
	}
}

void AudioFacade::deInit()
{
	stopPlayback();
}

Vector<std::unique_ptr<const AudioDevice>> AudioFacade::getAudioDevices()
{
	return output.getAudioDevices();
}

void AudioFacade::startPlayback(int deviceNumber)
{
	if (started) {
		stopPlayback();
	}

	auto devices = getAudioDevices();
	if (int(devices.size()) > deviceNumber) {
		engine = std::make_unique<AudioEngine>();

		AudioSpec format;
		format.bufferSize = 1024;
		format.format = AudioSampleFormat::Float;
		format.numChannels = 2;
		format.sampleRate = 48000;

		audioSpec = output.openAudioDevice(format, devices.at(deviceNumber).get(), [this]() { onNeedBuffer(); });
		started = true;

		std::cout << "Audio Playback started.\n";
		std::cout << "\tDevice: " << devices.at(deviceNumber)->getName() << " [" << deviceNumber << "]\n";
		std::cout << "\tSample rate: " << audioSpec.sampleRate << "\n";
		std::cout << "\tChannels: " << audioSpec.numChannels << "\n";
		std::cout << "\tFormat: " << toString(audioSpec.format) << "\n";
		std::cout << "\tBuffer size: " << audioSpec.bufferSize << std::endl;

		resumePlayback();
	}
}

void AudioFacade::stopPlayback()
{
	if (started) {
		pausePlayback();
		musicTracks.clear();
		engine.reset();
		started = false;
	}
}

void AudioFacade::resumePlayback()
{
	if (started) {
		if (running) {
			pausePlayback();
		}

		engine->start(audioSpec, output);
		running = true;

		if (ownAudioThread) {
			audioThread = system.createThread("Audio", [this]() { run(); });
		}

		output.startPlayback();
	}
}

void AudioFacade::pausePlayback()
{
	if (running) {
		{
			std::unique_lock<std::mutex> lock(audioMutex);
			running = false;
			engine->pause();
		}
		if (ownAudioThread) {
			audioThread.join();
			audioThread = {};
		}
		output.stopPlayback();
	}
}

AudioHandle AudioFacade::postEvent(const String& name, AudioPosition position)
{
	auto event = resources->get<AudioEvent>(name);
	event->loadDependencies(*resources);

	size_t id = uniqueId++;
	enqueue([=] () {
		engine->postEvent(id, event, position);
	});
	return std::make_shared<AudioHandleImpl>(*this, id);
}

AudioHandle AudioFacade::playMusic(const String& eventName, int track)
{
	float fadeInTime = 0;
	bool hasFade = fadeInTime > 0.0001f;

	stopMusic(track, 0.5f);
	auto handle = postEvent(eventName, AudioPosition::makeFixed());
	musicTracks[track] = handle;

	if (hasFade) {
		handle->setGain(0.0f);
		handle->setBehaviour(std::make_unique<AudioEmitterFadeBehaviour>(fadeInTime, 1.0f, false));
	}

	return handle;
}

AudioHandle AudioFacade::play(std::shared_ptr<const IAudioClip> clip, AudioPosition position, float volume, bool loop)
{
	size_t id = uniqueId++;
	enqueue([=] () {
		engine->play(id, clip, position, volume, loop);
	});
	return std::make_shared<AudioHandleImpl>(*this, id);
}

AudioHandle AudioFacade::getMusic(int track)
{
	auto iter = musicTracks.find(track);
	if (iter != musicTracks.end()) {
		return iter->second;
	} else {
		return AudioHandle();
	}
}

void AudioFacade::stopMusic(int track, float fadeOutTime)
{
	auto iter = musicTracks.find(track);
	if (iter != musicTracks.end()) {
		stopMusic(iter->second, fadeOutTime);
		musicTracks.erase(iter);
	}
}

void AudioFacade::stopAllMusic(float fadeOutTime)
{
	for (auto& m: musicTracks) {
		stopMusic(m.second, fadeOutTime);
	}
	musicTracks.clear();
}

void AudioFacade::setMasterVolume(float volume)
{
	enqueue([=] () {
		engine->setMasterGain(volumeToGain(volume));
	});
}

void AudioFacade::setGroupVolume(const String& groupName, float volume)
{
	enqueue([=] () {
		engine->setGroupGain(groupName, volumeToGain(volume));
	});
}

void AudioFacade::stopMusic(AudioHandle& handle, float fadeOutTime)
{
	if (fadeOutTime > 0.001f) {
		handle->setBehaviour(std::make_unique<AudioEmitterFadeBehaviour>(fadeOutTime, 0.0f, true));
	} else {
		handle->stop();
	}
}

void AudioFacade::onNeedBuffer()
{
	if (!ownAudioThread) {
		stepAudio();
	}
}

void AudioFacade::setListener(AudioListenerData listener)
{
	enqueue([=] () {
		engine->setListener(listener);
	});
}

void AudioFacade::onAudioException(std::exception& e)
{
	std::unique_lock<std::mutex> lock(exceptionMutex);
	exceptions.emplace_back(e.what());
}

void AudioFacade::run()
{
	while (running) {
		stepAudio();
	}
}

void AudioFacade::stepAudio()
{
	try {
		{
			std::unique_lock<std::mutex> lock(audioMutex);
			if (!running) {
				return;
			}
			std::swap(inbox, inboxProcessing);
			inbox.clear();
			playingSoundsNext = engine->getPlayingSounds();
		}

		for (auto& action : inboxProcessing) {
			action();
		}

		if (ownAudioThread) {
			engine->run();
		} else {
			engine->generateBuffer();
		}
	} catch (std::exception& e) {
		onAudioException(e);
	}
}

void AudioFacade::enqueue(std::function<void()> action)
{
	if (running) {
		outbox.emplace_back(std::move(action));
	}
}

void AudioFacade::pump()
{
	{
		std::unique_lock<std::mutex> lock(exceptionMutex);
		if (!exceptions.empty()) {
			for (size_t i = 0; i + 1 < exceptions.size(); ++i) {
				Logger::logError(exceptions[i]);
			}
			const auto e = exceptions.back();
			exceptions.clear();
			stopPlayback();
			throw Exception(e);
		}
	}

	if (running) {
		std::unique_lock<std::mutex> lock(audioMutex);
		if (!outbox.empty()) {
			size_t i = inbox.size();
			inbox.resize(i + outbox.size());
			for (auto& o: outbox) {
				inbox[i++] = std::move(o);
			}
			outbox.clear();
		}

		playingSounds = playingSoundsNext;
	} else {
		inbox.clear();
		outbox.clear();
	}
}
<commit_msg>Ensure that audio device is closed before program termination.<commit_after>#include "audio_facade.h"
#include "audio_engine.h"
#include "audio_handle_impl.h"
#include "audio_emitter_behaviour.h"
#include "halley/support/console.h"
#include "halley/support/logger.h"
#include "halley/core/resources/resources.h"
#include "audio_event.h"

using namespace Halley;

AudioFacade::AudioFacade(AudioOutputAPI& o, SystemAPI& system)
	: output(o)
	, system(system)
	, running(false)
	, ownAudioThread(o.needsAudioThread())
{
}

AudioFacade::~AudioFacade()
{
	AudioFacade::stopPlayback();
}

void AudioFacade::setResources(Resources& res)
{
	resources = &res;
}

void AudioFacade::init()
{
	std::cout << ConsoleColour(Console::GREEN) << "\nInitializing audio...\n" << ConsoleColour();
	std::cout << "Audio devices available:" << std::endl;
	int i = 0;
	for (auto& device: getAudioDevices()) {
		std::cout << "\t" << i++ << ": " << device->getName() << std::endl;
	}
}

void AudioFacade::deInit()
{
	stopPlayback();
}

Vector<std::unique_ptr<const AudioDevice>> AudioFacade::getAudioDevices()
{
	return output.getAudioDevices();
}

void AudioFacade::startPlayback(int deviceNumber)
{
	if (started) {
		stopPlayback();
	}

	auto devices = getAudioDevices();
	if (int(devices.size()) > deviceNumber) {
		engine = std::make_unique<AudioEngine>();

		AudioSpec format;
		format.bufferSize = 1024;
		format.format = AudioSampleFormat::Float;
		format.numChannels = 2;
		format.sampleRate = 48000;

		audioSpec = output.openAudioDevice(format, devices.at(deviceNumber).get(), [this]() { onNeedBuffer(); });
		started = true;

		std::cout << "Audio Playback started.\n";
		std::cout << "\tDevice: " << devices.at(deviceNumber)->getName() << " [" << deviceNumber << "]\n";
		std::cout << "\tSample rate: " << audioSpec.sampleRate << "\n";
		std::cout << "\tChannels: " << audioSpec.numChannels << "\n";
		std::cout << "\tFormat: " << toString(audioSpec.format) << "\n";
		std::cout << "\tBuffer size: " << audioSpec.bufferSize << std::endl;

		resumePlayback();
	}
}

void AudioFacade::stopPlayback()
{
	if (started) {
		pausePlayback();
		musicTracks.clear();
		engine.reset();
		output.closeAudioDevice();
		started = false;
	}
}

void AudioFacade::resumePlayback()
{
	if (started) {
		if (running) {
			pausePlayback();
		}

		engine->start(audioSpec, output);
		running = true;

		if (ownAudioThread) {
			audioThread = system.createThread("Audio", [this]() { run(); });
		}

		output.startPlayback();
	}
}

void AudioFacade::pausePlayback()
{
	if (running) {
		{
			std::unique_lock<std::mutex> lock(audioMutex);
			running = false;
			engine->pause();
		}
		if (ownAudioThread) {
			audioThread.join();
			audioThread = {};
		}
		output.stopPlayback();
	}
}

AudioHandle AudioFacade::postEvent(const String& name, AudioPosition position)
{
	auto event = resources->get<AudioEvent>(name);
	event->loadDependencies(*resources);

	size_t id = uniqueId++;
	enqueue([=] () {
		engine->postEvent(id, event, position);
	});
	return std::make_shared<AudioHandleImpl>(*this, id);
}

AudioHandle AudioFacade::playMusic(const String& eventName, int track)
{
	float fadeInTime = 0;
	bool hasFade = fadeInTime > 0.0001f;

	stopMusic(track, 0.5f);
	auto handle = postEvent(eventName, AudioPosition::makeFixed());
	musicTracks[track] = handle;

	if (hasFade) {
		handle->setGain(0.0f);
		handle->setBehaviour(std::make_unique<AudioEmitterFadeBehaviour>(fadeInTime, 1.0f, false));
	}

	return handle;
}

AudioHandle AudioFacade::play(std::shared_ptr<const IAudioClip> clip, AudioPosition position, float volume, bool loop)
{
	size_t id = uniqueId++;
	enqueue([=] () {
		engine->play(id, clip, position, volume, loop);
	});
	return std::make_shared<AudioHandleImpl>(*this, id);
}

AudioHandle AudioFacade::getMusic(int track)
{
	auto iter = musicTracks.find(track);
	if (iter != musicTracks.end()) {
		return iter->second;
	} else {
		return AudioHandle();
	}
}

void AudioFacade::stopMusic(int track, float fadeOutTime)
{
	auto iter = musicTracks.find(track);
	if (iter != musicTracks.end()) {
		stopMusic(iter->second, fadeOutTime);
		musicTracks.erase(iter);
	}
}

void AudioFacade::stopAllMusic(float fadeOutTime)
{
	for (auto& m: musicTracks) {
		stopMusic(m.second, fadeOutTime);
	}
	musicTracks.clear();
}

void AudioFacade::setMasterVolume(float volume)
{
	enqueue([=] () {
		engine->setMasterGain(volumeToGain(volume));
	});
}

void AudioFacade::setGroupVolume(const String& groupName, float volume)
{
	enqueue([=] () {
		engine->setGroupGain(groupName, volumeToGain(volume));
	});
}

void AudioFacade::stopMusic(AudioHandle& handle, float fadeOutTime)
{
	if (fadeOutTime > 0.001f) {
		handle->setBehaviour(std::make_unique<AudioEmitterFadeBehaviour>(fadeOutTime, 0.0f, true));
	} else {
		handle->stop();
	}
}

void AudioFacade::onNeedBuffer()
{
	if (!ownAudioThread) {
		stepAudio();
	}
}

void AudioFacade::setListener(AudioListenerData listener)
{
	enqueue([=] () {
		engine->setListener(listener);
	});
}

void AudioFacade::onAudioException(std::exception& e)
{
	std::unique_lock<std::mutex> lock(exceptionMutex);
	exceptions.emplace_back(e.what());
}

void AudioFacade::run()
{
	while (running) {
		stepAudio();
	}
}

void AudioFacade::stepAudio()
{
	try {
		{
			std::unique_lock<std::mutex> lock(audioMutex);
			if (!running) {
				return;
			}
			std::swap(inbox, inboxProcessing);
			inbox.clear();
			playingSoundsNext = engine->getPlayingSounds();
		}

		for (auto& action : inboxProcessing) {
			action();
		}

		if (ownAudioThread) {
			engine->run();
		} else {
			engine->generateBuffer();
		}
	} catch (std::exception& e) {
		onAudioException(e);
	}
}

void AudioFacade::enqueue(std::function<void()> action)
{
	if (running) {
		outbox.emplace_back(std::move(action));
	}
}

void AudioFacade::pump()
{
	{
		std::unique_lock<std::mutex> lock(exceptionMutex);
		if (!exceptions.empty()) {
			for (size_t i = 0; i + 1 < exceptions.size(); ++i) {
				Logger::logError(exceptions[i]);
			}
			const auto e = exceptions.back();
			exceptions.clear();
			stopPlayback();
			throw Exception(e);
		}
	}

	if (running) {
		std::unique_lock<std::mutex> lock(audioMutex);
		if (!outbox.empty()) {
			size_t i = inbox.size();
			inbox.resize(i + outbox.size());
			for (auto& o: outbox) {
				inbox[i++] = std::move(o);
			}
			outbox.clear();
		}

		playingSounds = playingSoundsNext;
	} else {
		inbox.clear();
		outbox.clear();
	}
}
<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "iconbuttonpage.h"
#include <MLabel>
#include <MLayout>
#include <MLocale>
#include <MApplicationPage>
#include <MGridLayoutPolicy>
#include <MLinearLayoutPolicy>
#include <MButton>
#include <MButtonGroup>
#include <MDebug>
#include <MApplication>
#include <QGraphicsLinearLayout>

IconButtonPage::IconButtonPage() :
    TemplatePage(),
    iconButton1(0),
    iconButton2(0)
{
    gid = TemplatePage::Buttons;
}

IconButtonPage::~IconButtonPage()
{
}

QString IconButtonPage::timedemoTitle()
{
    return "IconButton";
}

void IconButtonPage::createContent()
{
    TemplatePage::createContent();

    QGraphicsWidget *w = new QGraphicsWidget();
    w->setMinimumSize(container->minimumWidth(), 5);
    w->setMaximumSize(container->minimumWidth(), 5);

    containerPolicy->setSpacing(40);
    containerPolicy->addItem(w);
    //containerPolicy->addStretch();

    // Icon buttons
    iconButton1 = new MButton();
    iconButton1->setViewType(MButton::iconType);
    iconButton1->setIconID("icon-l-common-video-playback");

    containerPolicy->addItem(iconButton1, Qt::AlignCenter);

    iconButton2 = new MButton();
    iconButton2->setViewType(MButton::iconType);
    iconButton2->setIconID("icon-l-games");
    iconButton2->setMaximumWidth(175);

    containerPolicy->addItem(iconButton2, Qt::AlignCenter);
    containerPolicy->addStretch();
    retranslateUi();
}

void IconButtonPage::retranslateUi()
{
    //% "Icon Button"
    setTitle(qtTrId("xx_icon_button_page_title"));
    if (!isContentCreated())
        return;

    //% "Icon Buttons have an icon and can have a text label. "
    //% "Icon button differs from push button by its visual presentation: "
    //% "it does not have button-style edges like a Push Button does.\n\n "
    //% "Icon Buttons are used in e.g. Toolbars."
    infoLabel->setText("" + qtTrId("xx_icon_button_page_info_label"));
    //% "Lorem ipsum"
    iconButton2->setText(qtTrId("xx_icon_button_page_icon_button2"));
}

<commit_msg>Changes: Fixed Widgetsgallery iconbuttonpage layout.<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "iconbuttonpage.h"
#include <MLabel>
#include <MLayout>
#include <MLocale>
#include <MApplicationPage>
#include <MGridLayoutPolicy>
#include <MLinearLayoutPolicy>
#include <MButton>
#include <MButtonGroup>
#include <MDebug>
#include <MApplication>
#include <QGraphicsLinearLayout>

IconButtonPage::IconButtonPage() :
    TemplatePage(),
    iconButton1(0),
    iconButton2(0)
{
    gid = TemplatePage::Buttons;
}

IconButtonPage::~IconButtonPage()
{
}

QString IconButtonPage::timedemoTitle()
{
    return "IconButton";
}

void IconButtonPage::createContent()
{
    TemplatePage::createContent();

    QGraphicsWidget *w = new QGraphicsWidget();
    w->setMinimumSize(container->minimumWidth(), 5);
    w->setMaximumSize(container->maximumWidth(), 5);

    containerPolicy->setSpacing(40);
    containerPolicy->addItem(w);
    //containerPolicy->addStretch();

    // Icon buttons
    iconButton1 = new MButton();
    iconButton1->setViewType(MButton::iconType);
    iconButton1->setIconID("icon-l-common-video-playback");

    containerPolicy->addItem(iconButton1, Qt::AlignCenter);

    iconButton2 = new MButton();
    iconButton2->setViewType(MButton::iconType);
    iconButton2->setIconID("icon-l-games");
    iconButton2->setMaximumWidth(175);

    containerPolicy->addItem(iconButton2, Qt::AlignCenter);
    containerPolicy->addStretch();
    retranslateUi();
}

void IconButtonPage::retranslateUi()
{
    //% "Icon Button"
    setTitle(qtTrId("xx_icon_button_page_title"));
    if (!isContentCreated())
        return;

    //% "Icon Buttons have an icon and can have a text label. "
    //% "Icon button differs from push button by its visual presentation: "
    //% "it does not have button-style edges like a Push Button does.\n\n "
    //% "Icon Buttons are used in e.g. Toolbars."
    infoLabel->setText("" + qtTrId("xx_icon_button_page_info_label"));
    //% "Lorem ipsum"
    iconButton2->setText(qtTrId("xx_icon_button_page_icon_button2"));
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: template.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-19 16:19:47 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "template.hxx"
#include "templateimpl.hxx"

#ifndef CONFIGMGR_SETNODEACCESS_HXX
#include "setnodeaccess.hxx"
#endif
#ifndef CONFIGMGR_API_APITYPES_HXX_
#include "apitypes.hxx"
#endif

namespace configmgr
{
    namespace configuration
    {
//-----------------------------------------------------------------------------
// class TemplateProvider
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
TemplateProvider::TemplateProvider()
: m_aImpl()
{
}

//-----------------------------------------------------------------------------
TemplateProvider::TemplateProvider(TemplateManagerRef const & xProvider, RequestOptions const& aOptions)
: m_aImpl( new TemplateProvider_Impl(xProvider,aOptions) )
{
}

//-----------------------------------------------------------------------------
TemplateProvider::TemplateProvider(TemplateProvider const& aOther)
: m_aImpl(aOther.m_aImpl)
{
}

//-----------------------------------------------------------------------------
TemplateProvider& TemplateProvider::operator =(TemplateProvider const& aOther)
{
    m_aImpl = aOther.m_aImpl;
    return *this;
}

//-----------------------------------------------------------------------------
TemplateProvider::~TemplateProvider()
{
}

//-----------------------------------------------------------------------------
// class SpecialTemplateProvider
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
SpecialTemplateProvider::SpecialTemplateProvider()
: m_aImpl( new SpecialTemplateProvider_Impl() )
{
}

//-----------------------------------------------------------------------------
SpecialTemplateProvider::SpecialTemplateProvider(SpecialTemplateProvider const& aOther)
: m_aImpl(aOther.m_aImpl)
{
}

//-----------------------------------------------------------------------------
SpecialTemplateProvider& SpecialTemplateProvider::operator =(SpecialTemplateProvider const& aOther)
{
    m_aImpl = aOther.m_aImpl;
    return *this;
}

//-----------------------------------------------------------------------------
SpecialTemplateProvider::~SpecialTemplateProvider()
{
}

//-----------------------------------------------------------------------------
// class Template
//-----------------------------------------------------------------------------

Template::Template(Name const& aName, Name const& aModule,UnoType const& aType)
: m_aName(aName)
, m_aModule(aModule)
, m_aInstanceType(aType)
{
}
//-----------------------------------------------------------------------------

bool Template::isInstanceTypeKnown() const
{
    OSL_ASSERT( TemplateImplHelper::getNoTypeAvailable().getTypeClass() == uno::TypeClass_VOID );
    return m_aInstanceType.getTypeClass() != uno::TypeClass_VOID;
}
//-----------------------------------------------------------------------------

/// checks if this is a 'value' template
bool Template::isInstanceValue() const
{
    OSL_ENSURE( isInstanceTypeKnown(), "Template instance type unknown - cannot determine kind");
    return m_aInstanceType.getTypeClass() != uno::TypeClass_INTERFACE;
}
//-----------------------------------------------------------------------------

UnoType Template::getInstanceType() const
{
    OSL_ENSURE( isInstanceTypeKnown(), "Template instance type unknown - returning invalid (VOID) type");
    return m_aInstanceType;
}
//-----------------------------------------------------------------------------

/// get the path where the template is located
OUString Template::getPathString() const
{
    TemplateName aNames(m_aName,m_aModule);
    return aNames.makePathString( );
}
//-----------------------------------------------------------------------------

TemplateHolder makeSimpleTemplate(UnoType const& aType, SpecialTemplateProvider const& aProvider)
{
    TemplateName aNames(aType,false);
    return TemplateImplHelper::makeSpecialTemplate( aNames, aProvider, aType);
}
//-----------------------------------------------------------------------------

TemplateHolder makeTreeTemplate(OUString const& sName, OUString const& sModule, SpecialTemplateProvider const& aProvider)
{
    TemplateName aNames( sName,sModule );
    return TemplateImplHelper::makeSpecialTemplate( aNames,aProvider, configapi::getUnoInterfaceType());
}
//-----------------------------------------------------------------------------

TemplateHolder makeSetElementTemplate(data::SetNodeAccess const& _aSet, TemplateProvider const& _aProvider)
{
    TemplateName aNames( _aSet.getElementTemplateName(), _aSet.getElementTemplateModule() );
    return TemplateImplHelper::makeElementTemplateWithType(aNames, _aProvider, _aSet);
}
//-----------------------------------------------------------------------------
    }
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.14.194); FILE MERGED 2005/09/05 17:05:32 rt 1.14.194.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: template.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 04:34:13 $
 *
 *  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
 *
 ************************************************************************/

#include "template.hxx"
#include "templateimpl.hxx"

#ifndef CONFIGMGR_SETNODEACCESS_HXX
#include "setnodeaccess.hxx"
#endif
#ifndef CONFIGMGR_API_APITYPES_HXX_
#include "apitypes.hxx"
#endif

namespace configmgr
{
    namespace configuration
    {
//-----------------------------------------------------------------------------
// class TemplateProvider
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
TemplateProvider::TemplateProvider()
: m_aImpl()
{
}

//-----------------------------------------------------------------------------
TemplateProvider::TemplateProvider(TemplateManagerRef const & xProvider, RequestOptions const& aOptions)
: m_aImpl( new TemplateProvider_Impl(xProvider,aOptions) )
{
}

//-----------------------------------------------------------------------------
TemplateProvider::TemplateProvider(TemplateProvider const& aOther)
: m_aImpl(aOther.m_aImpl)
{
}

//-----------------------------------------------------------------------------
TemplateProvider& TemplateProvider::operator =(TemplateProvider const& aOther)
{
    m_aImpl = aOther.m_aImpl;
    return *this;
}

//-----------------------------------------------------------------------------
TemplateProvider::~TemplateProvider()
{
}

//-----------------------------------------------------------------------------
// class SpecialTemplateProvider
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
SpecialTemplateProvider::SpecialTemplateProvider()
: m_aImpl( new SpecialTemplateProvider_Impl() )
{
}

//-----------------------------------------------------------------------------
SpecialTemplateProvider::SpecialTemplateProvider(SpecialTemplateProvider const& aOther)
: m_aImpl(aOther.m_aImpl)
{
}

//-----------------------------------------------------------------------------
SpecialTemplateProvider& SpecialTemplateProvider::operator =(SpecialTemplateProvider const& aOther)
{
    m_aImpl = aOther.m_aImpl;
    return *this;
}

//-----------------------------------------------------------------------------
SpecialTemplateProvider::~SpecialTemplateProvider()
{
}

//-----------------------------------------------------------------------------
// class Template
//-----------------------------------------------------------------------------

Template::Template(Name const& aName, Name const& aModule,UnoType const& aType)
: m_aName(aName)
, m_aModule(aModule)
, m_aInstanceType(aType)
{
}
//-----------------------------------------------------------------------------

bool Template::isInstanceTypeKnown() const
{
    OSL_ASSERT( TemplateImplHelper::getNoTypeAvailable().getTypeClass() == uno::TypeClass_VOID );
    return m_aInstanceType.getTypeClass() != uno::TypeClass_VOID;
}
//-----------------------------------------------------------------------------

/// checks if this is a 'value' template
bool Template::isInstanceValue() const
{
    OSL_ENSURE( isInstanceTypeKnown(), "Template instance type unknown - cannot determine kind");
    return m_aInstanceType.getTypeClass() != uno::TypeClass_INTERFACE;
}
//-----------------------------------------------------------------------------

UnoType Template::getInstanceType() const
{
    OSL_ENSURE( isInstanceTypeKnown(), "Template instance type unknown - returning invalid (VOID) type");
    return m_aInstanceType;
}
//-----------------------------------------------------------------------------

/// get the path where the template is located
OUString Template::getPathString() const
{
    TemplateName aNames(m_aName,m_aModule);
    return aNames.makePathString( );
}
//-----------------------------------------------------------------------------

TemplateHolder makeSimpleTemplate(UnoType const& aType, SpecialTemplateProvider const& aProvider)
{
    TemplateName aNames(aType,false);
    return TemplateImplHelper::makeSpecialTemplate( aNames, aProvider, aType);
}
//-----------------------------------------------------------------------------

TemplateHolder makeTreeTemplate(OUString const& sName, OUString const& sModule, SpecialTemplateProvider const& aProvider)
{
    TemplateName aNames( sName,sModule );
    return TemplateImplHelper::makeSpecialTemplate( aNames,aProvider, configapi::getUnoInterfaceType());
}
//-----------------------------------------------------------------------------

TemplateHolder makeSetElementTemplate(data::SetNodeAccess const& _aSet, TemplateProvider const& _aProvider)
{
    TemplateName aNames( _aSet.getElementTemplateName(), _aSet.getElementTemplateModule() );
    return TemplateImplHelper::makeElementTemplateWithType(aNames, _aProvider, _aSet);
}
//-----------------------------------------------------------------------------
    }
}

<|endoftext|>


<commit_before>#include "Halide.h"

using namespace Halide;

Expr u16(Expr x) { return cast<uint16_t>(x); }
Expr u8(Expr x) { return cast<uint8_t>(x); }

// Define a 1D Gaussian blur (a [1 4 6 4 1] filter) of 5 elements.
Expr blur5(Expr x0, Expr x1, Expr x2, Expr x3, Expr x4) {
    return u8((u16(x0) + 4*u16(x1) + 6*u16(x2) + 4*u16(x3) + u16(x4) + 8)/16);
}

int main(int argc, char **argv) {
    Target target = get_target_from_environment();

    std::cout << "Target: " << target.to_string() << "\n";

    Var x("x"), y("y"), c("c");

    // Takes an 8-bit input image.
    ImageParam input(UInt(8), 3);

    // Apply a boundary condition to the input.
    Func input_bounded = BoundaryConditions::repeat_edge(input);

    // Implement this as a separable blur in y followed by x.
    Func blur_y("blur_y");
    blur_y(x, y, c) = blur5(input_bounded(x, y - 2, c),
                            input_bounded(x, y - 1, c),
                            input_bounded(x, y,     c),
                            input_bounded(x, y + 1, c),
                            input_bounded(x, y + 2, c));

    Func blur("blur");
    blur(x, y, c) = blur5(blur_y(x - 2, y, c),
                          blur_y(x - 1, y, c),
                          blur_y(x,     y, c),
                          blur_y(x + 1, y, c),
                          blur_y(x + 2, y, c));

    // Schedule.

    // Require the input and output to have 3 channels.
    blur.bound(c, 0, 3);
    input.set_min(2, 0).set_extent(2, 3);

    if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
        const int vector_size = target.has_feature(Target::HVX_128) ? 128 : 64;

        // The strategy here is to split each scanline of the result
        // into chunks of multiples of the vector size, computing the
        // blur in y at each chunk. We use the RoundUp tail strategy to
        // keep the last chunk's memory accesses aligned.
        Var xo("xo"), xi("xi");
        blur.compute_root()
            .hexagon()
            .split(x, xo, xi, vector_size*2, TailStrategy::RoundUp)
            .vectorize(xi, vector_size)
            .parallel(y, 16);
        blur_y.compute_at(blur, xo)
            .vectorize(x, vector_size, TailStrategy::RoundUp);

        // Require scanlines of the input and output to be aligned.
        auto blur_buffer = blur.output_buffer();

        input.set_host_alignment(vector_size);
        blur_buffer.set_host_alignment(vector_size);

        input.set_min(0, 0).set_extent(0, (input.extent(0)/vector_size)*vector_size);
        blur_buffer.set_min(0, 0).set_extent(0, (blur_buffer.extent(0)/vector_size)*vector_size);

        for (int i = 1; i < 3; i++) {
            input.set_stride(i, (input.stride(i)/vector_size)*vector_size);
            blur_buffer.set_stride(i, (blur_buffer.stride(i)/vector_size)*vector_size);
        }
    } else {
        const int vector_size = target.natural_vector_size<uint8_t>();

        blur.compute_root()
            .parallel(y, 16)
            .vectorize(x, vector_size);
        blur_y.compute_at(blur, y)
            .vectorize(x, vector_size);
    }

    std::stringstream hdr;
    hdr << argv[2] << ".h";
    blur.compile_to_header(hdr.str(), {input}, argv[2], target);
    std::stringstream obj;
    obj << argv[1] << ".o";
    blur.compile_to_object(obj.str(), {input}, argv[2], target);

    return 0;
}
<commit_msg>Don't use short casts.<commit_after>#include "Halide.h"

using namespace Halide;

// Define a 1D Gaussian blur (a [1 4 6 4 1] filter) of 5 elements.
Expr blur5(Expr x0, Expr x1, Expr x2, Expr x3, Expr x4) {
    // Widen to 16 bits, so we don't overflow while computing the stencil.
    x0 = cast<uint16_t>(x0);
    x1 = cast<uint16_t>(x1);
    x2 = cast<uint16_t>(x2);
    x3 = cast<uint16_t>(x3);
    x4 = cast<uint16_t>(x4);
    return cast<uint8_t>((x0 + 4*x1 + 6*x2 + 4*x3 + x4 + 8)/16);
}

int main(int argc, char **argv) {
    Target target = get_target_from_environment();

    std::cout << "Target: " << target.to_string() << "\n";

    Var x("x"), y("y"), c("c");

    // Takes an 8-bit input image.
    ImageParam input(UInt(8), 3);

    // Apply a boundary condition to the input.
    Func input_bounded = BoundaryConditions::repeat_edge(input);

    // Implement this as a separable blur in y followed by x.
    Func blur_y("blur_y");
    blur_y(x, y, c) = blur5(input_bounded(x, y - 2, c),
                            input_bounded(x, y - 1, c),
                            input_bounded(x, y,     c),
                            input_bounded(x, y + 1, c),
                            input_bounded(x, y + 2, c));

    Func blur("blur");
    blur(x, y, c) = blur5(blur_y(x - 2, y, c),
                          blur_y(x - 1, y, c),
                          blur_y(x,     y, c),
                          blur_y(x + 1, y, c),
                          blur_y(x + 2, y, c));

    // Schedule.

    // Require the input and output to have 3 channels.
    blur.bound(c, 0, 3);
    input.set_min(2, 0).set_extent(2, 3);

    if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
        const int vector_size = target.has_feature(Target::HVX_128) ? 128 : 64;

        // The strategy here is to split each scanline of the result
        // into chunks of multiples of the vector size, computing the
        // blur in y at each chunk. We use the RoundUp tail strategy to
        // keep the last chunk's memory accesses aligned.
        Var xo("xo"), xi("xi");
        blur.compute_root()
            .hexagon()
            .split(x, xo, xi, vector_size*2, TailStrategy::RoundUp)
            .vectorize(xi, vector_size)
            .parallel(y, 16);
        blur_y.compute_at(blur, xo)
            .vectorize(x, vector_size, TailStrategy::RoundUp);

        // Require scanlines of the input and output to be aligned.
        auto blur_buffer = blur.output_buffer();

        input.set_host_alignment(vector_size);
        blur_buffer.set_host_alignment(vector_size);

        input.set_min(0, 0).set_extent(0, (input.extent(0)/vector_size)*vector_size);
        blur_buffer.set_min(0, 0).set_extent(0, (blur_buffer.extent(0)/vector_size)*vector_size);

        for (int i = 1; i < 3; i++) {
            input.set_stride(i, (input.stride(i)/vector_size)*vector_size);
            blur_buffer.set_stride(i, (blur_buffer.stride(i)/vector_size)*vector_size);
        }
    } else {
        const int vector_size = target.natural_vector_size<uint8_t>();

        blur.compute_root()
            .parallel(y, 16)
            .vectorize(x, vector_size);
        blur_y.compute_at(blur, y)
            .vectorize(x, vector_size);
    }

    std::stringstream hdr;
    hdr << argv[2] << ".h";
    blur.compile_to_header(hdr.str(), {input}, argv[2], target);
    std::stringstream obj;
    obj << argv[1] << ".o";
    blur.compile_to_object(obj.str(), {input}, argv[2], target);

    return 0;
}
<|endoftext|>


<commit_before>/*=========================================================================

Library:   TubeTK

Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.

All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=========================================================================*/

#include "tubeConvertTubesToDensityImage.h"
#include "tubeCLIProgressReporter.h"
#include "tubeMessage.h"
#include <itkImageFileReader.h>
#include <itkSpatialObjectReader.h>
#include <itkTimeProbesCollectorBase.h>

#include "ConvertTubesToDensityImageCLP.h"

int DoIt( int argc, char * argv[] );

/** Main work happens here */
template< unsigned int Dimension >
int DoIt( int argc, char * argv[] )
{
  PARSE_ARGS;

  /*Typedefs..*/
  typedef float                                         TPixel;
  typedef itk::Vector< TPixel, Dimension >              TangentPixelType;
  typedef itk::Image< TPixel, Dimension >               DensityImageType;
  typedef itk::Image< TPixel, Dimension >               RadiusImageType;
  typedef itk::Image< TangentPixelType, Dimension >     TangentImageType;
  typedef itk::Image< unsigned char, Dimension >        TemplateImageType;
  typedef itk::ImageFileReader< TemplateImageType >     TemplateImageReaderType;

  /** Max Intensity value */
  TPixel   max_densityIntensity = 2048;

  typedef tube::ConvertTubesToDensityImage<
  TPixel, Dimension > TubeToDensityImageBuilderType;

  typedef typename TubeToDensityImageBuilderType::TubeGroupType  TubesType;
  typedef itk::SpatialObjectReader< Dimension >         TubesReaderType;

  double progress = 0.0;
  itk::TimeProbesCollectorBase timeCollector;

  tube::CLIProgressReporter progressReporter(
    "tubeDensityImageRadiusBuilder",
    CLPProcessInformation );

  progressReporter.Start();
  progressReporter.Report( progress );

  typename TubeToDensityImageBuilderType::Pointer
    builder = TubeToDensityImageBuilderType::New();

  builder->SetMaxDensityIntensity( max_densityIntensity ); // Const

  if( !inputTemplateImage.empty() )
    {
    std::cout << "Trying to use template image as constraints!" << std::endl;

    timeCollector.Start( "Loading template image" );

    typename TemplateImageReaderType::Pointer imTemplateReader;
    imTemplateReader = TemplateImageReaderType::New();
    imTemplateReader->SetFileName( inputTemplateImage.c_str() );
    imTemplateReader->Update();

    typename TemplateImageType::Pointer imT = imTemplateReader->GetOutput();
    typename TubeToDensityImageBuilderType::SizeType size;
    double spacing[Dimension];
    for( unsigned int i = 0; i < Dimension; i++ )
      {
      size[i] = imT->GetLargestPossibleRegion().GetSize()[i];
      spacing[i] = imT->GetSpacing()[i];
      }
    builder->SetSize( size );
    builder->SetSpacing( spacing );

    timeCollector.Stop( "Loading template image" );
    }
  else
    {
    std::cout << "Trying to use user-specified constraints!" << std::endl;

    if( !outputSize.size() )
      {
      std::cerr << "Output size is missing!" << std::endl;
      return -1;
      }
    typename TubeToDensityImageBuilderType::SizeType sizeValue;
    for( unsigned int i = 0; i < Dimension; i++ )
      {
      sizeValue[i] = outputSize[i];
      }
    builder->SetSize( sizeValue );

    if( !outputSpacing.size() )
      {
      std::cerr << "Output spacing is missing!" << std::endl;
      return -1;
      }
    double sp[Dimension];
    for( unsigned int i = 0; i < Dimension; i++ )
      {
      sp[i] = outputSpacing[i];
      }
    builder->SetSpacing( sp );
    }

  builder->SetUseSquareDistance( useSquareDistance );
  typename TubesReaderType::Pointer reader = TubesReaderType::New();
  try
    {
    reader->SetFileName( inputTubeFile.c_str() );
    std::cout << "Reading Tube group... ";
    reader->Update();
    std::cout << "Done." << std::endl;
    }
  catch( ... )
    {
    std::cerr << "Error:: No readable Tubes found " << std::endl;
    return EXIT_FAILURE;
    }
  builder->SetInputTubeGroup( reader->GetGroup() );

  progress = 0.1; // At about 10% done
  progressReporter.Report( progress );

  timeCollector.Start( "Update filter" );
  builder->Update();
  timeCollector.Stop( "Update filter" );

  progress = 0.8; // At about 80% done after filter
  progressReporter.Report( progress );

  timeCollector.Start( "Save data" );
  std::cout << "Writing image: " << outputDensityImage.c_str() << std::endl;
  typedef itk::ImageFileWriter< DensityImageType > WriterType_d;
  typename WriterType_d::Pointer  writer_d = WriterType_d::New();

  writer_d->SetFileName( outputDensityImage.c_str() );
  writer_d->SetInput( builder->GetDensityMapImage() );
  writer_d->SetUseCompression(true);
  writer_d->Update();

  std::cout << "Writing image: " << outputRadiusImage.c_str() << std::endl;
  typedef itk::ImageFileWriter< RadiusImageType > WriterType_r;
  typename WriterType_r::Pointer  writer_r = WriterType_r::New();

  writer_r->SetFileName( outputRadiusImage.c_str() );
  writer_r->SetInput( builder->GetRadiusMapImage() );
  writer_r->SetUseCompression( true );
  writer_r->Update();

  std::cout << "Writing image: " << outputTangentImage.c_str() << std::endl;
  typedef itk::ImageFileWriter< TangentImageType > WriterType_t;
  typename WriterType_t::Pointer  writer_t = WriterType_t::New();

  writer_t->SetFileName( outputTangentImage.c_str() );
  writer_t->SetInput( builder->GetTangentMapImage() );
  writer_t->SetUseCompression( true );
  writer_t->Update();

  timeCollector.Stop( "Save data" );

  progress = 1.0;
  progressReporter.Report( progress );
  progressReporter.End();

  timeCollector.Report();
  return EXIT_SUCCESS;
}

// Main
int main( int argc, char * argv[] )
{
  try
    {
    PARSE_ARGS;
    }
  catch( const std::exception & err )
    {
    tube::ErrorMessage( err.what() );
    return EXIT_FAILURE;
    }
  PARSE_ARGS;

  MetaScene *mScene = new MetaScene;
  mScene->Read( inputTubeFile.c_str() );

  if( mScene->GetObjectList()->empty() )
    {
    tubeWarningMacro( << "Input Tube file has no spatial objects" );
    delete mScene;
    return EXIT_SUCCESS;
    }

  switch( mScene->GetObjectList()->front()->NDims() )
    {
    case 2:
      {
      bool result = DoIt<2>( argc, argv );
      delete mScene;
      return result;
      break;
      }
    case 3:
      {
      bool result = DoIt<3>( argc, argv );
      delete mScene;
      return result;
      break;
      }
    default:
      {
      tubeErrorMacro(
        << "Error: Only 2D and 3D data is currently supported." );
      delete mScene;
      return EXIT_FAILURE;
      break;
      }
    }
  return EXIT_FAILURE;
}
<commit_msg>COMP: Remove compiler warning.<commit_after>/*=========================================================================

Library:   TubeTK

Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.

All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=========================================================================*/

#include "tubeConvertTubesToDensityImage.h"
#include "tubeCLIProgressReporter.h"
#include "tubeMessage.h"
#include <itkImageFileReader.h>
#include <itkSpatialObjectReader.h>
#include <itkTimeProbesCollectorBase.h>

#include "ConvertTubesToDensityImageCLP.h"

int DoIt( int argc, char * argv[] );

/** Main work happens here */
template< unsigned int Dimension >
int DoIt( int argc, char * argv[] )
{
  PARSE_ARGS;

  /*Typedefs..*/
  typedef float                                         TPixel;
  typedef itk::Vector< TPixel, Dimension >              TangentPixelType;
  typedef itk::Image< TPixel, Dimension >               DensityImageType;
  typedef itk::Image< TPixel, Dimension >               RadiusImageType;
  typedef itk::Image< TangentPixelType, Dimension >     TangentImageType;
  typedef itk::Image< unsigned char, Dimension >        TemplateImageType;
  typedef itk::ImageFileReader< TemplateImageType >     TemplateImageReaderType;

  /** Max Intensity value */
  TPixel   max_densityIntensity = 2048;

  typedef tube::ConvertTubesToDensityImage<
  TPixel, Dimension > TubeToDensityImageBuilderType;

  typedef itk::SpatialObjectReader< Dimension >         TubesReaderType;

  double progress = 0.0;
  itk::TimeProbesCollectorBase timeCollector;

  tube::CLIProgressReporter progressReporter(
    "tubeDensityImageRadiusBuilder",
    CLPProcessInformation );

  progressReporter.Start();
  progressReporter.Report( progress );

  typename TubeToDensityImageBuilderType::Pointer
    builder = TubeToDensityImageBuilderType::New();

  builder->SetMaxDensityIntensity( max_densityIntensity ); // Const

  if( !inputTemplateImage.empty() )
    {
    std::cout << "Trying to use template image as constraints!" << std::endl;

    timeCollector.Start( "Loading template image" );

    typename TemplateImageReaderType::Pointer imTemplateReader;
    imTemplateReader = TemplateImageReaderType::New();
    imTemplateReader->SetFileName( inputTemplateImage.c_str() );
    imTemplateReader->Update();

    typename TemplateImageType::Pointer imT = imTemplateReader->GetOutput();
    typename TubeToDensityImageBuilderType::SizeType size;
    double spacing[Dimension];
    for( unsigned int i = 0; i < Dimension; i++ )
      {
      size[i] = imT->GetLargestPossibleRegion().GetSize()[i];
      spacing[i] = imT->GetSpacing()[i];
      }
    builder->SetSize( size );
    builder->SetSpacing( spacing );

    timeCollector.Stop( "Loading template image" );
    }
  else
    {
    std::cout << "Trying to use user-specified constraints!" << std::endl;

    if( !outputSize.size() )
      {
      std::cerr << "Output size is missing!" << std::endl;
      return -1;
      }
    typename TubeToDensityImageBuilderType::SizeType sizeValue;
    for( unsigned int i = 0; i < Dimension; i++ )
      {
      sizeValue[i] = outputSize[i];
      }
    builder->SetSize( sizeValue );

    if( !outputSpacing.size() )
      {
      std::cerr << "Output spacing is missing!" << std::endl;
      return -1;
      }
    double sp[Dimension];
    for( unsigned int i = 0; i < Dimension; i++ )
      {
      sp[i] = outputSpacing[i];
      }
    builder->SetSpacing( sp );
    }

  builder->SetUseSquareDistance( useSquareDistance );
  typename TubesReaderType::Pointer reader = TubesReaderType::New();
  try
    {
    reader->SetFileName( inputTubeFile.c_str() );
    std::cout << "Reading Tube group... ";
    reader->Update();
    std::cout << "Done." << std::endl;
    }
  catch( ... )
    {
    std::cerr << "Error:: No readable Tubes found " << std::endl;
    return EXIT_FAILURE;
    }
  builder->SetInputTubeGroup( reader->GetGroup() );

  progress = 0.1; // At about 10% done
  progressReporter.Report( progress );

  timeCollector.Start( "Update filter" );
  builder->Update();
  timeCollector.Stop( "Update filter" );

  progress = 0.8; // At about 80% done after filter
  progressReporter.Report( progress );

  timeCollector.Start( "Save data" );
  std::cout << "Writing image: " << outputDensityImage.c_str() << std::endl;
  typedef itk::ImageFileWriter< DensityImageType > WriterType_d;
  typename WriterType_d::Pointer  writer_d = WriterType_d::New();

  writer_d->SetFileName( outputDensityImage.c_str() );
  writer_d->SetInput( builder->GetDensityMapImage() );
  writer_d->SetUseCompression(true);
  writer_d->Update();

  std::cout << "Writing image: " << outputRadiusImage.c_str() << std::endl;
  typedef itk::ImageFileWriter< RadiusImageType > WriterType_r;
  typename WriterType_r::Pointer  writer_r = WriterType_r::New();

  writer_r->SetFileName( outputRadiusImage.c_str() );
  writer_r->SetInput( builder->GetRadiusMapImage() );
  writer_r->SetUseCompression( true );
  writer_r->Update();

  std::cout << "Writing image: " << outputTangentImage.c_str() << std::endl;
  typedef itk::ImageFileWriter< TangentImageType > WriterType_t;
  typename WriterType_t::Pointer  writer_t = WriterType_t::New();

  writer_t->SetFileName( outputTangentImage.c_str() );
  writer_t->SetInput( builder->GetTangentMapImage() );
  writer_t->SetUseCompression( true );
  writer_t->Update();

  timeCollector.Stop( "Save data" );

  progress = 1.0;
  progressReporter.Report( progress );
  progressReporter.End();

  timeCollector.Report();
  return EXIT_SUCCESS;
}

// Main
int main( int argc, char * argv[] )
{
  try
    {
    PARSE_ARGS;
    }
  catch( const std::exception & err )
    {
    tube::ErrorMessage( err.what() );
    return EXIT_FAILURE;
    }
  PARSE_ARGS;

  MetaScene *mScene = new MetaScene;
  mScene->Read( inputTubeFile.c_str() );

  if( mScene->GetObjectList()->empty() )
    {
    tubeWarningMacro( << "Input Tube file has no spatial objects" );
    delete mScene;
    return EXIT_SUCCESS;
    }

  switch( mScene->GetObjectList()->front()->NDims() )
    {
    case 2:
      {
      bool result = DoIt<2>( argc, argv );
      delete mScene;
      return result;
      break;
      }
    case 3:
      {
      bool result = DoIt<3>( argc, argv );
      delete mScene;
      return result;
      break;
      }
    default:
      {
      tubeErrorMacro(
        << "Error: Only 2D and 3D data is currently supported." );
      delete mScene;
      return EXIT_FAILURE;
      break;
      }
    }
  return EXIT_FAILURE;
}
<|endoftext|>