<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qfxloader_p.h"
#include <private/qmlengine_p.h>

QT_BEGIN_NAMESPACE

QFxLoaderPrivate::QFxLoaderPrivate()
: item(0), component(0), ownComponent(false), resizeMode(QFxLoader::SizeLoaderToItem)
{
}

QFxLoaderPrivate::~QFxLoaderPrivate()
{
}

QML_DEFINE_TYPE(Qt,4,6,(QT_VERSION&0x00ff00)>>8,Loader,QFxLoader)

/*!
    \qmlclass Loader
    \inherits Item

    \brief The Loader item allows dynamically loading an Item-based
    subtree from a QML URL or Component.

    Loader instantiates an item from a component. The component to
    instantiate may be specified directly by the \c sourceComponent
    property, or loaded from a URL via the \c source property.

    It is also an effective means of delaying the creation of a component
    until it is required:
    \code
    Loader { id: PageLoader }
    Rectangle {
        MouseRegion { anchors.fill: parent; onClicked: PageLoader.source = "Page1.qml" }
    }
    \endcode
*/

/*!
    \internal
    \class QFxLoader
    \qmlclass Loader
 */

/*!
    Create a new QFxLoader instance.
 */
QFxLoader::QFxLoader(QFxItem *parent)
  : QFxItem(*(new QFxLoaderPrivate), parent)
{
}

/*!
    Destroy the loader instance.
 */
QFxLoader::~QFxLoader()
{
}

/*!
    \qmlproperty url Loader::source
    This property holds the URL of the QML component to
    instantiate.

    \sa status, progress
*/
QUrl QFxLoader::source() const
{
    Q_D(const QFxLoader);
    return d->source;
}

void QFxLoader::setSource(const QUrl &url)
{
    Q_D(QFxLoader);
    if (d->source == url)
        return;

    if (d->ownComponent) {
        delete d->component;
        d->component = 0;
    }
    d->item = 0;
    delete d->item;

    d->source = url;
    if (d->source.isEmpty()) {
        emit sourceChanged();
        emit statusChanged();
        emit progressChanged();
        emit itemChanged();
        return;
    }

    d->component = new QmlComponent(qmlEngine(this), d->source, this);
    d->ownComponent = true;
    if (!d->component->isLoading()) {
        d->_q_sourceLoaded();
    } else {
        connect(d->component, SIGNAL(statusChanged(QmlComponent::Status)),
                this, SLOT(_q_sourceLoaded()));
        connect(d->component, SIGNAL(progressChanged(qreal)),
                this, SIGNAL(progressChanged()));
        emit statusChanged();
        emit progressChanged();
        emit sourceChanged();
        emit itemChanged();
    }
}

/*!
    \qmlproperty Component Loader::sourceComponent
    The sourceComponent property holds the \l{Component} to instantiate.

    \qml
    Item {
        Component {
            id: RedSquare
            Rectangle { color: "red"; width: 10; height: 10 }
        }

        Loader { sourceComponent: RedSquare }
        Loader { sourceComponent: RedSquare; x: 10 }
    }
    \endqml

    \sa source
*/

QmlComponent *QFxLoader::sourceComponent() const
{
    Q_D(const QFxLoader);
    return d->component;
}

void QFxLoader::setSourceComponent(QmlComponent *comp)
{
    Q_D(QFxLoader);
    if (comp == d->component)
        return;

    d->source = QUrl();
    if (d->ownComponent) {
        delete d->component;
        d->component = 0;
    }
    delete d->item;
    d->item = 0;

    d->component = comp;
    d->ownComponent = false;
    if (!d->component) {
        emit sourceChanged();
        emit statusChanged();
        emit progressChanged();
        emit itemChanged();
        return;
    }

    if (!d->component->isLoading()) {
        d->_q_sourceLoaded();
    } else {
        connect(d->component, SIGNAL(statusChanged(QmlComponent::Status)),
                this, SLOT(_q_sourceLoaded()));
        connect(d->component, SIGNAL(progressChanged(qreal)),
                this, SIGNAL(progressChanged()));
        emit progressChanged();
        emit sourceChanged();
        emit statusChanged();
        emit itemChanged();
    }
}

void QFxLoaderPrivate::_q_sourceLoaded()
{
    Q_Q(QFxLoader);

    if (component) {
        QmlContext *ctxt = new QmlContext(qmlContext(q));
        ctxt->addDefaultObject(q);

        if (!component->errors().isEmpty()) {
            qWarning() << component->errors();
            emit q->sourceChanged();
            emit q->statusChanged();
            emit q->progressChanged();
            return;
        }

        QObject *obj = component->create(ctxt);
        if (obj) {
            item = qobject_cast<QFxItem *>(obj);
            if (item) {
                item->setParentItem(q);
//                item->setFocus(true);
                QFxItem *resizeItem = 0;
                if (resizeMode == QFxLoader::SizeLoaderToItem)
                    resizeItem = item;
                else if (resizeMode == QFxLoader::SizeItemToLoader)
                    resizeItem = q;
                if (resizeItem) {
                    QObject::connect(resizeItem, SIGNAL(widthChanged()), q, SLOT(_q_updateSize()));
                    QObject::connect(resizeItem, SIGNAL(heightChanged()), q, SLOT(_q_updateSize()));
                }
                _q_updateSize();
            }
        } else {
            delete obj;
            source = QUrl();
        }
        emit q->sourceChanged();
        emit q->statusChanged();
        emit q->progressChanged();
        emit q->itemChanged();
    }
}

/*!
    \qmlproperty enum Loader::status

    This property holds the status of QML loading.  It can be one of:
    \list
    \o Null - no QML source has been set
    \o Ready - the QML source has been loaded
    \o Loading - the QML source is currently being loaded
    \o Error - an error occurred while loading the QML source
    \endlist

    \sa progress
*/

QFxLoader::Status QFxLoader::status() const
{
    Q_D(const QFxLoader);

    if (d->component)
        return static_cast<QFxLoader::Status>(d->component->status());

    if (d->item)
        return Ready;

    return d->source.isEmpty() ? Null : Error;
}

/*!
    \qmlproperty real Loader::progress

    This property holds the progress of QML data loading, from 0.0 (nothing loaded)
    to 1.0 (finished).

    \sa status
*/
qreal QFxLoader::progress() const
{
    Q_D(const QFxLoader);

    if (d->item)
        return 1.0;

    if (d->component)
        return d->component->progress();

    return 0.0;
}

/*!
    \qmlproperty enum Loader::resizeMode

    This property determines how the Loader or item are resized:
    \list
    \o NoResize - no item will be resized
    \o SizeLoaderToItem - the Loader will be sized to the size of the item, unless the size of the Loader has been otherwise specified.
    \o SizeItemToLoader - the item will be sized to the size of the Loader.
    \endlist

    The default resizeMode is SizeLoaderToItem.
*/
QFxLoader::ResizeMode QFxLoader::resizeMode() const
{
    Q_D(const QFxLoader);
    return d->resizeMode;
}

void QFxLoader::setResizeMode(ResizeMode mode)
{
    Q_D(QFxLoader);
    if (mode == d->resizeMode)
        return;

    if (d->item) {
        QFxItem *resizeItem = 0;
        if (d->resizeMode == SizeLoaderToItem)
            resizeItem = d->item;
        else if (d->resizeMode == SizeItemToLoader)
            resizeItem = this;
        if (resizeItem) {
            disconnect(resizeItem, SIGNAL(widthChanged()), this, SLOT(_q_updateSize()));
            disconnect(resizeItem, SIGNAL(heightChanged()), this, SLOT(_q_updateSize()));
        }
    }

    d->resizeMode = mode;

    if (d->item) {
        QFxItem *resizeItem = 0;
        if (d->resizeMode == SizeLoaderToItem)
            resizeItem = d->item;
        else if (d->resizeMode == SizeItemToLoader)
            resizeItem = this;
        if (resizeItem) {
            connect(resizeItem, SIGNAL(widthChanged()), this, SLOT(_q_updateSize()));
            connect(resizeItem, SIGNAL(heightChanged()), this, SLOT(_q_updateSize()));
        }
    }
}

void QFxLoaderPrivate::_q_updateSize()
{
    Q_Q(QFxLoader);
    if (!item)
        return;
    switch (resizeMode) {
    case QFxLoader::SizeLoaderToItem:
        if (!q->widthValid())
            q->setImplicitWidth(item->width());
        if (!q->heightValid())
            q->setImplicitHeight(item->height());
        break;
    case QFxLoader::SizeItemToLoader:
        item->setWidth(q->width());
        item->setHeight(q->height());
        break;
    default:
        break;
    }
}

/*!
    \qmlproperty Item Loader::item
    This property holds the top-level item created from source.
*/
QFxItem *QFxLoader::item() const
{
    Q_D(const QFxLoader);
    return d->item;
}

QT_END_NAMESPACE

#include "moc_qfxloader.cpp"
<commit_msg>Best to delete pointer before zeroing it.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qfxloader_p.h"
#include <private/qmlengine_p.h>

QT_BEGIN_NAMESPACE

QFxLoaderPrivate::QFxLoaderPrivate()
: item(0), component(0), ownComponent(false), resizeMode(QFxLoader::SizeLoaderToItem)
{
}

QFxLoaderPrivate::~QFxLoaderPrivate()
{
}

QML_DEFINE_TYPE(Qt,4,6,(QT_VERSION&0x00ff00)>>8,Loader,QFxLoader)

/*!
    \qmlclass Loader
    \inherits Item

    \brief The Loader item allows dynamically loading an Item-based
    subtree from a QML URL or Component.

    Loader instantiates an item from a component. The component to
    instantiate may be specified directly by the \c sourceComponent
    property, or loaded from a URL via the \c source property.

    It is also an effective means of delaying the creation of a component
    until it is required:
    \code
    Loader { id: PageLoader }
    Rectangle {
        MouseRegion { anchors.fill: parent; onClicked: PageLoader.source = "Page1.qml" }
    }
    \endcode
*/

/*!
    \internal
    \class QFxLoader
    \qmlclass Loader
 */

/*!
    Create a new QFxLoader instance.
 */
QFxLoader::QFxLoader(QFxItem *parent)
  : QFxItem(*(new QFxLoaderPrivate), parent)
{
}

/*!
    Destroy the loader instance.
 */
QFxLoader::~QFxLoader()
{
}

/*!
    \qmlproperty url Loader::source
    This property holds the URL of the QML component to
    instantiate.

    \sa status, progress
*/
QUrl QFxLoader::source() const
{
    Q_D(const QFxLoader);
    return d->source;
}

void QFxLoader::setSource(const QUrl &url)
{
    Q_D(QFxLoader);
    if (d->source == url)
        return;

    if (d->ownComponent) {
        delete d->component;
        d->component = 0;
    }
    delete d->item;
    d->item = 0;

    d->source = url;
    if (d->source.isEmpty()) {
        emit sourceChanged();
        emit statusChanged();
        emit progressChanged();
        emit itemChanged();
        return;
    }

    d->component = new QmlComponent(qmlEngine(this), d->source, this);
    d->ownComponent = true;
    if (!d->component->isLoading()) {
        d->_q_sourceLoaded();
    } else {
        connect(d->component, SIGNAL(statusChanged(QmlComponent::Status)),
                this, SLOT(_q_sourceLoaded()));
        connect(d->component, SIGNAL(progressChanged(qreal)),
                this, SIGNAL(progressChanged()));
        emit statusChanged();
        emit progressChanged();
        emit sourceChanged();
        emit itemChanged();
    }
}

/*!
    \qmlproperty Component Loader::sourceComponent
    The sourceComponent property holds the \l{Component} to instantiate.

    \qml
    Item {
        Component {
            id: RedSquare
            Rectangle { color: "red"; width: 10; height: 10 }
        }

        Loader { sourceComponent: RedSquare }
        Loader { sourceComponent: RedSquare; x: 10 }
    }
    \endqml

    \sa source
*/

QmlComponent *QFxLoader::sourceComponent() const
{
    Q_D(const QFxLoader);
    return d->component;
}

void QFxLoader::setSourceComponent(QmlComponent *comp)
{
    Q_D(QFxLoader);
    if (comp == d->component)
        return;

    d->source = QUrl();
    if (d->ownComponent) {
        delete d->component;
        d->component = 0;
    }
    delete d->item;
    d->item = 0;

    d->component = comp;
    d->ownComponent = false;
    if (!d->component) {
        emit sourceChanged();
        emit statusChanged();
        emit progressChanged();
        emit itemChanged();
        return;
    }

    if (!d->component->isLoading()) {
        d->_q_sourceLoaded();
    } else {
        connect(d->component, SIGNAL(statusChanged(QmlComponent::Status)),
                this, SLOT(_q_sourceLoaded()));
        connect(d->component, SIGNAL(progressChanged(qreal)),
                this, SIGNAL(progressChanged()));
        emit progressChanged();
        emit sourceChanged();
        emit statusChanged();
        emit itemChanged();
    }
}

void QFxLoaderPrivate::_q_sourceLoaded()
{
    Q_Q(QFxLoader);

    if (component) {
        QmlContext *ctxt = new QmlContext(qmlContext(q));
        ctxt->addDefaultObject(q);

        if (!component->errors().isEmpty()) {
            qWarning() << component->errors();
            emit q->sourceChanged();
            emit q->statusChanged();
            emit q->progressChanged();
            return;
        }

        QObject *obj = component->create(ctxt);
        if (obj) {
            item = qobject_cast<QFxItem *>(obj);
            if (item) {
                item->setParentItem(q);
//                item->setFocus(true);
                QFxItem *resizeItem = 0;
                if (resizeMode == QFxLoader::SizeLoaderToItem)
                    resizeItem = item;
                else if (resizeMode == QFxLoader::SizeItemToLoader)
                    resizeItem = q;
                if (resizeItem) {
                    QObject::connect(resizeItem, SIGNAL(widthChanged()), q, SLOT(_q_updateSize()));
                    QObject::connect(resizeItem, SIGNAL(heightChanged()), q, SLOT(_q_updateSize()));
                }
                _q_updateSize();
            }
        } else {
            delete obj;
            source = QUrl();
        }
        emit q->sourceChanged();
        emit q->statusChanged();
        emit q->progressChanged();
        emit q->itemChanged();
    }
}

/*!
    \qmlproperty enum Loader::status

    This property holds the status of QML loading.  It can be one of:
    \list
    \o Null - no QML source has been set
    \o Ready - the QML source has been loaded
    \o Loading - the QML source is currently being loaded
    \o Error - an error occurred while loading the QML source
    \endlist

    \sa progress
*/

QFxLoader::Status QFxLoader::status() const
{
    Q_D(const QFxLoader);

    if (d->component)
        return static_cast<QFxLoader::Status>(d->component->status());

    if (d->item)
        return Ready;

    return d->source.isEmpty() ? Null : Error;
}

/*!
    \qmlproperty real Loader::progress

    This property holds the progress of QML data loading, from 0.0 (nothing loaded)
    to 1.0 (finished).

    \sa status
*/
qreal QFxLoader::progress() const
{
    Q_D(const QFxLoader);

    if (d->item)
        return 1.0;

    if (d->component)
        return d->component->progress();

    return 0.0;
}

/*!
    \qmlproperty enum Loader::resizeMode

    This property determines how the Loader or item are resized:
    \list
    \o NoResize - no item will be resized
    \o SizeLoaderToItem - the Loader will be sized to the size of the item, unless the size of the Loader has been otherwise specified.
    \o SizeItemToLoader - the item will be sized to the size of the Loader.
    \endlist

    The default resizeMode is SizeLoaderToItem.
*/
QFxLoader::ResizeMode QFxLoader::resizeMode() const
{
    Q_D(const QFxLoader);
    return d->resizeMode;
}

void QFxLoader::setResizeMode(ResizeMode mode)
{
    Q_D(QFxLoader);
    if (mode == d->resizeMode)
        return;

    if (d->item) {
        QFxItem *resizeItem = 0;
        if (d->resizeMode == SizeLoaderToItem)
            resizeItem = d->item;
        else if (d->resizeMode == SizeItemToLoader)
            resizeItem = this;
        if (resizeItem) {
            disconnect(resizeItem, SIGNAL(widthChanged()), this, SLOT(_q_updateSize()));
            disconnect(resizeItem, SIGNAL(heightChanged()), this, SLOT(_q_updateSize()));
        }
    }

    d->resizeMode = mode;

    if (d->item) {
        QFxItem *resizeItem = 0;
        if (d->resizeMode == SizeLoaderToItem)
            resizeItem = d->item;
        else if (d->resizeMode == SizeItemToLoader)
            resizeItem = this;
        if (resizeItem) {
            connect(resizeItem, SIGNAL(widthChanged()), this, SLOT(_q_updateSize()));
            connect(resizeItem, SIGNAL(heightChanged()), this, SLOT(_q_updateSize()));
        }
    }
}

void QFxLoaderPrivate::_q_updateSize()
{
    Q_Q(QFxLoader);
    if (!item)
        return;
    switch (resizeMode) {
    case QFxLoader::SizeLoaderToItem:
        if (!q->widthValid())
            q->setImplicitWidth(item->width());
        if (!q->heightValid())
            q->setImplicitHeight(item->height());
        break;
    case QFxLoader::SizeItemToLoader:
        item->setWidth(q->width());
        item->setHeight(q->height());
        break;
    default:
        break;
    }
}

/*!
    \qmlproperty Item Loader::item
    This property holds the top-level item created from source.
*/
QFxItem *QFxLoader::item() const
{
    Q_D(const QFxLoader);
    return d->item;
}

QT_END_NAMESPACE

#include "moc_qfxloader.cpp"
<|endoftext|>


<commit_before>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Nathan Osman
 *
 * 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 <QNetworkInterface>

#include "socketlistener.h"

SocketListener::SocketListener()
{
    connect(&monitor, &InterfaceMonitor::interfaceAdded, this, &SocketListener::addInterface);
    connect(&monitor, &InterfaceMonitor::interfaceRemoved, this, &SocketListener::removeInterface);
    connect(&timer, &QTimer::interval, this, &SocketListener::sendPing);
    connect(Settings::instance(), &Settings::settingChanged, this, &SocketListener::settingChanged);

    reload();
}

SocketListener::~SocketListener()
{
    QMap<QString, QUdpSocket *>::iterator i;

    for(i = sockets.begin(); i != sockets.end(); ++i) {
        shutdown(i.value(), true);
    }
}

void SocketListener::start()
{
    monitor.start();
    timer.start();
}

void SocketListener::addInterface(const QString &name)
{
    QUdpSocket * socket = new QUdpSocket;

    if(initialize(socket, name)) {
        sockets.insert(name, socket);
        return;
    }

    socket->deleteLater();
}

void SocketListener::removeInterface(const QString &name)
{
    shutdown(sockets.take(name), true);
}

void SocketListener::sendPing()
{
    QMap<QString, QUdpSocket *>::iterator i;

    for(i = sockets.begin(); i != sockets.end(); ++i) {
        i.value()->writeDatagram(Device::current(), multicastAddress, multicastPort);
    }
}

void SocketListener::processDatagrams()
{
    QUdpSocket * socket = qobject_cast<QUdpSocket *>(sender());

    while(socket->hasPendingDatagrams()) {
        QByteArray data;
        data.resize(socket->pendingDatagramSize());
        socket->readDatagram(data.data(), data.size());

        Device device;
        if(Device::deserialize(data, device)) {
            emit pingReceived(device);
        }
    }
}

void SocketListener::settingChanged(Settings::Key key)
{
    if(key == Settings::PingInterval || key == Settings::MulticastAddress ||
            key == Settings::MulticastPort) {

        QMap<QString, QUdpSocket *>::iterator i;

        for(i = sockets.begin(); i != sockets.end(); ++i) {
            shutdown(i.value(), false);
        }

        timer.stop();
        reload();
        timer.start();

        for(i = sockets.begin(); i != sockets.end(); ++i) {
            if(!initialize(i.value(), i.key())) {
                shutdown(sockets.take(i.key()), true);
            }
        }
    }
}

void SocketListener::reload()
{
    timer.setInterval(Settings::get<int>(Settings::PingInterval));

    multicastAddress = QHostAddress(Settings::get<QString>(Settings::MulticastAddress));
    multicastPort = Settings::get<quint16>(Settings::MulticastPort);
}

bool SocketListener::initialize(QUdpSocket *socket, const QString &name)
{
    QNetworkInterface interface = QNetworkInterface::interfaceFromName(name);

    return socket->bind(multicastPort, QUdpSocket::ShareAddress) &&
            socket->joinMulticastGroup(multicastAddress, interface);
}

void SocketListener::shutdown(QUdpSocket *socket, bool destroy)
{
    socket->leaveMulticastGroup(multicastAddress, socket->multicastInterface());
    socket->close();

    if(destroy) {
        socket->deleteLater();
    }
}
<commit_msg>Switched back to Java-style iterators and fixed QMap removal issue.<commit_after>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Nathan Osman
 *
 * 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 <QMapIterator>
#include <QMutableMapIterator>
#include <QNetworkInterface>

#include "socketlistener.h"

SocketListener::SocketListener()
{
    connect(&monitor, &InterfaceMonitor::interfaceAdded, this, &SocketListener::addInterface);
    connect(&monitor, &InterfaceMonitor::interfaceRemoved, this, &SocketListener::removeInterface);
    connect(&timer, &QTimer::interval, this, &SocketListener::sendPing);
    connect(Settings::instance(), &Settings::settingChanged, this, &SocketListener::settingChanged);

    reload();
}

SocketListener::~SocketListener()
{
    QMapIterator<QString, QUdpSocket *> i(sockets);

    while(i.hasNext()) {
        shutdown(i.next().value(), true);
    }
}

void SocketListener::start()
{
    monitor.start();
    timer.start();
}

void SocketListener::addInterface(const QString &name)
{
    QUdpSocket * socket = new QUdpSocket;

    if(initialize(socket, name)) {
        sockets.insert(name, socket);
        return;
    }

    socket->deleteLater();
}

void SocketListener::removeInterface(const QString &name)
{
    shutdown(sockets.take(name), true);
}

void SocketListener::sendPing()
{
    QMapIterator<QString, QUdpSocket *> i(sockets);

    while(i.hasNext()) {
        i.next().value()->writeDatagram(Device::current(), multicastAddress, multicastPort);
    }
}

void SocketListener::processDatagrams()
{
    QUdpSocket * socket = qobject_cast<QUdpSocket *>(sender());

    while(socket->hasPendingDatagrams()) {
        QByteArray data;
        data.resize(socket->pendingDatagramSize());
        socket->readDatagram(data.data(), data.size());

        Device device;
        if(Device::deserialize(data, device)) {
            emit pingReceived(device);
        }
    }
}

void SocketListener::settingChanged(Settings::Key key)
{
    if(key == Settings::PingInterval || key == Settings::MulticastAddress ||
            key == Settings::MulticastPort) {
        {
            QMapIterator<QString, QUdpSocket *> i(sockets);

            while(i.hasNext()) {
                shutdown(i.next().value(), false);
            }
        }

        timer.stop();
        reload();
        timer.start();

        {
            QMutableMapIterator<QString, QUdpSocket *> i(sockets);

            while(i.hasNext()) {
                i.next();
                if(!initialize(i.value(), i.key())) {
                    shutdown(i.value(), true);
                    i.remove();
                }
            }
        }
    }
}

void SocketListener::reload()
{
    timer.setInterval(Settings::get<int>(Settings::PingInterval));

    multicastAddress = QHostAddress(Settings::get<QString>(Settings::MulticastAddress));
    multicastPort = Settings::get<quint16>(Settings::MulticastPort);
}

bool SocketListener::initialize(QUdpSocket *socket, const QString &name)
{
    QNetworkInterface interface = QNetworkInterface::interfaceFromName(name);

    return socket->bind(multicastPort, QUdpSocket::ShareAddress) &&
            socket->joinMulticastGroup(multicastAddress, interface);
}

void SocketListener::shutdown(QUdpSocket *socket, bool destroy)
{
    socket->leaveMulticastGroup(multicastAddress, socket->multicastInterface());
    socket->close();

    if(destroy) {
        socket->deleteLater();
    }
}
<|endoftext|>


<commit_before>#include "WindowWidget.hpp"
using namespace fast;

void WindowWidget::keyPressEvent(QKeyEvent* event) {
    mView->keyPressEvent(event);
}

void WindowWidget::mouseMoveEvent(QMouseEvent* event) {
    mView->mouseMoveEvent(event);
}

void WindowWidget::mousePressEvent(QMouseEvent* event) {
    mView->mousePressEvent(event);
}

void WindowWidget::mouseReleaseEvent(QMouseEvent* event) {
    mView->mouseReleaseEvent(event);
}
<commit_msg>close window if user presses q or escape<commit_after>#include "WindowWidget.hpp"
using namespace fast;

void WindowWidget::keyPressEvent(QKeyEvent* event) {
    switch(event->key()) {
    case Qt::Key_Q:
    case Qt::Key_Escape:
        close();
        break;
    }
    mView->keyPressEvent(event);
}

void WindowWidget::mouseMoveEvent(QMouseEvent* event) {
    mView->mouseMoveEvent(event);
}

void WindowWidget::mousePressEvent(QMouseEvent* event) {
    mView->mousePressEvent(event);
}

void WindowWidget::mouseReleaseEvent(QMouseEvent* event) {
    mView->mouseReleaseEvent(event);
}
<|endoftext|>


<commit_before>#include <MetaValueImplementation.h>

#include <iostream>

using namespace std;

using Double = MetaValueImplementation<double>;
using Int = MetaValueImplementation<int64_t>;

int main() {
  MetaValue copy;
  MetaValue d1 = Double({{1.1, 2.2}, {3.3, 0.0}});
  MetaValue d2 = Double({{4.4, 5.5}, {6.6, 0.0}});
  cout << "d1   (" << d1.size() << "): " << d1 << endl;
  cout << "d2   (" << d2.size() << "): " << d2 << endl;
  cout << "d1+d2    : " << d1+d2 << endl;
  MetaValue i1 = Int({4, 5, 6});
  MetaValue i2 = Int({7, 8, 9});
  MetaValue i3 = Int({10});
  cout << "i1   (" << i1.size() << "): " << i1 << endl;
  cout << "i2   (" << i2.size() << "): " << i2 << endl;
  cout << "i3   (" << i3.size() << "): " << i3 << endl;
  cout << "i1+i2    : " << i1+i2 << endl;
  cout << "i1+i3    : " << i1+i3 << endl;
  cout << "d1+i2    : " << d1+i2 << endl;
  cout << "copy     : " << copy << endl;
  copy=d1;
  cout << "copy=d1  : " << copy << endl;
  return 0;
}

<commit_msg>Removed unsupported MetaValue Use-Case<commit_after><|endoftext|>


<commit_before>#include <config.h>

#include <vector>

#include <libport/cstdlib>

#include <libport/containers.hh>
#include <libport/debug.hh>
#include <libport/detect-win32.h>
#include <libport/program-name.hh>
#include <libport/separate.hh>
#include <libport/unistd.h>

GD_INIT();
GD_ADD_CATEGORY(Urbi);

int
main(int argc, char* argv[])
{
  libport::program_initialize(argc, argv);
  // Installation prefix.
  std::string urbi_root = libport::xgetenv("URBI_ROOT", URBI_ROOT);
  std::string urbi_launch =
    libport::xgetenv("URBI_LAUNCH", urbi_root + "/bin/urbi-launch" EXEEXT);
  std::vector<const char*> args;
  args.reserve(3 + argc + 1);
  libport::OptionParser opt_parser;
  opt_parser << libport::opts::debug;
  opt_parser(libport::program_arguments());
  args << urbi_launch.c_str()
       << "--start";
  if (libport::opts::debug.filled())
    args << "--debug" << libport::opts::debug.value().c_str();
  args << "--";
  args.insert(args.end(), argv + 1, argv + argc);
  GD_CATEGORY(Urbi);
  GD_FINFO_DEBUG("exec: %s", (libport::separate(args, " ")));
  libport::exec(args);
}
<commit_msg>urbi: fix debug category.<commit_after>#include <config.h>

#include <vector>

#include <libport/cstdlib>

#include <libport/containers.hh>
#include <libport/debug.hh>
#include <libport/detect-win32.h>
#include <libport/program-name.hh>
#include <libport/separate.hh>
#include <libport/unistd.h>

GD_INIT();
GD_ADD_CATEGORY(urbi);

int
main(int argc, char* argv[])
{
  libport::program_initialize(argc, argv);
  // Installation prefix.
  std::string urbi_root = libport::xgetenv("URBI_ROOT", URBI_ROOT);
  std::string urbi_launch =
    libport::xgetenv("URBI_LAUNCH", urbi_root + "/bin/urbi-launch" EXEEXT);
  std::vector<const char*> args;
  args.reserve(3 + argc + 1);
  libport::OptionParser opt_parser;
  opt_parser << libport::opts::debug;
  opt_parser(libport::program_arguments());
  args << urbi_launch.c_str()
       << "--start";
  if (libport::opts::debug.filled())
    args << "--debug" << libport::opts::debug.value().c_str();
  args << "--";
  args.insert(args.end(), argv + 1, argv + argc);
  GD_CATEGORY(urbi);
  GD_FINFO_DEBUG("exec: %s", (libport::separate(args, " ")));
  libport::exec(args);
}
<|endoftext|>


<commit_before>#include "Example1.h"

#include <FrameView.h>
#include <TextLabel.h>
#include <LinearLayout.h>
#include <Button.h>
#include <ScrollLayout.h>
#include <Switch.h>
#include <TextField.h>
#include <ImageElement.h>
#include <NavigationBar.h>
#include <NavigationBarItem.h>

#include <iostream>

using namespace std;

Example1::Example1() : FWApplication("com.sometrik.example1")
{
  auto view = std::make_shared<FrameView>();
  view->style("background-color", "#cccccc");
  addChild(view);

  auto layout = std::make_shared<LinearLayout>(FW_VERTICAL);
  view->addChild(layout);

  auto image = std::make_shared<ImageElement>("test.png");
  layout->addChild(image);

  auto title = make_shared<TextLabel>("Hello again!", 1234);
  title->style("font-size", 20);
  title->style("background-color", "#e03030");
  title->style("shadow", 5);
  title->style("border", "#801010");
  title->style("border-radius", 5);
  layout->addChild(title);

  auto nameLayout = make_shared<LinearLayout>(FW_HORIZONTAL);
  layout->addChild(nameLayout);
  nameLayout->addChild(make_shared<TextLabel>("Kirjoita nimesi:"));

  textField = make_shared<TextField>();
  nameLayout->addChild(textField);

  layout->addChild(make_shared<Switch>("On", "Off"));

  auto buttonLayout = std::make_shared<LinearLayout>(FW_HORIZONTAL);
  buttonLayout->addChild(make_shared<Button>("Click me!")).style("background", "#30e030").style("border-radius", 5);
  buttonLayout->addChild(make_shared<Button>("Cancel"));
  buttonLayout->addChild(make_shared<Button>("Button"));
  layout->addChild(buttonLayout);

  auto scrollLayout = std::make_shared<ScrollLayout>();
  scrollLayout->style("min-height", 200);
  layout->addChild(scrollLayout);
  auto scrollContent = std::make_shared<LinearLayout>(FW_VERTICAL);
  scrollLayout->addChild(scrollContent);

  for (int i = 0; i < 100; i++) {
    scrollContent->addChild(std::make_shared<TextLabel>("Number: " + to_string(i)));
  }

  auto navigationBar = std::make_shared<NavigationBar>();
  navigationBar->addChild(std::make_shared<NavigationBarItem>("Page 1"));
  navigationBar->addChild(std::make_shared<NavigationBarItem>("Page 2"));
  navigationBar->addChild(std::make_shared<NavigationBarItem>("Page 3"));
  layout->addChild(navigationBar);
}

void
Example1::onCommandEvent(CommandEvent & ev) {
  getLogger().println("got command event " + textField->getValue());

  getChildById(1234).text("Hello " + textField->getValue() + "!");
}

FWApplication * applicationMain() {
  return new Example1();
}
<commit_msg>update example<commit_after>#include "Example1.h"

#include <FrameView.h>
#include <TextLabel.h>
#include <LinearLayout.h>
#include <Button.h>
#include <ScrollLayout.h>
#include <Switch.h>
#include <TextField.h>
#include <ImageElement.h>
#include <NavigationBar.h>
#include <NavigationBarItem.h>
#include <FrameLayout.h>
#include <ProgressBar.h>

#include <iostream>

using namespace std;

Example1::Example1() : FWApplication("com.sometrik.example1")
{
  auto view = std::make_shared<FrameView>();
  view->style("background-color", "#cccccc");
  addChild(view);

  auto layout = std::make_shared<LinearLayout>(FW_VERTICAL);
  view->addChild(layout);

  auto image = std::make_shared<ImageElement>("test.png");
  layout->addChild(image);

  layout->addChild(make_shared<ProgressBar>());

  auto title = make_shared<TextLabel>("Hello again!", 1234);
  title->style("font-size", 20);
  title->style("background-color", "#e03030");
  title->style("shadow", 5);
  title->style("border", "#801010");
  title->style("border-radius", 5);
  layout->addChild(title);

  auto nameLayout = make_shared<LinearLayout>(FW_HORIZONTAL);
  layout->addChild(nameLayout);
  nameLayout->addChild(make_shared<TextLabel>("Kirjoita nimesi:"));

  textField = make_shared<TextField>();
  nameLayout->addChild(textField);

  auto buttonLayout = std::make_shared<LinearLayout>(FW_HORIZONTAL);
  buttonLayout->addChild(make_shared<Button>("Click me!")).style("background", "#30e030").style("border-radius", 5);
  buttonLayout->addChild(make_shared<Button>("Cancel"));
  buttonLayout->addChild(make_shared<Button>("Button"));
  layout->addChild(buttonLayout);

  auto scrollLayout = std::make_shared<ScrollLayout>();
  scrollLayout->style("min-height", 200);
  layout->addChild(scrollLayout);
  auto scrollFrame = std::make_shared<FrameLayout>();
  scrollLayout->addChild(scrollFrame);
  auto scrollContent = std::make_shared<LinearLayout>(FW_VERTICAL);
  scrollFrame->addChild(scrollContent);

  for (int i = 0; i < 100; i++) {
    scrollContent->addChild(std::make_shared<TextLabel>("Number: " + to_string(i)));
  }

  layout->addChild(make_shared<Switch>("On", "Off"));

  auto navigationBar = std::make_shared<NavigationBar>();
  navigationBar->addChild(std::make_shared<NavigationBarItem>("Page 1"));
  navigationBar->addChild(std::make_shared<NavigationBarItem>("Page 2"));
  navigationBar->addChild(std::make_shared<NavigationBarItem>("Page 3"));
  layout->addChild(navigationBar);
}

void
Example1::onCommandEvent(CommandEvent & ev) {
  getLogger().println("got command event " + textField->getValue());

  getChildById(1234).text("Hello " + textField->getValue() + "!");
}

FWApplication * applicationMain() {
  return new Example1();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: adc_msg.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2005-01-27 11:20:53 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef ADC_ADC_MSG_HXX
#define ADC_ADC_MSG_HXX

// USED SERVICES
    // BASE CLASSES
    // COMPONENTS
    // PARAMETERS
namespace csv
{
    class File;
}

namespace autodoc
{

/** Gathers, sorts and displays (mainly diagnostic) messages to the
    user of Autodoc.
*/
class Messages
{
  public:
    // LIFECYCLE
                        Messages();
                        ~Messages();
    // OPERATIONS
    void                WriteFile(
                            const String &      i_sOutputFilePath);
    // INQUIRY

    // ACCESS
    void                Out_MissingDoc(
                            const String &      i_sEntity,
                            const String &      i_sFile,
                            uintt               i_nLine);
    void                Out_ParseError(
                            const String &      i_sFile,
                            uintt               i_nLine);
    void                Out_InvalidConstSymbol(
                            const String &      i_sText,
                            const String &      i_sFile,
                            uintt               i_nLine);
    void                Out_UnresolvedLink(
                            const String &      i_sLinkText,
                            const String &      i_sFile,
                            uintt               i_nLine);
    void                Out_TypeVsMemberMisuse(
                            const String &      i_sLinkText,
                            const String &      i_sFile,
                            uintt               i_nLine);

    static Messages &   The_();

  private:
    struct Location
    {
        String              sFile;
        uintt               nLine;

                            Location(
                                const String &      i_file,
                                uintt               i_line)
                                :   sFile(i_file),
                                    nLine(i_line)   {}
        bool                operator<(
                                const Location &    i_other) const
                                { int cmp = csv::compare(sFile,i_other.sFile);
                                  return cmp < 0
                                            ?   true
                                            :   cmp > 0
                                                    ?   false
                                                    :   nLine < i_other.nLine;
                                }
    };

    typedef std::map<Location,String>   MessageMap;

    // Locals
    void                AddValue(
                            MessageMap &        o_dest,
                            const String &      i_sText,
                            const String &      i_sFile,
                            uintt               i_nLine );
    void                WriteParagraph(
                            csv::File &         o_out,
                            const MessageMap &  i_source,
                            const String &      i_title,
                            const String &      i_firstIntermediateText );

    // DATA
    MessageMap          aMissingDocs;
    MessageMap          aParseErrors;
    MessageMap          aInvalidConstSymbols;
    MessageMap          aUnresolvedLinks;
    MessageMap          aTypeVsMemberMisuses;
};

// IMPLEMENTATION

}   // namespace autodoc

inline autodoc::Messages &
TheMessages()
{
    return autodoc::Messages::The_();
}

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.16); FILE MERGED 2005/09/05 13:11:30 rt 1.2.16.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: adc_msg.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 18:08:39 $
 *
 *  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 ADC_ADC_MSG_HXX
#define ADC_ADC_MSG_HXX

// USED SERVICES
    // BASE CLASSES
    // COMPONENTS
    // PARAMETERS
namespace csv
{
    class File;
}

namespace autodoc
{

/** Gathers, sorts and displays (mainly diagnostic) messages to the
    user of Autodoc.
*/
class Messages
{
  public:
    // LIFECYCLE
                        Messages();
                        ~Messages();
    // OPERATIONS
    void                WriteFile(
                            const String &      i_sOutputFilePath);
    // INQUIRY

    // ACCESS
    void                Out_MissingDoc(
                            const String &      i_sEntity,
                            const String &      i_sFile,
                            uintt               i_nLine);
    void                Out_ParseError(
                            const String &      i_sFile,
                            uintt               i_nLine);
    void                Out_InvalidConstSymbol(
                            const String &      i_sText,
                            const String &      i_sFile,
                            uintt               i_nLine);
    void                Out_UnresolvedLink(
                            const String &      i_sLinkText,
                            const String &      i_sFile,
                            uintt               i_nLine);
    void                Out_TypeVsMemberMisuse(
                            const String &      i_sLinkText,
                            const String &      i_sFile,
                            uintt               i_nLine);

    static Messages &   The_();

  private:
    struct Location
    {
        String              sFile;
        uintt               nLine;

                            Location(
                                const String &      i_file,
                                uintt               i_line)
                                :   sFile(i_file),
                                    nLine(i_line)   {}
        bool                operator<(
                                const Location &    i_other) const
                                { int cmp = csv::compare(sFile,i_other.sFile);
                                  return cmp < 0
                                            ?   true
                                            :   cmp > 0
                                                    ?   false
                                                    :   nLine < i_other.nLine;
                                }
    };

    typedef std::map<Location,String>   MessageMap;

    // Locals
    void                AddValue(
                            MessageMap &        o_dest,
                            const String &      i_sText,
                            const String &      i_sFile,
                            uintt               i_nLine );
    void                WriteParagraph(
                            csv::File &         o_out,
                            const MessageMap &  i_source,
                            const String &      i_title,
                            const String &      i_firstIntermediateText );

    // DATA
    MessageMap          aMissingDocs;
    MessageMap          aParseErrors;
    MessageMap          aInvalidConstSymbols;
    MessageMap          aUnresolvedLinks;
    MessageMap          aTypeVsMemberMisuses;
};

// IMPLEMENTATION

}   // namespace autodoc

inline autodoc::Messages &
TheMessages()
{
    return autodoc::Messages::The_();
}

#endif
<|endoftext|>


<commit_before>#include "StableHeaders.h"

#include "FarsightChannel.h"

#include <TelepathyQt4/Farsight/Channel>

namespace TelepathyIM
{
    FarsightChannel::FarsightChannel(const Tp::StreamedMediaChannelPtr &channel,
                                     const QString &audioSrc,
                                     const QString &audioSink,
                                     const QString &videoSrc)
                                     : QObject(0)
                                     // are these needed?
                                     //channel_(0), tf_channel_(0), bus_(0), pipeline_(0), audio_input_(0),
                                     //audio_output_(0), video_input_(0), video_tee_(0),
                                     //audio_volume_(0),
                                     //audio_resample_(0)
    {
        tf_channel_ = createFarsightChannel(channel);
        if (!tf_channel_) {
            LogError("Unable to construct TfChannel");
            return;
        }
        ConnectTfChannelEvents();

        //g_value_init (&volume_, G_TYPE_DOUBLE);
        pipeline_ = gst_pipeline_new(NULL);
        bus_ = gst_pipeline_get_bus(GST_PIPELINE(pipeline_));

        // create audioSrc, audioSink, videoSrc based on given vals
        audio_input_ = setUpElement(audioSrc);
        audio_output_ = setUpElement(audioSink);

        // audio modifications
        audio_resample_ = gst_element_factory_make("audioresample", NULL);
        //audio_volume_  = gst_element_factory_make("volume", NULL);

        audio_bin_ = gst_bin_new("audio-output-bin");

        gst_bin_add_many(GST_BIN(audio_bin_), audio_resample_, audio_output_, NULL);
        gst_element_link_many(audio_resample_, audio_output_, NULL);

        // add ghost pad to audio_bin_
        GstPad *sink = gst_element_get_static_pad(audio_resample_, "sink");
        audio_ghost_ = gst_ghost_pad_new("sink", sink);
        gst_element_add_pad(GST_ELEMENT(audio_bin_), audio_ghost_);
        gst_object_unref(G_OBJECT(sink));
        gst_object_ref(audio_bin_);
        gst_object_sink(audio_bin_);

        GstElement *video_src;

        if(videoSrc!=NULL) // If the videoSrc!=NULL we set up the pipeline with video preview elements
        {
            // create video elems,
            video_bin_ = gst_bin_new("video-input-bin");

            GstElement *scale = gst_element_factory_make("videoscale", NULL);
            GstElement *rate = gst_element_factory_make("videorate", NULL);
            GstElement *colorspace = gst_element_factory_make("ffmpegcolorspace", NULL);
            GstElement *capsfilter = gst_element_factory_make("capsfilter", NULL);
            GstCaps *caps = gst_caps_new_simple("video/x-raw-yuv",
                    "width", G_TYPE_INT, 320,
                    "height", G_TYPE_INT, 240,
                    NULL);
            g_object_set(G_OBJECT(capsfilter), "caps", caps, NULL);

            video_src = setUpElement(videoSrc);
            gst_bin_add_many(GST_BIN(video_bin_), video_src, scale, rate, colorspace, capsfilter, NULL);
            gst_element_link_many(video_src, scale, rate, colorspace, capsfilter, NULL);
            GstPad *src = gst_element_get_static_pad(capsfilter, "src");
            GstPad *ghost = gst_ghost_pad_new("src", src);
            Q_ASSERT(gst_element_add_pad(GST_ELEMENT(video_bin_), ghost));
            gst_object_unref(G_OBJECT(src));
            gst_object_ref(video_input_);
            gst_object_sink(video_input_);

            video_tee_ = setUpElement("tee");
            //video_preview_element_ = setUpElement("glimagesink");
            video_preview_element_ = setUpElement("autovideosink");
            gst_bin_add_many(GST_BIN(pipeline_), video_bin_, video_tee_,
                    video_preview_element_, NULL);
            gst_element_link_many(video_bin_, video_tee_,
                    video_preview_element_, NULL);

            video_remote_output_element_ = setUpElement("autovideosink");
        }
        // can empty pipeline be put to playing when video is not used?, lets try anyway
        gst_element_set_state(pipeline_, GST_STATE_PLAYING);
        status_ = StatusConnecting;
        emit statusChanged(status_);
    }

    FarsightChannel::~FarsightChannel()
    {
        if (tf_channel_) {
            g_object_unref(tf_channel_);
            tf_channel_ = 0;
        }
        if (bus_) {
            g_object_unref(bus_);
            bus_ = 0;
        }
        gst_element_set_state(pipeline_, GST_STATE_NULL);
        if (pipeline_) {
            g_object_unref(pipeline_);
            pipeline_ = 0;
        }
        if (audio_input_) {
            g_object_unref(audio_input_);
            audio_input_ = 0;
        }
        if (audio_output_) {
            g_object_unref(audio_output_);
            audio_output_ = 0;
        }
    }

    void FarsightChannel::ConnectTfChannelEvents()
    {
        /* Set up the telepathy farsight channel */
        g_signal_connect(tf_channel_, "closed", G_CALLBACK(&FarsightChannel::onClosed), this);
        g_signal_connect(tf_channel_, "session-created", G_CALLBACK(&FarsightChannel::onSessionCreated), this);
        g_signal_connect(tf_channel_, "stream-created", G_CALLBACK(&FarsightChannel::onStreamCreated), this);
    }

    GstElement* FarsightChannel::setUpElement(QString elemName)
    {
        const char* arrayTest = elemName.toStdString().c_str();
        GstElement* element = gst_element_factory_make(elemName.toStdString().c_str(), NULL);
        gst_object_ref(element);
        gst_object_sink(element);
        return element;
    }

    FarsightChannel::Status FarsightChannel::GetStatus() const
    {
        return status_;
    }

    void FarsightChannel::SetAudioPlaybackVolume(const double value)
    {
        if(value<0||value>1){
            LogError("Trying to set volume out of range");
            return;
        }
        double setValue = value*10; // range is from 0 to 10
        //g_value_set_double(&volume_, setValue);
        //g_object_set_property (G_OBJECT(audio_volume_), "volume", &volume_);
    }

    void FarsightChannel::SetAudioRecordVolume(const double value)
    {
        if(value<0||value>1){
            LogError("Trying to set record volume out of range");
            return;
        }
        // todo: Implement
    }

    // Link bus events to tf_channel_
    gboolean FarsightChannel::busWatch(GstBus *bus, GstMessage *message, FarsightChannel *self)
    {
        try {
            if(self->tf_channel_ == NULL)
            {
                LogWarning("CommunicationModule: receiving bus message when tf_channel_ is NULL");
                return FALSE;
            }
            tf_channel_bus_message(self->tf_channel_, message);
            return TRUE;
        } catch(...){
            LogWarning("CommunicationModule: passing gstreamer bus message to telepathy-farsight failed");
            return FALSE;
        }
    }

    void FarsightChannel::onClosed(TfChannel *tfChannel,
        FarsightChannel *self)
    {
        self->status_ = StatusDisconnected;
        emit self->statusChanged(self->status_);
    }

    void FarsightChannel::onSessionCreated(TfChannel *tfChannel,
        FsConference *conference, FsParticipant *participant,
            FarsightChannel *self)
    {
        gst_bus_add_watch(self->bus_, (GstBusFunc) &FarsightChannel::busWatch, self);
        gst_bin_add(GST_BIN(self->pipeline_), GST_ELEMENT(conference));
        gst_element_set_state(GST_ELEMENT(conference), GST_STATE_PLAYING);
    }

    void FarsightChannel::onStreamCreated(TfChannel *tfChannel,
        TfStream *stream, FarsightChannel *self)
    {
        guint media_type;
        GstPad *sink;

        g_signal_connect(stream, "src-pad-added", G_CALLBACK(&FarsightChannel::onSrcPadAdded), self);
        g_signal_connect(stream, "request-resource", G_CALLBACK(&FarsightChannel::onRequestResource), NULL);

        g_object_get(stream, "media-type", &media_type, "sink-pad", &sink, NULL);

        GstPad *pad;

        switch (media_type) {
        case TP_MEDIA_STREAM_TYPE_AUDIO:
            gst_bin_add(GST_BIN(self->pipeline_), self->audio_input_);
            gst_element_set_state(self->audio_input_, GST_STATE_PLAYING);
            pad = gst_element_get_static_pad(self->audio_input_, "src");
            gst_pad_link(pad, sink);
            break;
        case TP_MEDIA_STREAM_TYPE_VIDEO:
            pad = gst_element_get_request_pad(self->video_tee_, "src%d");
            gst_pad_link(pad, sink);
            break;
        default:
            Q_ASSERT(false);
        }

        gst_object_unref(sink);
    }

    void FarsightChannel::onSrcPadAdded(TfStream *stream,
        GstPad *src, FsCodec *codec, FarsightChannel *self)
    {
        guint media_type;

        g_object_get(stream, "media-type", &media_type, NULL);

        GstPad *pad;
        GstElement *element = 0;

        switch (media_type) {
        case TP_MEDIA_STREAM_TYPE_AUDIO:
            element = self->audio_output_;
            g_object_ref(element);
            break;
        case TP_MEDIA_STREAM_TYPE_VIDEO:
            //element = self->video_output_->element();
            break;
        default:
            Q_ASSERT(false);
        }

        gst_bin_add(GST_BIN(self->pipeline_), element);

        pad = gst_element_get_static_pad(element, "sink");
        gst_element_set_state(element, GST_STATE_PLAYING);

        gst_pad_link(src, pad);

        self->status_ = StatusConnected;
        emit self->statusChanged(self->status_);
    }

    gboolean FarsightChannel::onRequestResource(TfStream *stream,
        guint direction, gpointer data)
    {
        LogInfo("CommunicationModule: resource request");
        return TRUE;
    }

} // end of namespace: TelepathyIM
<commit_msg>Fix for empty element names in QString to c char array conversion<commit_after>#include "StableHeaders.h"

#include "FarsightChannel.h"

#include <TelepathyQt4/Farsight/Channel>

namespace TelepathyIM
{
    FarsightChannel::FarsightChannel(const Tp::StreamedMediaChannelPtr &channel,
                                     const QString &audioSrc,
                                     const QString &audioSink,
                                     const QString &videoSrc)
                                     : QObject(0)
                                     // are these needed?
                                     //channel_(0), tf_channel_(0), bus_(0), pipeline_(0), audio_input_(0),
                                     //audio_output_(0), video_input_(0), video_tee_(0),
                                     //audio_volume_(0),
                                     //audio_resample_(0)
    {
        tf_channel_ = createFarsightChannel(channel);
        if (!tf_channel_) {
            LogError("Unable to construct TfChannel");
            return;
        }
        ConnectTfChannelEvents();

        //g_value_init (&volume_, G_TYPE_DOUBLE);
        pipeline_ = gst_pipeline_new(NULL);
        bus_ = gst_pipeline_get_bus(GST_PIPELINE(pipeline_));

        // create audioSrc, audioSink, videoSrc based on given vals
        audio_input_ = setUpElement(audioSrc);
        audio_output_ = setUpElement(audioSink);

        // audio modifications
        audio_resample_ = gst_element_factory_make("audioresample", NULL);
        //audio_volume_  = gst_element_factory_make("volume", NULL);

        audio_bin_ = gst_bin_new("audio-output-bin");

        gst_bin_add_many(GST_BIN(audio_bin_), audio_resample_, audio_output_, NULL);
        gst_element_link_many(audio_resample_, audio_output_, NULL);

        // add ghost pad to audio_bin_
        GstPad *sink = gst_element_get_static_pad(audio_resample_, "sink");
        audio_ghost_ = gst_ghost_pad_new("sink", sink);
        gst_element_add_pad(GST_ELEMENT(audio_bin_), audio_ghost_);
        gst_object_unref(G_OBJECT(sink));
        gst_object_ref(audio_bin_);
        gst_object_sink(audio_bin_);

        GstElement *video_src;

        if(videoSrc!=NULL) // If the videoSrc!=NULL we set up the pipeline with video preview elements
        {
            // create video elems,
            video_bin_ = gst_bin_new("video-input-bin");

            GstElement *scale = gst_element_factory_make("videoscale", NULL);
            GstElement *rate = gst_element_factory_make("videorate", NULL);
            GstElement *colorspace = gst_element_factory_make("ffmpegcolorspace", NULL);
            GstElement *capsfilter = gst_element_factory_make("capsfilter", NULL);
            GstCaps *caps = gst_caps_new_simple("video/x-raw-yuv",
                    "width", G_TYPE_INT, 320,
                    "height", G_TYPE_INT, 240,
                    NULL);
            g_object_set(G_OBJECT(capsfilter), "caps", caps, NULL);

            video_src = setUpElement(videoSrc);
            gst_bin_add_many(GST_BIN(video_bin_), video_src, scale, rate, colorspace, capsfilter, NULL);
            gst_element_link_many(video_src, scale, rate, colorspace, capsfilter, NULL);
            GstPad *src = gst_element_get_static_pad(capsfilter, "src");
            GstPad *ghost = gst_ghost_pad_new("src", src);
            Q_ASSERT(gst_element_add_pad(GST_ELEMENT(video_bin_), ghost));
            gst_object_unref(G_OBJECT(src));
            gst_object_ref(video_input_);
            gst_object_sink(video_input_);

            video_tee_ = setUpElement("tee");
            //video_preview_element_ = setUpElement("glimagesink");
            video_preview_element_ = setUpElement("autovideosink");
            gst_bin_add_many(GST_BIN(pipeline_), video_bin_, video_tee_,
                    video_preview_element_, NULL);
            gst_element_link_many(video_bin_, video_tee_,
                    video_preview_element_, NULL);

            video_remote_output_element_ = setUpElement("autovideosink");
        }
        // can empty pipeline be put to playing when video is not used?, lets try anyway
        gst_element_set_state(pipeline_, GST_STATE_PLAYING);
        status_ = StatusConnecting;
        emit statusChanged(status_);
    }

    FarsightChannel::~FarsightChannel()
    {
        if (tf_channel_) {
            g_object_unref(tf_channel_);
            tf_channel_ = 0;
        }
        if (bus_) {
            g_object_unref(bus_);
            bus_ = 0;
        }
        gst_element_set_state(pipeline_, GST_STATE_NULL);
        if (pipeline_) {
            g_object_unref(pipeline_);
            pipeline_ = 0;
        }
        if (audio_input_) {
            g_object_unref(audio_input_);
            audio_input_ = 0;
        }
        if (audio_output_) {
            g_object_unref(audio_output_);
            audio_output_ = 0;
        }
    }

    void FarsightChannel::ConnectTfChannelEvents()
    {
        /* Set up the telepathy farsight channel */
        g_signal_connect(tf_channel_, "closed", G_CALLBACK(&FarsightChannel::onClosed), this);
        g_signal_connect(tf_channel_, "session-created", G_CALLBACK(&FarsightChannel::onSessionCreated), this);
        g_signal_connect(tf_channel_, "stream-created", G_CALLBACK(&FarsightChannel::onStreamCreated), this);
    }

    GstElement* FarsightChannel::setUpElement(QString elemName)
    {
        std::string tempElemName = elemName.toStdString();
        const char* cStrElemName = tempElemName.c_str();
        GstElement* element = gst_element_factory_make(cStrElemName, NULL);
        gst_object_ref(element);
        gst_object_sink(element);
        return element;
    }

    FarsightChannel::Status FarsightChannel::GetStatus() const
    {
        return status_;
    }

    void FarsightChannel::SetAudioPlaybackVolume(const double value)
    {
        if(value<0||value>1){
            LogError("Trying to set volume out of range");
            return;
        }
        double setValue = value*10; // range is from 0 to 10
        //g_value_set_double(&volume_, setValue);
        //g_object_set_property (G_OBJECT(audio_volume_), "volume", &volume_);
    }

    void FarsightChannel::SetAudioRecordVolume(const double value)
    {
        if(value<0||value>1){
            LogError("Trying to set record volume out of range");
            return;
        }
        // todo: Implement
    }

    // Link bus events to tf_channel_
    gboolean FarsightChannel::busWatch(GstBus *bus, GstMessage *message, FarsightChannel *self)
    {
        try {
            if(self->tf_channel_ == NULL)
            {
                LogWarning("CommunicationModule: receiving bus message when tf_channel_ is NULL");
                return FALSE;
            }
            tf_channel_bus_message(self->tf_channel_, message);
            return TRUE;
        } catch(...){
            LogWarning("CommunicationModule: passing gstreamer bus message to telepathy-farsight failed");
            return FALSE;
        }
    }

    void FarsightChannel::onClosed(TfChannel *tfChannel,
        FarsightChannel *self)
    {
        self->status_ = StatusDisconnected;
        emit self->statusChanged(self->status_);
    }

    void FarsightChannel::onSessionCreated(TfChannel *tfChannel,
        FsConference *conference, FsParticipant *participant,
            FarsightChannel *self)
    {
        gst_bus_add_watch(self->bus_, (GstBusFunc) &FarsightChannel::busWatch, self);
        gst_bin_add(GST_BIN(self->pipeline_), GST_ELEMENT(conference));
        gst_element_set_state(GST_ELEMENT(conference), GST_STATE_PLAYING);
    }

    void FarsightChannel::onStreamCreated(TfChannel *tfChannel,
        TfStream *stream, FarsightChannel *self)
    {
        guint media_type;
        GstPad *sink;

        g_signal_connect(stream, "src-pad-added", G_CALLBACK(&FarsightChannel::onSrcPadAdded), self);
        g_signal_connect(stream, "request-resource", G_CALLBACK(&FarsightChannel::onRequestResource), NULL);

        g_object_get(stream, "media-type", &media_type, "sink-pad", &sink, NULL);

        GstPad *pad;

        switch (media_type) {
        case TP_MEDIA_STREAM_TYPE_AUDIO:
            gst_bin_add(GST_BIN(self->pipeline_), self->audio_input_);
            gst_element_set_state(self->audio_input_, GST_STATE_PLAYING);
            pad = gst_element_get_static_pad(self->audio_input_, "src");
            gst_pad_link(pad, sink);
            break;
        case TP_MEDIA_STREAM_TYPE_VIDEO:
            pad = gst_element_get_request_pad(self->video_tee_, "src%d");
            gst_pad_link(pad, sink);
            break;
        default:
            Q_ASSERT(false);
        }

        gst_object_unref(sink);
    }

    void FarsightChannel::onSrcPadAdded(TfStream *stream,
        GstPad *src, FsCodec *codec, FarsightChannel *self)
    {
        guint media_type;

        g_object_get(stream, "media-type", &media_type, NULL);

        GstPad *pad;
        GstElement *element = 0;

        switch (media_type) {
        case TP_MEDIA_STREAM_TYPE_AUDIO:
            element = self->audio_output_;
            g_object_ref(element);
            break;
        case TP_MEDIA_STREAM_TYPE_VIDEO:
            //element = self->video_output_->element();
            break;
        default:
            Q_ASSERT(false);
        }

        gst_bin_add(GST_BIN(self->pipeline_), element);

        pad = gst_element_get_static_pad(element, "sink");
        gst_element_set_state(element, GST_STATE_PLAYING);

        gst_pad_link(src, pad);

        self->status_ = StatusConnected;
        emit self->statusChanged(self->status_);
    }

    gboolean FarsightChannel::onRequestResource(TfStream *stream,
        guint direction, gpointer data)
    {
        LogInfo("CommunicationModule: resource request");
        return TRUE;
    }

} // end of namespace: TelepathyIM
<|endoftext|>


<commit_before><commit_msg>Fix eleven year old typo<commit_after><|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS warnings01 (1.8.8); FILE MERGED 2006/05/23 19:07:57 sb 1.8.8.4: RESYNC: (1.12-1.14); FILE MERGED 2006/04/07 18:38:44 sb 1.8.8.3: RESYNC: (1.11-1.12); FILE MERGED 2005/11/07 17:34:12 pl 1.8.8.2: RESYNC: (1.8-1.11); FILE MERGED 2005/11/07 12:02:44 ab 1.8.8.1: #i53898# Removed warnings<commit_after><|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkLevelWindowManager.h"
#include <itkCommand.h>
#include "mitkDataStorage.h"
#include "mitkNodePredicateBase.h"
#include "mitkNodePredicateProperty.h"
#include "mitkNodePredicateDataType.h"
#include "mitkNodePredicateAnd.h"
#include "mitkNodePredicateOr.h"
#include "mitkNodePredicateNot.h"
#include "mitkProperties.h"
#include "mitkMessage.h"

mitk::LevelWindowManager::LevelWindowManager()
: m_DataStorage(NULL)
, m_LevelWindowProperty(NULL)
, m_AutoTopMost(true)
, m_IsObserverTagSet(false)
, m_CurrentImage(NULL)
, m_IsPropertyModifiedTagSet(false)
{
}

mitk::LevelWindowManager::~LevelWindowManager()
{
  if (m_DataStorage.IsNotNull())
  {
    m_DataStorage->AddNodeEvent.RemoveListener(
        MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageAddedNode ));
    m_DataStorage->RemoveNodeEvent.RemoveListener(
        MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageRemovedNode ));
    m_DataStorage = NULL;
  }

  if (m_IsPropertyModifiedTagSet && m_LevelWindowProperty.IsNotNull())
  {
    m_LevelWindowProperty->RemoveObserver(m_PropertyModifiedTag);
    m_IsPropertyModifiedTagSet = false;
  }

  //clear both observer maps
  this->ClearPropObserverLists();
}

void mitk::LevelWindowManager::SetDataStorage( mitk::DataStorage* ds )
{
  if (ds == NULL) return;

  /* remove listeners of old DataStorage */
  if (m_DataStorage.IsNotNull())
  {
    m_DataStorage->AddNodeEvent.RemoveListener(
        MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageAddedNode ));
    m_DataStorage->RemoveNodeEvent.RemoveListener(
        MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageRemovedNode ));
  }

  /* register listener for new DataStorage */
  m_DataStorage = ds;  // register
  m_DataStorage->AddNodeEvent.AddListener(
      MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageAddedNode ));
  m_DataStorage->RemoveNodeEvent.AddListener(
      MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageRemovedNode ));

  this->DataStorageAddedNode(); // update us with new DataStorage
}

void mitk::LevelWindowManager::OnPropertyModified(const itk::EventObject& )
{
  Modified();
}

void mitk::LevelWindowManager::SetAutoTopMostImage(bool autoTopMost, const mitk::DataNode* removedNode)
{
  m_AutoTopMost = autoTopMost;
  if (m_AutoTopMost == false)
    return;

  if (m_IsPropertyModifiedTagSet && m_LevelWindowProperty.IsNotNull())
  {
    m_LevelWindowProperty->RemoveObserver(m_PropertyModifiedTag);
    m_IsPropertyModifiedTagSet = false;
  }

  /* search topmost image */
  if (m_DataStorage.IsNull())
  {
    itkExceptionMacro("DataStorage not set");
  }

  int maxLayer = itk::NumericTraits<int>::min();
  m_LevelWindowProperty = NULL;

  mitk::DataNode::Pointer topLevelNode;

  mitk::DataStorage::SetOfObjects::ConstPointer all = this->GetRelevantNodes();
  for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin(); it != all->End(); ++it)
  {
    mitk::DataNode::Pointer node = it->Value();
    if (node.IsNull() || (removedNode != NULL && node == removedNode))
      continue;

    node->SetBoolProperty( "imageForLevelWindow", false );

    if (node->IsVisible(NULL) == false)
      continue;

    int layer = 0;
    node->GetIntProperty("layer", layer);
    if ( layer < maxLayer )
      continue;

    mitk::LevelWindowProperty::Pointer levelWindowProperty = dynamic_cast<mitk::LevelWindowProperty*>(node->GetProperty("levelwindow"));
    if (levelWindowProperty.IsNull())
      continue;

    m_LevelWindowProperty = levelWindowProperty;
    m_CurrentImage = dynamic_cast<mitk::Image*>(node->GetData());
    topLevelNode = node;

    maxLayer = layer;
  }

  if (topLevelNode.IsNotNull())
  {
    topLevelNode->SetBoolProperty( "imageForLevelWindow", true );
  }

  this->SetLevelWindowProperty( m_LevelWindowProperty );

  if ( m_LevelWindowProperty.IsNull() )
  {
    Modified();
  }
  // else SetLevelWindowProperty will call Modified();
}

// sets an specific LevelWindowProperty, all changes will affect the image belonging to this property.
void mitk::LevelWindowManager::SetLevelWindowProperty(LevelWindowProperty::Pointer levelWindowProperty)
{
  if (levelWindowProperty.IsNull())
    return;

  if (m_IsPropertyModifiedTagSet)  // remove listener for old property
  {
    m_LevelWindowProperty->RemoveObserver(m_PropertyModifiedTag);
    m_IsPropertyModifiedTagSet = false;
  }

  m_LevelWindowProperty = levelWindowProperty;

  itk::ReceptorMemberCommand<LevelWindowManager>::Pointer command = itk::ReceptorMemberCommand<LevelWindowManager>::New();  // register listener for new property
  command->SetCallbackFunction(this, &LevelWindowManager::OnPropertyModified);
  m_PropertyModifiedTag = m_LevelWindowProperty->AddObserver( itk::ModifiedEvent(), command );
  m_IsPropertyModifiedTagSet = true;

  /* search image than belongs to the property */
  mitk::NodePredicateProperty::Pointer p = mitk::NodePredicateProperty::New("levelwindow", m_LevelWindowProperty);
  mitk::DataNode* n = m_DataStorage->GetNode(p);
  if (n == NULL)
  {
    mitkThrow() << "No Image in DataStorage that belongs to LevelWindow property" << m_LevelWindowProperty;
  }

  m_CurrentImage = dynamic_cast<mitk::Image*>(n->GetData());
  n->SetBoolProperty( "imageForLevelWindow", true );
  this->Modified();
}

// returns the current mitkLevelWindowProperty object from the image that is affected by changes
mitk::LevelWindowProperty::Pointer mitk::LevelWindowManager::GetLevelWindowProperty()
{
  return m_LevelWindowProperty;
}

// returns Level/Window values for the current image
const mitk::LevelWindow& mitk::LevelWindowManager::GetLevelWindow()
{
  if (m_LevelWindowProperty.IsNotNull())
  {
    return m_LevelWindowProperty->GetLevelWindow();
  }
  else
  {
    itkExceptionMacro("No LevelWindow available!");
  }
}

// sets new Level/Window values and informs all listeners about changes
void mitk::LevelWindowManager::SetLevelWindow(const mitk::LevelWindow& levelWindow)
{
  if (m_LevelWindowProperty.IsNotNull())
  {
    m_LevelWindowProperty->SetLevelWindow(levelWindow);
  }
  this->Modified();
}

void mitk::LevelWindowManager::DataStorageAddedNode( const mitk::DataNode* )
{
  //update observers with new data storage
  UpdateObservers();

  //check if everything is still ok
  if ((m_PropObserverToNode.size() != m_PropObserverToNode2.size()) || (m_PropObserverToNode2.size() != this->GetRelevantNodes()->size()))
     {mitkThrow() << "Wrong number of observers in Level Window Manager!";}
}

void mitk::LevelWindowManager::DataStorageRemovedNode( const mitk::DataNode* removedNode )
{
  //first: check if deleted node is part of relevant nodes. If not, abort method because there is no need change anything.
  if ((this->GetRelevantNodes()->size() == 0)) return;
  bool removedNodeIsRelevant = false;
  /* Iterator code: is crashing, don't know why... so using for loop
  for (mitk::DataStorage::SetOfObjects::ConstIterator it = this->GetRelevantNodes()->Begin();
       it != this->GetRelevantNodes()->End();
       ++it)
  {if (it->Value() == removedNode) {removedNodeIsRelevant=true;}}*/
  for (int i=0; i<this->GetRelevantNodes()->size(); i++)
    {
    if (this->GetRelevantNodes()->at(i) == removedNode) {removedNodeIsRelevant=true;}
    }
  if (!removedNodeIsRelevant) return;

  //remember node which will be removed
  m_NodeMarkedToDelete = removedNode;

  //update observers
  UpdateObservers();

  /* search image than belongs to the property */
  if (m_LevelWindowProperty.IsNull())
  {
    SetAutoTopMostImage(true, removedNode);
  }
  else
  {
    mitk::NodePredicateProperty::Pointer p2 = mitk::NodePredicateProperty::New("levelwindow", m_LevelWindowProperty);
    mitk::DataNode* n = m_DataStorage->GetNode(p2);
    if (n == NULL || m_AutoTopMost) // if node was deleted, change our behaviour to AutoTopMost, if AutoTopMost is true change level window to topmost node
    {
      SetAutoTopMostImage(true, removedNode);
    }
  }

  //reset variable
  m_NodeMarkedToDelete = NULL;

  //check if everything is still ok
  if ((m_PropObserverToNode.size() != m_PropObserverToNode2.size()) || (m_PropObserverToNode2.size() != (this->GetRelevantNodes()->size()-1)))
     {mitkThrow() << "Wrong number of observers in Level Window Manager!";}
}

void mitk::LevelWindowManager::UpdateObservers()
{
  this->ClearPropObserverLists(); //remove old observers
  CreatePropObserverLists(); //create new observer lists

}

int mitk::LevelWindowManager::GetNumberOfObservers()
{
  return m_PropObserverToNode.size();
}

mitk::DataStorage* mitk::LevelWindowManager::GetDataStorage()
{
  return m_DataStorage.GetPointer();
}

// true if changes on slider or line-edits will affect always the topmost layer image
bool mitk::LevelWindowManager::isAutoTopMost()
{
  return m_AutoTopMost;
}

void mitk::LevelWindowManager::Update(const itk::EventObject&)  // visible property of a image has changed
{
  if (m_AutoTopMost)
  {
    SetAutoTopMostImage(true);
    return;
  }
  mitk::DataStorage::SetOfObjects::ConstPointer all = this->GetRelevantNodes();
  for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin();
       it != all->End();
       ++it)
  {
    mitk::DataNode::Pointer node = it->Value();
    if (node.IsNull())
      continue;

    node->SetBoolProperty( "imageForLevelWindow", false );

    if (node->IsVisible(NULL) == false)
      continue;

    mitk::LevelWindowProperty::Pointer levelWindowProperty = dynamic_cast<mitk::LevelWindowProperty*>(node->GetProperty("levelwindow"));
    if (levelWindowProperty.IsNull())
      continue;

    m_LevelWindowProperty = levelWindowProperty;
    m_CurrentImage = dynamic_cast<mitk::Image*>(node->GetData());
    node->SetBoolProperty( "imageForLevelWindow", true );
    if (m_LevelWindowProperty.IsNull() && m_LevelWindowProperty.GetPointer() == levelWindowProperty) // we found our m_LevelWindowProperty
    {
      return;
    }
  }
  Modified();
}

mitk::DataStorage::SetOfObjects::ConstPointer mitk::LevelWindowManager::GetRelevantNodes()
{
  if (m_DataStorage.IsNull())
    return mitk::DataStorage::SetOfObjects::ConstPointer(mitk::DataStorage::SetOfObjects::New());  // return empty set

  mitk::BoolProperty::Pointer trueProp = mitk::BoolProperty::New(true);
  mitk::NodePredicateProperty::Pointer notBinary = mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(false));
  mitk::NodePredicateProperty::Pointer hasLevelWindow = mitk::NodePredicateProperty::New("levelwindow", NULL);

  mitk::NodePredicateDataType::Pointer isImage = mitk::NodePredicateDataType::New("Image");
  mitk::NodePredicateDataType::Pointer isDImage = mitk::NodePredicateDataType::New("DiffusionImage");
  mitk::NodePredicateDataType::Pointer isTImage = mitk::NodePredicateDataType::New("TensorImage");
  mitk::NodePredicateDataType::Pointer isQImage = mitk::NodePredicateDataType::New("QBallImage");
  mitk::NodePredicateOr::Pointer predicateTypes = mitk::NodePredicateOr::New();
  predicateTypes->AddPredicate(isImage);
  predicateTypes->AddPredicate(isDImage);
  predicateTypes->AddPredicate(isTImage);
  predicateTypes->AddPredicate(isQImage);

  mitk::NodePredicateAnd::Pointer predicate = mitk::NodePredicateAnd::New();
  predicate->AddPredicate(notBinary);
  predicate->AddPredicate(hasLevelWindow);
  predicate->AddPredicate(predicateTypes);

  mitk::DataStorage::SetOfObjects::ConstPointer relevantNodes = m_DataStorage->GetSubset( predicate );

  return relevantNodes;
}

mitk::Image* mitk::LevelWindowManager::GetCurrentImage()
{
  return m_CurrentImage;
}

void mitk::LevelWindowManager::ClearPropObserverLists()
{
for( ObserverToPropertyMap::iterator iter = m_PropObserverToNode.begin();
       iter != m_PropObserverToNode.end();
       ++iter )
  {
    (*iter).second->RemoveObserver((*iter).first.first);
    (*iter).second = 0;
  }
  m_PropObserverToNode.clear();

  for( ObserverToPropertyMap::iterator iter = m_PropObserverToNode2.begin();
       iter != m_PropObserverToNode2.end();
       ++iter )
  {
    (*iter).second->RemoveObserver((*iter).first.first);
    (*iter).second = 0;
  }
  m_PropObserverToNode2.clear();
}

void mitk::LevelWindowManager::CreatePropObserverLists()
{
  if (m_DataStorage.IsNull())     //check if data storage is set
    {itkExceptionMacro("DataStorage not set");}

  /* add observers for all relevant nodes */
  mitk::DataStorage::SetOfObjects::ConstPointer all = this->GetRelevantNodes();
  for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin();
       it != all->End();
       ++it)
  {
    if ((it->Value().IsNull()) || (it->Value() == m_NodeMarkedToDelete))
      {continue;}

    /* register listener for changes in visible property */
    itk::ReceptorMemberCommand<LevelWindowManager>::Pointer command = itk::ReceptorMemberCommand<LevelWindowManager>::New();
    command->SetCallbackFunction(this, &LevelWindowManager::Update);
    unsigned long idx = it->Value()->GetProperty("visible")->AddObserver( itk::ModifiedEvent(), command );
    m_PropObserverToNode[PropDataPair(idx, it->Value())] = it->Value()->GetProperty("visible");
  }

  /* add observers for all layer properties*/
  for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin();
       it != all->End();
       ++it)
  {
    if ((it->Value().IsNull()) || (it->Value() == m_NodeMarkedToDelete))
      {continue;}
    /* register listener for changes in layer property */
    itk::ReceptorMemberCommand<LevelWindowManager>::Pointer command2 = itk::ReceptorMemberCommand<LevelWindowManager>::New();
    command2->SetCallbackFunction(this, &LevelWindowManager::Update);
    unsigned long idx = it->Value()->GetProperty("layer")->AddObserver( itk::ModifiedEvent(), command2 );
    m_PropObserverToNode2[PropDataPair(idx, it->Value())] = it->Value()->GetProperty("layer");
  }

}
<commit_msg>fixed a bug: Initialized the LevelWindowManager also in the AddNode method<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkLevelWindowManager.h"
#include <itkCommand.h>
#include "mitkDataStorage.h"
#include "mitkNodePredicateBase.h"
#include "mitkNodePredicateProperty.h"
#include "mitkNodePredicateDataType.h"
#include "mitkNodePredicateAnd.h"
#include "mitkNodePredicateOr.h"
#include "mitkNodePredicateNot.h"
#include "mitkProperties.h"
#include "mitkMessage.h"

mitk::LevelWindowManager::LevelWindowManager()
: m_DataStorage(NULL)
, m_LevelWindowProperty(NULL)
, m_AutoTopMost(true)
, m_IsObserverTagSet(false)
, m_CurrentImage(NULL)
, m_IsPropertyModifiedTagSet(false)
{
}

mitk::LevelWindowManager::~LevelWindowManager()
{
  if (m_DataStorage.IsNotNull())
  {
    m_DataStorage->AddNodeEvent.RemoveListener(
        MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageAddedNode ));
    m_DataStorage->RemoveNodeEvent.RemoveListener(
        MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageRemovedNode ));
    m_DataStorage = NULL;
  }

  if (m_IsPropertyModifiedTagSet && m_LevelWindowProperty.IsNotNull())
  {
    m_LevelWindowProperty->RemoveObserver(m_PropertyModifiedTag);
    m_IsPropertyModifiedTagSet = false;
  }

  //clear both observer maps
  this->ClearPropObserverLists();
}

void mitk::LevelWindowManager::SetDataStorage( mitk::DataStorage* ds )
{
  if (ds == NULL) return;

  /* remove listeners of old DataStorage */
  if (m_DataStorage.IsNotNull())
  {
    m_DataStorage->AddNodeEvent.RemoveListener(
        MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageAddedNode ));
    m_DataStorage->RemoveNodeEvent.RemoveListener(
        MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageRemovedNode ));
  }

  /* register listener for new DataStorage */
  m_DataStorage = ds;  // register
  m_DataStorage->AddNodeEvent.AddListener(
      MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageAddedNode ));
  m_DataStorage->RemoveNodeEvent.AddListener(
      MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageRemovedNode ));

  this->DataStorageAddedNode(); // update us with new DataStorage
}

void mitk::LevelWindowManager::OnPropertyModified(const itk::EventObject& )
{
  Modified();
}

void mitk::LevelWindowManager::SetAutoTopMostImage(bool autoTopMost, const mitk::DataNode* removedNode)
{
  m_AutoTopMost = autoTopMost;
  if (m_AutoTopMost == false)
    return;

  if (m_IsPropertyModifiedTagSet && m_LevelWindowProperty.IsNotNull())
  {
    m_LevelWindowProperty->RemoveObserver(m_PropertyModifiedTag);
    m_IsPropertyModifiedTagSet = false;
  }

  /* search topmost image */
  if (m_DataStorage.IsNull())
  {
    itkExceptionMacro("DataStorage not set");
  }

  int maxLayer = itk::NumericTraits<int>::min();
  m_LevelWindowProperty = NULL;

  mitk::DataNode::Pointer topLevelNode;

  mitk::DataStorage::SetOfObjects::ConstPointer all = this->GetRelevantNodes();
  for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin(); it != all->End(); ++it)
  {
    mitk::DataNode::Pointer node = it->Value();
    if (node.IsNull() || (removedNode != NULL && node == removedNode))
      continue;

    node->SetBoolProperty( "imageForLevelWindow", false );

    if (node->IsVisible(NULL) == false)
      continue;

    int layer = 0;
    node->GetIntProperty("layer", layer);
    if ( layer < maxLayer )
      continue;

    mitk::LevelWindowProperty::Pointer levelWindowProperty = dynamic_cast<mitk::LevelWindowProperty*>(node->GetProperty("levelwindow"));
    if (levelWindowProperty.IsNull())
      continue;

    m_LevelWindowProperty = levelWindowProperty;
    m_CurrentImage = dynamic_cast<mitk::Image*>(node->GetData());
    topLevelNode = node;

    maxLayer = layer;
  }

  if (topLevelNode.IsNotNull())
  {
    topLevelNode->SetBoolProperty( "imageForLevelWindow", true );
  }

  this->SetLevelWindowProperty( m_LevelWindowProperty );

  if ( m_LevelWindowProperty.IsNull() )
  {
    Modified();
  }
  // else SetLevelWindowProperty will call Modified();
}

// sets an specific LevelWindowProperty, all changes will affect the image belonging to this property.
void mitk::LevelWindowManager::SetLevelWindowProperty(LevelWindowProperty::Pointer levelWindowProperty)
{
  if (levelWindowProperty.IsNull())
    return;

  if (m_IsPropertyModifiedTagSet)  // remove listener for old property
  {
    m_LevelWindowProperty->RemoveObserver(m_PropertyModifiedTag);
    m_IsPropertyModifiedTagSet = false;
  }

  m_LevelWindowProperty = levelWindowProperty;

  itk::ReceptorMemberCommand<LevelWindowManager>::Pointer command = itk::ReceptorMemberCommand<LevelWindowManager>::New();  // register listener for new property
  command->SetCallbackFunction(this, &LevelWindowManager::OnPropertyModified);
  m_PropertyModifiedTag = m_LevelWindowProperty->AddObserver( itk::ModifiedEvent(), command );
  m_IsPropertyModifiedTagSet = true;

  /* search image than belongs to the property */
  mitk::NodePredicateProperty::Pointer p = mitk::NodePredicateProperty::New("levelwindow", m_LevelWindowProperty);
  mitk::DataNode* n = m_DataStorage->GetNode(p);
  if (n == NULL)
  {
    mitkThrow() << "No Image in DataStorage that belongs to LevelWindow property" << m_LevelWindowProperty;
  }

  m_CurrentImage = dynamic_cast<mitk::Image*>(n->GetData());
  n->SetBoolProperty( "imageForLevelWindow", true );
  this->Modified();
}

// returns the current mitkLevelWindowProperty object from the image that is affected by changes
mitk::LevelWindowProperty::Pointer mitk::LevelWindowManager::GetLevelWindowProperty()
{
  return m_LevelWindowProperty;
}

// returns Level/Window values for the current image
const mitk::LevelWindow& mitk::LevelWindowManager::GetLevelWindow()
{
  if (m_LevelWindowProperty.IsNotNull())
  {
    return m_LevelWindowProperty->GetLevelWindow();
  }
  else
  {
    itkExceptionMacro("No LevelWindow available!");
  }
}

// sets new Level/Window values and informs all listeners about changes
void mitk::LevelWindowManager::SetLevelWindow(const mitk::LevelWindow& levelWindow)
{
  if (m_LevelWindowProperty.IsNotNull())
  {
    m_LevelWindowProperty->SetLevelWindow(levelWindow);
  }
  this->Modified();
}

void mitk::LevelWindowManager::DataStorageAddedNode( const mitk::DataNode* )
{

  //update observers with new data storage
  UpdateObservers();

  //Initialize LevelWindowsManager to new image
  SetAutoTopMostImage(true, NULL);

  //check if everything is still ok
  if ((m_PropObserverToNode.size() != m_PropObserverToNode2.size()) || (m_PropObserverToNode2.size() != this->GetRelevantNodes()->size()))
     {mitkThrow() << "Wrong number of observers in Level Window Manager!";}

}

void mitk::LevelWindowManager::DataStorageRemovedNode( const mitk::DataNode* removedNode )
{
  //first: check if deleted node is part of relevant nodes. If not, abort method because there is no need change anything.
  if ((this->GetRelevantNodes()->size() == 0)) return;
  bool removedNodeIsRelevant = false;
  /* Iterator code: is crashing, don't know why... so using for loop
  for (mitk::DataStorage::SetOfObjects::ConstIterator it = this->GetRelevantNodes()->Begin();
       it != this->GetRelevantNodes()->End();
       ++it)
  {if (it->Value() == removedNode) {removedNodeIsRelevant=true;}}*/
  for (unsigned int i=0; i<this->GetRelevantNodes()->size(); i++)
    {
    if (this->GetRelevantNodes()->at(i) == removedNode) {removedNodeIsRelevant=true;}
    }
  if (!removedNodeIsRelevant) return;

  //remember node which will be removed
  m_NodeMarkedToDelete = removedNode;

  //update observers
  UpdateObservers();

  /* search image than belongs to the property */
  if (m_LevelWindowProperty.IsNull())
  {
    SetAutoTopMostImage(true, removedNode);
  }
  else
  {
    mitk::NodePredicateProperty::Pointer p2 = mitk::NodePredicateProperty::New("levelwindow", m_LevelWindowProperty);
    mitk::DataNode* n = m_DataStorage->GetNode(p2);
    if (n == NULL || m_AutoTopMost) // if node was deleted, change our behaviour to AutoTopMost, if AutoTopMost is true change level window to topmost node
    {
      SetAutoTopMostImage(true, removedNode);
    }
  }

  //reset variable
  m_NodeMarkedToDelete = NULL;

  //check if everything is still ok
  if ((m_PropObserverToNode.size() != m_PropObserverToNode2.size()) || (m_PropObserverToNode2.size() != (this->GetRelevantNodes()->size()-1)))
     {mitkThrow() << "Wrong number of observers in Level Window Manager!";}
}

void mitk::LevelWindowManager::UpdateObservers()
{
  this->ClearPropObserverLists(); //remove old observers
  CreatePropObserverLists(); //create new observer lists

}

int mitk::LevelWindowManager::GetNumberOfObservers()
{
  return m_PropObserverToNode.size();
}

mitk::DataStorage* mitk::LevelWindowManager::GetDataStorage()
{
  return m_DataStorage.GetPointer();
}

// true if changes on slider or line-edits will affect always the topmost layer image
bool mitk::LevelWindowManager::isAutoTopMost()
{
  return m_AutoTopMost;
}

void mitk::LevelWindowManager::Update(const itk::EventObject&)  // visible property of a image has changed
{
  if (m_AutoTopMost)
  {
    SetAutoTopMostImage(true);
    return;
  }
  mitk::DataStorage::SetOfObjects::ConstPointer all = this->GetRelevantNodes();
  for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin();
       it != all->End();
       ++it)
  {
    mitk::DataNode::Pointer node = it->Value();
    if (node.IsNull())
      continue;

    node->SetBoolProperty( "imageForLevelWindow", false );

    if (node->IsVisible(NULL) == false)
      continue;

    mitk::LevelWindowProperty::Pointer levelWindowProperty = dynamic_cast<mitk::LevelWindowProperty*>(node->GetProperty("levelwindow"));
    if (levelWindowProperty.IsNull())
      continue;

    m_LevelWindowProperty = levelWindowProperty;
    m_CurrentImage = dynamic_cast<mitk::Image*>(node->GetData());
    node->SetBoolProperty( "imageForLevelWindow", true );
    if (m_LevelWindowProperty.IsNull() && m_LevelWindowProperty.GetPointer() == levelWindowProperty) // we found our m_LevelWindowProperty
    {
      return;
    }
  }
  Modified();
}

mitk::DataStorage::SetOfObjects::ConstPointer mitk::LevelWindowManager::GetRelevantNodes()
{
  if (m_DataStorage.IsNull())
    return mitk::DataStorage::SetOfObjects::ConstPointer(mitk::DataStorage::SetOfObjects::New());  // return empty set

  mitk::BoolProperty::Pointer trueProp = mitk::BoolProperty::New(true);
  mitk::NodePredicateProperty::Pointer notBinary = mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(false));
  mitk::NodePredicateProperty::Pointer hasLevelWindow = mitk::NodePredicateProperty::New("levelwindow", NULL);

  mitk::NodePredicateDataType::Pointer isImage = mitk::NodePredicateDataType::New("Image");
  mitk::NodePredicateDataType::Pointer isDImage = mitk::NodePredicateDataType::New("DiffusionImage");
  mitk::NodePredicateDataType::Pointer isTImage = mitk::NodePredicateDataType::New("TensorImage");
  mitk::NodePredicateDataType::Pointer isQImage = mitk::NodePredicateDataType::New("QBallImage");
  mitk::NodePredicateOr::Pointer predicateTypes = mitk::NodePredicateOr::New();
  predicateTypes->AddPredicate(isImage);
  predicateTypes->AddPredicate(isDImage);
  predicateTypes->AddPredicate(isTImage);
  predicateTypes->AddPredicate(isQImage);

  mitk::NodePredicateAnd::Pointer predicate = mitk::NodePredicateAnd::New();
  predicate->AddPredicate(notBinary);
  predicate->AddPredicate(hasLevelWindow);
  predicate->AddPredicate(predicateTypes);

  mitk::DataStorage::SetOfObjects::ConstPointer relevantNodes = m_DataStorage->GetSubset( predicate );

  return relevantNodes;
}

mitk::Image* mitk::LevelWindowManager::GetCurrentImage()
{
  return m_CurrentImage;
}

void mitk::LevelWindowManager::ClearPropObserverLists()
{
for( ObserverToPropertyMap::iterator iter = m_PropObserverToNode.begin();
       iter != m_PropObserverToNode.end();
       ++iter )
  {
    (*iter).second->RemoveObserver((*iter).first.first);
    (*iter).second = 0;
  }
  m_PropObserverToNode.clear();

  for( ObserverToPropertyMap::iterator iter = m_PropObserverToNode2.begin();
       iter != m_PropObserverToNode2.end();
       ++iter )
  {
    (*iter).second->RemoveObserver((*iter).first.first);
    (*iter).second = 0;
  }
  m_PropObserverToNode2.clear();
}

void mitk::LevelWindowManager::CreatePropObserverLists()
{
  if (m_DataStorage.IsNull())     //check if data storage is set
    {itkExceptionMacro("DataStorage not set");}

  /* add observers for all relevant nodes */
  mitk::DataStorage::SetOfObjects::ConstPointer all = this->GetRelevantNodes();
  for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin();
       it != all->End();
       ++it)
  {
    if ((it->Value().IsNull()) || (it->Value() == m_NodeMarkedToDelete))
      {continue;}

    /* register listener for changes in visible property */
    itk::ReceptorMemberCommand<LevelWindowManager>::Pointer command = itk::ReceptorMemberCommand<LevelWindowManager>::New();
    command->SetCallbackFunction(this, &LevelWindowManager::Update);
    unsigned long idx = it->Value()->GetProperty("visible")->AddObserver( itk::ModifiedEvent(), command );
    m_PropObserverToNode[PropDataPair(idx, it->Value())] = it->Value()->GetProperty("visible");
  }

  /* add observers for all layer properties*/
  for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin();
       it != all->End();
       ++it)
  {
    if ((it->Value().IsNull()) || (it->Value() == m_NodeMarkedToDelete))
      {continue;}
    /* register listener for changes in layer property */
    itk::ReceptorMemberCommand<LevelWindowManager>::Pointer command2 = itk::ReceptorMemberCommand<LevelWindowManager>::New();
    command2->SetCallbackFunction(this, &LevelWindowManager::Update);
    unsigned long idx = it->Value()->GetProperty("layer")->AddObserver( itk::ModifiedEvent(), command2 );
    m_PropObserverToNode2[PropDataPair(idx, it->Value())] = it->Value()->GetProperty("layer");
  }

}
<|endoftext|>