<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $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 Technology Preview License Agreement accompanying
** this package.
**
** 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.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qsensormanager.h"
#include <QDebug>
#include "qsensorpluginloader_p.h"
#include "qsensorplugin.h"
#include <QSettings>
#include "sensorlog_p.h"
#include <QTimer>

QTM_BEGIN_NAMESPACE

Q_GLOBAL_STATIC(QSensorPluginLoader, pluginLoader)

typedef QHash<QByteArray,QSensorBackendFactory*> FactoryForIdentifierMap;
typedef QHash<QByteArray,FactoryForIdentifierMap> BackendIdentifiersForTypeMap;

class QSensorManagerPrivate : public QObject
{
    friend class QSensorManager;

    Q_OBJECT
public:
    QSensorManagerPrivate()
        : pluginsLoaded(false)
        , sensorsChanged(false)
    {
    }

    bool pluginsLoaded;

    QList<CreatePluginFunc> staticRegistrations;

    // Holds a mapping from type to available identifiers (and from there to the factory)
    BackendIdentifiersForTypeMap backendsByType;

    // Holds the first identifier for each type
    QHash<QByteArray, QByteArray> firstIdentifierForType;

    bool sensorsChanged;
    QList<QSensorChangesInterface*> changeListeners;

Q_SIGNALS:
    void availableSensorsChanged();

public Q_SLOTS:
    void emitSensorsChanged()
    {
        static bool alreadyRunning = false;
        if (!pluginsLoaded || alreadyRunning) {
            // We're busy.
            // Just note that a registration changed and exit.
            // Someone up the call stack will deal with this.
            sensorsChanged = true;
            return;
        }

        // Set a flag so any recursive calls doesn't cause a loop.
        alreadyRunning = true;

        // Since one [un]registration may cause other [un]registrations and since
        // the order in which we do things matters we just do a cascading update
        // until things stop changing.
        do {
            sensorsChanged = false;
            Q_FOREACH (QSensorChangesInterface *changes, changeListeners) {
                changes->sensorsChanged();
            }
        } while (sensorsChanged);

        // We're going away now so clear the flag
        alreadyRunning = false;

        // Notify the client of the changes
        Q_EMIT availableSensorsChanged();
    }
};

Q_GLOBAL_STATIC(QSensorManagerPrivate, sensorManagerPrivate)

// The unit test needs to change the behaviour of the library. It does this
// through an exported but undocumented function.
static void initPlugin(QObject *plugin);
static bool settings_use_user_scope = false;
static bool load_external_plugins = true;
Q_SENSORS_EXPORT void sensors_unit_test_hook(int index)
{
    QSensorManagerPrivate *d = sensorManagerPrivate();

    switch (index) {
    case 0:
        Q_ASSERT(d->pluginsLoaded == false);
        settings_use_user_scope = true;
        load_external_plugins = false;
        break;
    case 1:
        Q_ASSERT(load_external_plugins == false);
        Q_ASSERT(d->pluginsLoaded == true);
        SENSORLOG() << "initializing plugins";
        Q_FOREACH (QObject *plugin, pluginLoader()->plugins()) {
            initPlugin(plugin);
        }
        break;
    default:
        break;
    }
}

static void initPlugin(QObject *o)
{
    if (!o) return;
    QSensorManagerPrivate *d = sensorManagerPrivate();

    QSensorPluginInterface *plugin = qobject_cast<QSensorPluginInterface*>(o);
    if (plugin)
        plugin->registerSensors();
    QSensorChangesInterface *changes = qobject_cast<QSensorChangesInterface*>(o);
    if (changes)
        d->changeListeners << changes;
}

static void loadPlugins()
{
    QSensorManagerPrivate *d = sensorManagerPrivate();
    d->pluginsLoaded = true;

    SENSORLOG() << "initializing static plugins";
    Q_FOREACH (CreatePluginFunc func, d->staticRegistrations) {
        QSensorPluginInterface *plugin = func();
        plugin->registerSensors();
    }

    if (load_external_plugins) {
        SENSORLOG() << "initializing plugins";
        Q_FOREACH (QObject *plugin, pluginLoader()->plugins()) {
            initPlugin(plugin);
        }
    }

    if (d->sensorsChanged) {
        // Notify the app that the available sensor list has changed.
        // This may cause recursive calls!
        d->emitSensorsChanged();
    }
}

// =====================================================================

/*!
    \class QSensorManager
    \ingroup sensors_backend
    \inmodule QtSensors

    \brief The QSensorManager class handles registration and creation of sensor backends.

    Sensor plugins register backends using the registerBackend() function.

    When QSensor::connectToBackend() is called, the createBackend() function will be called.
*/

/*!
    Register a sensor for \a type. The \a identifier must be unique.

    The \a factory will be asked to create instances of the backend.
*/
void QSensorManager::registerBackend(const QByteArray &type, const QByteArray &identifier, QSensorBackendFactory *factory)
{
    QSensorManagerPrivate *d = sensorManagerPrivate();
    if (!d->backendsByType.contains(type)) {
        (void)d->backendsByType[type];
        d->firstIdentifierForType[type] = identifier;
    } else if (d->firstIdentifierForType[type].startsWith("generic.")) {
        // Don't let a generic backend be the default when some other backend exists!
        d->firstIdentifierForType[type] = identifier;
    }
    FactoryForIdentifierMap &factoryByIdentifier = d->backendsByType[type];
    if (factoryByIdentifier.contains(identifier)) {
        qWarning() << "A backend with type" << type << "and identifier" << identifier << "has already been registered!";
        return;
    }
    SENSORLOG() << "registering backend for type" << type << "identifier" << identifier;// << "factory" << QString().sprintf("0x%08x", (unsigned int)factory);
    factoryByIdentifier[identifier] = factory;

    // Notify the app that the available sensor list has changed.
    // This may cause recursive calls!
    d->emitSensorsChanged();
}

/*!
    Unregister the backend for \a type with \a identifier.

    Note that this only prevents new instance of the backend from being created. It does not
    invalidate the existing instances of the backend. The backend code should handle the
    disappearance of the underlying hardware itself.
*/
void QSensorManager::unregisterBackend(const QByteArray &type, const QByteArray &identifier)
{
    QSensorManagerPrivate *d = sensorManagerPrivate();
    if (!d->backendsByType.contains(type)) {
        qWarning() << "No backends of type" << type << "are registered";
        return;
    }
    FactoryForIdentifierMap &factoryByIdentifier = d->backendsByType[type];
    if (!factoryByIdentifier.contains(identifier)) {
        qWarning() << "Identifier" << identifier << "is not registered";
        return;
    }

    (void)factoryByIdentifier.take(identifier); // we don't own this pointer anyway
    if (d->firstIdentifierForType[type] == identifier) {
        if (factoryByIdentifier.count()) {
            d->firstIdentifierForType[type] = factoryByIdentifier.begin().key();
            if (d->firstIdentifierForType[type].startsWith("generic.")) {
                // Don't let a generic backend be the default when some other backend exists!
                for (FactoryForIdentifierMap::const_iterator it = factoryByIdentifier.begin()++; it != factoryByIdentifier.end(); it++) {
                    const QByteArray &identifier(it.key());
                    if (!identifier.startsWith("generic.")) {
                        d->firstIdentifierForType[type] = identifier;
                        break;
                    }
                }
            }
        } else {
            (void)d->firstIdentifierForType.take(type);
        }
    }
    if (!factoryByIdentifier.count())
        (void)d->backendsByType.take(type);

    // Notify the app that the available sensor list has changed.
    // This may cause recursive calls!
    d->emitSensorsChanged();
}

/*!
    \internal
*/
void QSensorManager::registerStaticPlugin(CreatePluginFunc func)
{
    QSensorManagerPrivate *d = sensorManagerPrivate();
    d->staticRegistrations.append(func);
}

/*!
    Create a backend for \a sensor. Returns null if no suitable backend exists.
*/
QSensorBackend *QSensorManager::createBackend(QSensor *sensor)
{
    Q_ASSERT(sensor);

    QSensorManagerPrivate *d = sensorManagerPrivate();
    if (!d->pluginsLoaded)
        loadPlugins();

    SENSORLOG() << "QSensorManager::createBackend" << "type" << sensor->type() << "identifier" << sensor->identifier();

    if (!d->backendsByType.contains(sensor->type())) {
        SENSORLOG() << "no backends of type" << sensor->type() << "have been registered.";
        return 0;
    }

    const FactoryForIdentifierMap &factoryByIdentifier = d->backendsByType[sensor->type()];
    QSensorBackendFactory *factory;
    QSensorBackend *backend;

    if (sensor->identifier().isEmpty()) {
        QByteArray defaultIdentifier = QSensor::defaultSensorForType(sensor->type());
        SENSORLOG() << "Trying the default" << defaultIdentifier;
        // No identifier set, try the default
        factory = factoryByIdentifier[defaultIdentifier];
        //SENSORLOG() << "factory" << QString().sprintf("0x%08x", (unsigned int)factory);
        sensor->setIdentifier(defaultIdentifier); // the factory requires this
        backend = factory->createBackend(sensor);
        if (backend) return backend; // Got it!

        // The default failed to instantiate so try any other registered sensors for this type
        Q_FOREACH (const QByteArray &identifier, factoryByIdentifier.keys()) {
            SENSORLOG() << "Trying" << identifier;
            if (identifier == defaultIdentifier) continue; // Don't do the default one again
            factory = factoryByIdentifier[identifier];
            //SENSORLOG() << "factory" << QString().sprintf("0x%08x", (unsigned int)factory);
            sensor->setIdentifier(identifier); // the factory requires this
            backend = factory->createBackend(sensor);
            if (backend) return backend; // Got it!
        }
        SENSORLOG() << "FAILED";
        sensor->setIdentifier(QByteArray()); // clear the identifier
    } else {
        if (!factoryByIdentifier.contains(sensor->identifier())) {
            SENSORLOG() << "no backend with identifier" << sensor->identifier() << "for type" << sensor->type();
            return 0;
        }

        // We were given an explicit identifier so don't substitute other backends if it fails to instantiate
        factory = factoryByIdentifier[sensor->identifier()];
        //SENSORLOG() << "factory" << QString().sprintf("0x%08x", (unsigned int)factory);
        backend = factory->createBackend(sensor);
        if (backend) return backend; // Got it!
    }

    SENSORLOG() << "no suitable backend found for requested identifier" << sensor->identifier() << "and type" << sensor->type();
    return 0;
}

/*!
    Returns true if the backend identified by \a type and \a identifier is registered.

    This is a convenience method that helps out plugins doing dynamic registration.
*/
bool QSensorManager::isBackendRegistered(const QByteArray &type, const QByteArray &identifier)
{
    QSensorManagerPrivate *d = sensorManagerPrivate();
    if (!d->pluginsLoaded)
        loadPlugins();

    if (!d->backendsByType.contains(type))
        return false;

    const FactoryForIdentifierMap &factoryByIdentifier = d->backendsByType[type];
    if (!factoryByIdentifier.contains(identifier))
        return false;

    return true;
}

// =====================================================================

/*!
    Returns a list of all sensor types.
*/
QList<QByteArray> QSensor::sensorTypes()
{
    QSensorManagerPrivate *d = sensorManagerPrivate();
    if (!d->pluginsLoaded)
        loadPlugins();

    return d->backendsByType.keys();
}

/*!
    Returns a list of ids for each of the sensors for \a type.
    If there are no sensors of that type available the list will be empty.
*/
QList<QByteArray> QSensor::sensorsForType(const QByteArray &type)
{
    QSensorManagerPrivate *d = sensorManagerPrivate();
    if (!d->pluginsLoaded)
        loadPlugins();

    // no sensors of that type exist
    if (!d->backendsByType.contains(type))
        return QList<QByteArray>();

    return d->backendsByType[type].keys();
}

/*!
    Returns the default sensor identifier for \a type.
    This is set in a config file and can be overridden if required.
    If no default is available the system will return the first registered
    sensor for \a type.

    Note that there is special case logic to prevent the generic plugin's backends from becoming the
    default when another backend is registered for the same type. This logic means that a backend
    identifier starting with \c{generic.} will only be the default if no other backends have been
    registered for that type or if it is specified in \c{Sensors.conf}.

    \sa {Determining the default sensor for a type}
*/
QByteArray QSensor::defaultSensorForType(const QByteArray &type)
{
    QSensorManagerPrivate *d = sensorManagerPrivate();
    if (!d->pluginsLoaded)
        loadPlugins();

    // no sensors of that type exist
    if (!d->backendsByType.contains(type))
        return QByteArray();

    // The unit test needs to modify Sensors.conf but it can't access the system directory
    QSettings::Scope scope = settings_use_user_scope ? QSettings::UserScope : QSettings::SystemScope;
    QSettings settings(scope, QLatin1String("Nokia"), QLatin1String("Sensors"));
    QVariant value = settings.value(QString(QLatin1String("Default/%1")).arg(QString::fromLatin1(type)));
    if (!value.isNull()) {
        QByteArray defaultIdentifier = value.toByteArray();
        if (d->backendsByType[type].contains(defaultIdentifier)) // Don't return a value that we can't use!
            return defaultIdentifier;
    }

    // This is our fallback
    return d->firstIdentifierForType[type];
}

void QSensor::registerInstance()
{
    QSensorManagerPrivate *d = sensorManagerPrivate();
    connect(d, SIGNAL(availableSensorsChanged()), this, SIGNAL(availableSensorsChanged()));
}

// =====================================================================

/*!
    \class QSensorBackendFactory
    \ingroup sensors_backend
    \inmodule QtSensors

    \brief The QSensorBackendFactory class instantiates instances of
           QSensorBackend.

    This interface must be implemented in order to register a sensor backend.

    \sa {Creating a sensor plugin}
*/

/*!
    \fn QSensorBackendFactory::~QSensorBackendFactory()
    \internal
*/

/*!
    \fn QSensorBackendFactory::createBackend(QSensor *sensor)

    Instantiate a backend. If the factory handles multiple identifiers
    it should check with the \a sensor to see which one is requested.

    If the factory cannot create a backend it should return 0.
*/

/*!
    \macro REGISTER_STATIC_PLUGIN(pluginname)
    \relates QSensorManager

    Registers a static plugin, \a pluginname.

    Note that this macro relies on static initialization so it may not be appropriate
    for use in a library and may not work on all platforms.

    \sa {Creating a sensor plugin}
*/

#include "qsensormanager.moc"

QTM_END_NAMESPACE

<commit_msg>Ensure that loadPlugins cannot be used incorrectly.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $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 Technology Preview License Agreement accompanying
** this package.
**
** 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.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qsensormanager.h"
#include <QDebug>
#include "qsensorpluginloader_p.h"
#include "qsensorplugin.h"
#include <QSettings>
#include "sensorlog_p.h"
#include <QTimer>

QTM_BEGIN_NAMESPACE

Q_GLOBAL_STATIC(QSensorPluginLoader, pluginLoader)

typedef QHash<QByteArray,QSensorBackendFactory*> FactoryForIdentifierMap;
typedef QHash<QByteArray,FactoryForIdentifierMap> BackendIdentifiersForTypeMap;

class QSensorManagerPrivate : public QObject
{
    friend class QSensorManager;

    Q_OBJECT
public:
    QSensorManagerPrivate()
        : pluginsLoaded(false)
        , sensorsChanged(false)
    {
    }

    bool pluginsLoaded;
    void loadPlugins();

    QList<CreatePluginFunc> staticRegistrations;

    // Holds a mapping from type to available identifiers (and from there to the factory)
    BackendIdentifiersForTypeMap backendsByType;

    // Holds the first identifier for each type
    QHash<QByteArray, QByteArray> firstIdentifierForType;

    bool sensorsChanged;
    QList<QSensorChangesInterface*> changeListeners;

Q_SIGNALS:
    void availableSensorsChanged();

public Q_SLOTS:
    void emitSensorsChanged()
    {
        static bool alreadyRunning = false;
        if (!pluginsLoaded || alreadyRunning) {
            // We're busy.
            // Just note that a registration changed and exit.
            // Someone up the call stack will deal with this.
            sensorsChanged = true;
            return;
        }

        // Set a flag so any recursive calls doesn't cause a loop.
        alreadyRunning = true;

        // Since one [un]registration may cause other [un]registrations and since
        // the order in which we do things matters we just do a cascading update
        // until things stop changing.
        do {
            sensorsChanged = false;
            Q_FOREACH (QSensorChangesInterface *changes, changeListeners) {
                changes->sensorsChanged();
            }
        } while (sensorsChanged);

        // We're going away now so clear the flag
        alreadyRunning = false;

        // Notify the client of the changes
        Q_EMIT availableSensorsChanged();
    }
};

Q_GLOBAL_STATIC(QSensorManagerPrivate, sensorManagerPrivate)

// The unit test needs to change the behaviour of the library. It does this
// through an exported but undocumented function.
static void initPlugin(QObject *plugin);
static bool settings_use_user_scope = false;
static bool load_external_plugins = true;
Q_SENSORS_EXPORT void sensors_unit_test_hook(int index)
{
    QSensorManagerPrivate *d = sensorManagerPrivate();

    switch (index) {
    case 0:
        Q_ASSERT(d->pluginsLoaded == false);
        settings_use_user_scope = true;
        load_external_plugins = false;
        break;
    case 1:
        Q_ASSERT(load_external_plugins == false);
        Q_ASSERT(d->pluginsLoaded == true);
        SENSORLOG() << "initializing plugins";
        Q_FOREACH (QObject *plugin, pluginLoader()->plugins()) {
            initPlugin(plugin);
        }
        break;
    default:
        break;
    }
}

static void initPlugin(QObject *o)
{
    if (!o) return;
    QSensorManagerPrivate *d = sensorManagerPrivate();

    QSensorPluginInterface *plugin = qobject_cast<QSensorPluginInterface*>(o);
    if (plugin)
        plugin->registerSensors();
    QSensorChangesInterface *changes = qobject_cast<QSensorChangesInterface*>(o);
    if (changes)
        d->changeListeners << changes;
}

void QSensorManagerPrivate::loadPlugins()
{
    QSensorManagerPrivate *d = this;
    if (d->pluginsLoaded) return;
    d->pluginsLoaded = true;

    SENSORLOG() << "initializing static plugins";
    Q_FOREACH (CreatePluginFunc func, d->staticRegistrations) {
        QSensorPluginInterface *plugin = func();
        plugin->registerSensors();
    }

    if (load_external_plugins) {
        SENSORLOG() << "initializing plugins";
        Q_FOREACH (QObject *plugin, pluginLoader()->plugins()) {
            initPlugin(plugin);
        }
    }

    if (d->sensorsChanged) {
        // Notify the app that the available sensor list has changed.
        // This may cause recursive calls!
        d->emitSensorsChanged();
    }
}

// =====================================================================

/*!
    \class QSensorManager
    \ingroup sensors_backend
    \inmodule QtSensors

    \brief The QSensorManager class handles registration and creation of sensor backends.

    Sensor plugins register backends using the registerBackend() function.

    When QSensor::connectToBackend() is called, the createBackend() function will be called.
*/

/*!
    Register a sensor for \a type. The \a identifier must be unique.

    The \a factory will be asked to create instances of the backend.
*/
void QSensorManager::registerBackend(const QByteArray &type, const QByteArray &identifier, QSensorBackendFactory *factory)
{
    QSensorManagerPrivate *d = sensorManagerPrivate();
    if (!d->backendsByType.contains(type)) {
        (void)d->backendsByType[type];
        d->firstIdentifierForType[type] = identifier;
    } else if (d->firstIdentifierForType[type].startsWith("generic.")) {
        // Don't let a generic backend be the default when some other backend exists!
        d->firstIdentifierForType[type] = identifier;
    }
    FactoryForIdentifierMap &factoryByIdentifier = d->backendsByType[type];
    if (factoryByIdentifier.contains(identifier)) {
        qWarning() << "A backend with type" << type << "and identifier" << identifier << "has already been registered!";
        return;
    }
    SENSORLOG() << "registering backend for type" << type << "identifier" << identifier;// << "factory" << QString().sprintf("0x%08x", (unsigned int)factory);
    factoryByIdentifier[identifier] = factory;

    // Notify the app that the available sensor list has changed.
    // This may cause recursive calls!
    d->emitSensorsChanged();
}

/*!
    Unregister the backend for \a type with \a identifier.

    Note that this only prevents new instance of the backend from being created. It does not
    invalidate the existing instances of the backend. The backend code should handle the
    disappearance of the underlying hardware itself.
*/
void QSensorManager::unregisterBackend(const QByteArray &type, const QByteArray &identifier)
{
    QSensorManagerPrivate *d = sensorManagerPrivate();
    if (!d->backendsByType.contains(type)) {
        qWarning() << "No backends of type" << type << "are registered";
        return;
    }
    FactoryForIdentifierMap &factoryByIdentifier = d->backendsByType[type];
    if (!factoryByIdentifier.contains(identifier)) {
        qWarning() << "Identifier" << identifier << "is not registered";
        return;
    }

    (void)factoryByIdentifier.take(identifier); // we don't own this pointer anyway
    if (d->firstIdentifierForType[type] == identifier) {
        if (factoryByIdentifier.count()) {
            d->firstIdentifierForType[type] = factoryByIdentifier.begin().key();
            if (d->firstIdentifierForType[type].startsWith("generic.")) {
                // Don't let a generic backend be the default when some other backend exists!
                for (FactoryForIdentifierMap::const_iterator it = factoryByIdentifier.begin()++; it != factoryByIdentifier.end(); it++) {
                    const QByteArray &identifier(it.key());
                    if (!identifier.startsWith("generic.")) {
                        d->firstIdentifierForType[type] = identifier;
                        break;
                    }
                }
            }
        } else {
            (void)d->firstIdentifierForType.take(type);
        }
    }
    if (!factoryByIdentifier.count())
        (void)d->backendsByType.take(type);

    // Notify the app that the available sensor list has changed.
    // This may cause recursive calls!
    d->emitSensorsChanged();
}

/*!
    \internal
*/
void QSensorManager::registerStaticPlugin(CreatePluginFunc func)
{
    QSensorManagerPrivate *d = sensorManagerPrivate();
    d->staticRegistrations.append(func);
}

/*!
    Create a backend for \a sensor. Returns null if no suitable backend exists.
*/
QSensorBackend *QSensorManager::createBackend(QSensor *sensor)
{
    Q_ASSERT(sensor);

    QSensorManagerPrivate *d = sensorManagerPrivate();
    d->loadPlugins();

    SENSORLOG() << "QSensorManager::createBackend" << "type" << sensor->type() << "identifier" << sensor->identifier();

    if (!d->backendsByType.contains(sensor->type())) {
        SENSORLOG() << "no backends of type" << sensor->type() << "have been registered.";
        return 0;
    }

    const FactoryForIdentifierMap &factoryByIdentifier = d->backendsByType[sensor->type()];
    QSensorBackendFactory *factory;
    QSensorBackend *backend;

    if (sensor->identifier().isEmpty()) {
        QByteArray defaultIdentifier = QSensor::defaultSensorForType(sensor->type());
        SENSORLOG() << "Trying the default" << defaultIdentifier;
        // No identifier set, try the default
        factory = factoryByIdentifier[defaultIdentifier];
        //SENSORLOG() << "factory" << QString().sprintf("0x%08x", (unsigned int)factory);
        sensor->setIdentifier(defaultIdentifier); // the factory requires this
        backend = factory->createBackend(sensor);
        if (backend) return backend; // Got it!

        // The default failed to instantiate so try any other registered sensors for this type
        Q_FOREACH (const QByteArray &identifier, factoryByIdentifier.keys()) {
            SENSORLOG() << "Trying" << identifier;
            if (identifier == defaultIdentifier) continue; // Don't do the default one again
            factory = factoryByIdentifier[identifier];
            //SENSORLOG() << "factory" << QString().sprintf("0x%08x", (unsigned int)factory);
            sensor->setIdentifier(identifier); // the factory requires this
            backend = factory->createBackend(sensor);
            if (backend) return backend; // Got it!
        }
        SENSORLOG() << "FAILED";
        sensor->setIdentifier(QByteArray()); // clear the identifier
    } else {
        if (!factoryByIdentifier.contains(sensor->identifier())) {
            SENSORLOG() << "no backend with identifier" << sensor->identifier() << "for type" << sensor->type();
            return 0;
        }

        // We were given an explicit identifier so don't substitute other backends if it fails to instantiate
        factory = factoryByIdentifier[sensor->identifier()];
        //SENSORLOG() << "factory" << QString().sprintf("0x%08x", (unsigned int)factory);
        backend = factory->createBackend(sensor);
        if (backend) return backend; // Got it!
    }

    SENSORLOG() << "no suitable backend found for requested identifier" << sensor->identifier() << "and type" << sensor->type();
    return 0;
}

/*!
    Returns true if the backend identified by \a type and \a identifier is registered.

    This is a convenience method that helps out plugins doing dynamic registration.
*/
bool QSensorManager::isBackendRegistered(const QByteArray &type, const QByteArray &identifier)
{
    QSensorManagerPrivate *d = sensorManagerPrivate();
    d->loadPlugins();

    if (!d->backendsByType.contains(type))
        return false;

    const FactoryForIdentifierMap &factoryByIdentifier = d->backendsByType[type];
    if (!factoryByIdentifier.contains(identifier))
        return false;

    return true;
}

// =====================================================================

/*!
    Returns a list of all sensor types.
*/
QList<QByteArray> QSensor::sensorTypes()
{
    QSensorManagerPrivate *d = sensorManagerPrivate();
    d->loadPlugins();

    return d->backendsByType.keys();
}

/*!
    Returns a list of ids for each of the sensors for \a type.
    If there are no sensors of that type available the list will be empty.
*/
QList<QByteArray> QSensor::sensorsForType(const QByteArray &type)
{
    QSensorManagerPrivate *d = sensorManagerPrivate();
    d->loadPlugins();

    // no sensors of that type exist
    if (!d->backendsByType.contains(type))
        return QList<QByteArray>();

    return d->backendsByType[type].keys();
}

/*!
    Returns the default sensor identifier for \a type.
    This is set in a config file and can be overridden if required.
    If no default is available the system will return the first registered
    sensor for \a type.

    Note that there is special case logic to prevent the generic plugin's backends from becoming the
    default when another backend is registered for the same type. This logic means that a backend
    identifier starting with \c{generic.} will only be the default if no other backends have been
    registered for that type or if it is specified in \c{Sensors.conf}.

    \sa {Determining the default sensor for a type}
*/
QByteArray QSensor::defaultSensorForType(const QByteArray &type)
{
    QSensorManagerPrivate *d = sensorManagerPrivate();
    d->loadPlugins();

    // no sensors of that type exist
    if (!d->backendsByType.contains(type))
        return QByteArray();

    // The unit test needs to modify Sensors.conf but it can't access the system directory
    QSettings::Scope scope = settings_use_user_scope ? QSettings::UserScope : QSettings::SystemScope;
    QSettings settings(scope, QLatin1String("Nokia"), QLatin1String("Sensors"));
    QVariant value = settings.value(QString(QLatin1String("Default/%1")).arg(QString::fromLatin1(type)));
    if (!value.isNull()) {
        QByteArray defaultIdentifier = value.toByteArray();
        if (d->backendsByType[type].contains(defaultIdentifier)) // Don't return a value that we can't use!
            return defaultIdentifier;
    }

    // This is our fallback
    return d->firstIdentifierForType[type];
}

void QSensor::registerInstance()
{
    QSensorManagerPrivate *d = sensorManagerPrivate();
    connect(d, SIGNAL(availableSensorsChanged()), this, SIGNAL(availableSensorsChanged()));
}

// =====================================================================

/*!
    \class QSensorBackendFactory
    \ingroup sensors_backend
    \inmodule QtSensors

    \brief The QSensorBackendFactory class instantiates instances of
           QSensorBackend.

    This interface must be implemented in order to register a sensor backend.

    \sa {Creating a sensor plugin}
*/

/*!
    \fn QSensorBackendFactory::~QSensorBackendFactory()
    \internal
*/

/*!
    \fn QSensorBackendFactory::createBackend(QSensor *sensor)

    Instantiate a backend. If the factory handles multiple identifiers
    it should check with the \a sensor to see which one is requested.

    If the factory cannot create a backend it should return 0.
*/

/*!
    \macro REGISTER_STATIC_PLUGIN(pluginname)
    \relates QSensorManager

    Registers a static plugin, \a pluginname.

    Note that this macro relies on static initialization so it may not be appropriate
    for use in a library and may not work on all platforms.

    \sa {Creating a sensor plugin}
*/

#include "qsensormanager.moc"

QTM_END_NAMESPACE

<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2012 Sergey Lisitsyn
 * Copyright (C) 2012 Sergey Lisitsyn
 */

#include <shogun/ui/GUIConverter.h>
#include <shogun/ui/SGInterface.h>

#include <shogun/lib/config.h>
#include <shogun/io/SGIO.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/kernel/GaussianKernel.h>

#include <shogun/converter/LocallyLinearEmbedding.h>
#include <shogun/converter/HessianLocallyLinearEmbedding.h>
#include <shogun/converter/LocalTangentSpaceAlignment.h>
#include <shogun/converter/NeighborhoodPreservingEmbedding.h>
#include <shogun/converter/LaplacianEigenmaps.h>
#include <shogun/converter/LocalityPreservingProjections.h>
#include <shogun/converter/DiffusionMaps.h>
#include <shogun/converter/LinearLocalTangentSpaceAlignment.h>
#include <shogun/converter/MultidimensionalScaling.h>
#include <shogun/converter/Isomap.h>
#include <shogun/converter/EmbeddingConverter.h>

using namespace shogun;

CGUIConverter::CGUIConverter(CSGInterface* ui)
: CSGObject(), m_ui(ui)
{
	m_converter = NULL;
}

CGUIConverter::~CGUIConverter()
{
	SG_UNREF(m_converter);
}

bool CGUIConverter::create_locallylinearembedding(int32_t k)
{
#ifdef HAVE_LAPACK
	m_converter = new CLocallyLinearEmbedding();
	((CLocallyLinearEmbedding*)m_converter)->set_k(k);
#else
	SG_ERROR("Requires Lapack to be enabled at compile time\n");
#endif
	return true;
}

bool CGUIConverter::create_neighborhoodpreservingembedding(int32_t k)
{
#ifdef HAVE_LAPACK
	m_converter = new CNeighborhoodPreservingEmbedding();
	((CNeighborhoodPreservingEmbedding*)m_converter)->set_k(k);
#else
	SG_ERROR("Requires Lapack to be enabled at compile time\n");
#endif
	return true;
}

bool CGUIConverter::create_localtangentspacealignment(int32_t k)
{
#ifdef HAVE_LAPACK
	m_converter = new CLocalTangentSpaceAlignment();
	((CLocalTangentSpaceAlignment*)m_converter)->set_k(k);
#else
	SG_ERROR("Requires Lapack to be enabled at compile time\n");
#endif
	return true;
}

bool CGUIConverter::create_linearlocaltangentspacealignment(int32_t k)
{
#ifdef HAVE_LAPACK
	m_converter = new CLinearLocalTangentSpaceAlignment();
	((CLinearLocalTangentSpaceAlignment*)m_converter)->set_k(k);
#else
	SG_ERROR("Requires Lapack to be enabled at compile time\n");
#endif
	return true;
}

bool CGUIConverter::create_hessianlocallylinearembedding(int32_t k)
{
#ifdef HAVE_LAPACK
	m_converter = new CLocallyLinearEmbedding();
	((CHessianLocallyLinearEmbedding*)m_converter)->set_k(k);
#else
	SG_ERROR("Requires Lapack to be enabled at compile time\n");
#endif
	return true;
}

bool CGUIConverter::create_laplacianeigenmaps(int32_t k, float64_t width)
{
#ifdef HAVE_LAPACK
	m_converter = new CLaplacianEigenmaps();
	((CLaplacianEigenmaps*)m_converter)->set_k(k);
	((CLaplacianEigenmaps*)m_converter)->set_tau(width);
#else
	SG_ERROR("Requires Lapack to be enabled at compile time\n");
#endif
	return true;
}

bool CGUIConverter::create_localitypreservingprojections(int32_t k, float64_t width)
{
#ifdef HAVE_LAPACK
	m_converter = new CLocalityPreservingProjections();
	((CLocalityPreservingProjections*)m_converter)->set_k(k);
	((CLocalityPreservingProjections*)m_converter)->set_tau(width);
#else
	SG_ERROR("Requires Lapack to be enabled at compile time\n");
#endif
	return true;
}

bool CGUIConverter::create_diffusionmaps(int32_t t, float64_t width)
{
#ifdef HAVE_LAPACK
	m_converter = new CDiffusionMaps();
	((CDiffusionMaps*)m_converter)->set_t(t);
	((CDiffusionMaps*)m_converter)->set_kernel(new CGaussianKernel(100,width));
#else
	SG_ERROR("Requires Lapack to be enabled at compile time\n");
#endif
	return true;
}

bool CGUIConverter::create_isomap(int32_t k)
{
#ifdef HAVE_LAPACK
	m_converter = new CIsomap();
	((CIsomap*)m_converter)->set_k(k);
#else
	SG_ERROR("Requires Lapack to be enabled at compile time\n");
#endif
	return true;
}

bool CGUIConverter::create_multidimensionalscaling()
{
#ifdef HAVE_LAPACK
	m_converter = new CMultidimensionalScaling();
#else
	SG_ERROR("Requires Lapack to be enabled at compile time\n");
#endif
	return true;
}

CDenseFeatures<float64_t>* CGUIConverter::embed(int32_t target_dim)
{
	if (!m_converter)
		SG_ERROR("No converter created");
	((CEmbeddingConverter*)m_converter)->set_target_dim(target_dim);
	return ((CEmbeddingConverter*)m_converter)->embed(m_ui->ui_features->get_train_features());
}

<commit_msg>Fixed requirement in static converter interface<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2012 Sergey Lisitsyn
 * Copyright (C) 2012 Sergey Lisitsyn
 */

#include <shogun/ui/GUIConverter.h>
#include <shogun/ui/SGInterface.h>

#include <shogun/lib/config.h>
#include <shogun/io/SGIO.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/kernel/GaussianKernel.h>

#include <shogun/converter/LocallyLinearEmbedding.h>
#include <shogun/converter/HessianLocallyLinearEmbedding.h>
#include <shogun/converter/LocalTangentSpaceAlignment.h>
#include <shogun/converter/NeighborhoodPreservingEmbedding.h>
#include <shogun/converter/LaplacianEigenmaps.h>
#include <shogun/converter/LocalityPreservingProjections.h>
#include <shogun/converter/DiffusionMaps.h>
#include <shogun/converter/LinearLocalTangentSpaceAlignment.h>
#include <shogun/converter/MultidimensionalScaling.h>
#include <shogun/converter/Isomap.h>
#include <shogun/converter/EmbeddingConverter.h>

using namespace shogun;

CGUIConverter::CGUIConverter(CSGInterface* ui)
: CSGObject(), m_ui(ui)
{
	m_converter = NULL;
}

CGUIConverter::~CGUIConverter()
{
	SG_UNREF(m_converter);
}

bool CGUIConverter::create_locallylinearembedding(int32_t k)
{
#ifdef HAVE_EIGEN3
	m_converter = new CLocallyLinearEmbedding();
	((CLocallyLinearEmbedding*)m_converter)->set_k(k);
#else
	SG_ERROR("Requires EIGEN3 to be enabled at compile time\n");
#endif
	return true;
}

bool CGUIConverter::create_neighborhoodpreservingembedding(int32_t k)
{
#ifdef HAVE_EIGEN3
	m_converter = new CNeighborhoodPreservingEmbedding();
	((CNeighborhoodPreservingEmbedding*)m_converter)->set_k(k);
#else
	SG_ERROR("Requires EIGEN3 to be enabled at compile time\n");
#endif
	return true;
}

bool CGUIConverter::create_localtangentspacealignment(int32_t k)
{
#ifdef HAVE_EIGEN3
	m_converter = new CLocalTangentSpaceAlignment();
	((CLocalTangentSpaceAlignment*)m_converter)->set_k(k);
#else
	SG_ERROR("Requires EIGEN3 to be enabled at compile time\n");
#endif
	return true;
}

bool CGUIConverter::create_linearlocaltangentspacealignment(int32_t k)
{
#ifdef HAVE_EIGEN3
	m_converter = new CLinearLocalTangentSpaceAlignment();
	((CLinearLocalTangentSpaceAlignment*)m_converter)->set_k(k);
#else
	SG_ERROR("Requires EIGEN3 to be enabled at compile time\n");
#endif
	return true;
}

bool CGUIConverter::create_hessianlocallylinearembedding(int32_t k)
{
#ifdef HAVE_EIGEN3
	m_converter = new CLocallyLinearEmbedding();
	((CHessianLocallyLinearEmbedding*)m_converter)->set_k(k);
#else
	SG_ERROR("Requires EIGEN3 to be enabled at compile time\n");
#endif
	return true;
}

bool CGUIConverter::create_laplacianeigenmaps(int32_t k, float64_t width)
{
#ifdef HAVE_EIGEN3
	m_converter = new CLaplacianEigenmaps();
	((CLaplacianEigenmaps*)m_converter)->set_k(k);
	((CLaplacianEigenmaps*)m_converter)->set_tau(width);
#else
	SG_ERROR("Requires EIGEN3 to be enabled at compile time\n");
#endif
	return true;
}

bool CGUIConverter::create_localitypreservingprojections(int32_t k, float64_t width)
{
#ifdef HAVE_EIGEN3
	m_converter = new CLocalityPreservingProjections();
	((CLocalityPreservingProjections*)m_converter)->set_k(k);
	((CLocalityPreservingProjections*)m_converter)->set_tau(width);
#else
	SG_ERROR("Requires EIGEN3 to be enabled at compile time\n");
#endif
	return true;
}

bool CGUIConverter::create_diffusionmaps(int32_t t, float64_t width)
{
#ifdef HAVE_EIGEN3
	m_converter = new CDiffusionMaps();
	((CDiffusionMaps*)m_converter)->set_t(t);
	((CDiffusionMaps*)m_converter)->set_kernel(new CGaussianKernel(100,width));
#else
	SG_ERROR("Requires EIGEN3 to be enabled at compile time\n");
#endif
	return true;
}

bool CGUIConverter::create_isomap(int32_t k)
{
#ifdef HAVE_EIGEN3
	m_converter = new CIsomap();
	((CIsomap*)m_converter)->set_k(k);
#else
	SG_ERROR("Requires EIGEN3 to be enabled at compile time\n");
#endif
	return true;
}

bool CGUIConverter::create_multidimensionalscaling()
{
#ifdef HAVE_EIGEN3
	m_converter = new CMultidimensionalScaling();
#else
	SG_ERROR("Requires EIGEN3 to be enabled at compile time\n");
#endif
	return true;
}

CDenseFeatures<float64_t>* CGUIConverter::embed(int32_t target_dim)
{
	if (!m_converter)
		SG_ERROR("No converter created");
	((CEmbeddingConverter*)m_converter)->set_target_dim(target_dim);
	return ((CEmbeddingConverter*)m_converter)->embed(m_ui->ui_features->get_train_features());
}

<|endoftext|>


<commit_before>/*
	Flexisip, a flexible SIP proxy server with media capabilities.
	Copyright (C) 2010  Belledonne Communications SARL.

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

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "flexisip/sip-boolean-expressions.hh"
#include "flexisip/expressionparser-impl.cc"
#include "sofia-sip/sip.h"

using namespace std;

namespace flexisip{

shared_ptr<SipBooleanExpressionBuilder> SipBooleanExpressionBuilder::sInstance;

static inline string stringFromC(const char *s){
	return s ? string(s) : string();
}

static ExpressionRules<sip_t> rules = {
	{
		{"direction", [](const sip_t &sip)->string {return sip.sip_request != nullptr ? "request" : "response";} },

		{"request.method-name", [](const sip_t &sip)->string {
			return stringFromC((sip.sip_request && sip.sip_request->rq_method_name) ? sip.sip_request->rq_method_name : nullptr);} },
		{"request.method", [](const sip_t &sip)->string {
			return stringFromC((sip.sip_request && sip.sip_request->rq_method_name) ? sip.sip_request->rq_method_name : nullptr);} },
		{"request.uri.domain", [](const sip_t &sip)->string {
			return stringFromC(sip.sip_request ? sip.sip_request->rq_url->url_host : nullptr);} },
		{"request.uri.user", [](const sip_t &sip)->string {
			return stringFromC(sip.sip_request ? sip.sip_request->rq_url->url_user : nullptr);} },
		{"request.uri.params", [](const sip_t &sip)->string {
			return stringFromC(sip.sip_request ? sip.sip_request->rq_url->url_params : nullptr);} },

		{"from.uri.domain", [](const sip_t &sip)->string {return stringFromC(sip.sip_from ? sip.sip_from->a_url->url_host : nullptr);} },
		{"from.uri.user", [](const sip_t &sip)->string {return stringFromC(sip.sip_from ? sip.sip_from->a_url->url_user : nullptr);} },
		{"from.uri.params", [](const sip_t &sip)->string {return stringFromC(sip.sip_from ? sip.sip_from->a_url->url_params : nullptr);} },

		{"to.uri.domain", [](const sip_t &sip)->string {return stringFromC(sip.sip_to ? sip.sip_to->a_url->url_host : nullptr);} },
		{"to.uri.user", [](const sip_t &sip)->string {return stringFromC(sip.sip_to ? sip.sip_to->a_url->url_user : nullptr);} },
		{"to.uri.params", [](const sip_t &sip)->string {return stringFromC(sip.sip_to ? sip.sip_to->a_url->url_params : nullptr);} },

		{"user-agent", [](const sip_t &sip)->string {return stringFromC(sip.sip_user_agent ? sip.sip_user_agent->g_string : nullptr);} },

		{"call-id", [](const sip_t &sip)->string {return stringFromC(sip.sip_call_id ? sip.sip_call_id->i_id : nullptr);} },
		{"call-id.hash", [](const sip_t &sip)->string {
			ostringstream ostr;
			if (sip.sip_call_id) ostr << sip.sip_call_id->i_hash;
			return ostr.str();
		} },

		{"status.phrase", [](const sip_t &sip)->string {return stringFromC(sip.sip_status ? sip.sip_status->st_phrase : nullptr);} },
		{"status.code", [](const sip_t &sip)->string {
			ostringstream ostr;
			if (sip.sip_status) ostr << sip.sip_status->st_status;
			return ostr.str();
		} }
	},
	{
		{"is_request", [](const sip_t & sip)->bool {return sip.sip_request != nullptr;} },
		{"is_response", [](const sip_t & sip)->bool {return sip.sip_request == nullptr;} }
	}
};

SipBooleanExpressionBuilder::SipBooleanExpressionBuilder() : BooleanExpressionBuilder<sip_t>(rules){
}

SipBooleanExpressionBuilder &SipBooleanExpressionBuilder::get(){
	if (!sInstance) {
		sInstance = shared_ptr<SipBooleanExpressionBuilder>(new SipBooleanExpressionBuilder());
	}
	return *sInstance;
}

shared_ptr<SipBooleanExpression> SipBooleanExpressionBuilder::parse(const string &expression){
	return BooleanExpressionBuilder<sip_t>::parse(expression);
}

}//end of namespace
<commit_msg>Add "contact" header to the list of headers that can be used in entry filters of modules. This may be useful to prevent NatHelper module to alterate contact header in some situations, until a better solution is found.<commit_after>/*
	Flexisip, a flexible SIP proxy server with media capabilities.
	Copyright (C) 2010  Belledonne Communications SARL.

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

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "flexisip/sip-boolean-expressions.hh"
#include "flexisip/expressionparser-impl.cc"
#include "sofia-sip/sip.h"

using namespace std;

namespace flexisip{

shared_ptr<SipBooleanExpressionBuilder> SipBooleanExpressionBuilder::sInstance;

static inline string stringFromC(const char *s){
	return s ? string(s) : string();
}

static ExpressionRules<sip_t> rules = {
	{
		{"direction", [](const sip_t &sip)->string {return sip.sip_request != nullptr ? "request" : "response";} },

		{"request.method-name", [](const sip_t &sip)->string {
			return stringFromC((sip.sip_request && sip.sip_request->rq_method_name) ? sip.sip_request->rq_method_name : nullptr);} },
		{"request.method", [](const sip_t &sip)->string {
			return stringFromC((sip.sip_request && sip.sip_request->rq_method_name) ? sip.sip_request->rq_method_name : nullptr);} },
		{"request.uri.domain", [](const sip_t &sip)->string {
			return stringFromC(sip.sip_request ? sip.sip_request->rq_url->url_host : nullptr);} },
		{"request.uri.user", [](const sip_t &sip)->string {
			return stringFromC(sip.sip_request ? sip.sip_request->rq_url->url_user : nullptr);} },
		{"request.uri.params", [](const sip_t &sip)->string {
			return stringFromC(sip.sip_request ? sip.sip_request->rq_url->url_params : nullptr);} },

		{"from.uri.domain", [](const sip_t &sip)->string {return stringFromC(sip.sip_from ? sip.sip_from->a_url->url_host : nullptr);} },
		{"from.uri.user", [](const sip_t &sip)->string {return stringFromC(sip.sip_from ? sip.sip_from->a_url->url_user : nullptr);} },
		{"from.uri.params", [](const sip_t &sip)->string {return stringFromC(sip.sip_from ? sip.sip_from->a_url->url_params : nullptr);} },

		{"to.uri.domain", [](const sip_t &sip)->string {return stringFromC(sip.sip_to ? sip.sip_to->a_url->url_host : nullptr);} },
		{"to.uri.user", [](const sip_t &sip)->string {return stringFromC(sip.sip_to ? sip.sip_to->a_url->url_user : nullptr);} },
		{"to.uri.params", [](const sip_t &sip)->string {return stringFromC(sip.sip_to ? sip.sip_to->a_url->url_params : nullptr);} },

		{"contact.uri.domain", [](const sip_t &sip)->string {return stringFromC(sip.sip_contact ? sip.sip_contact->m_url->url_host : nullptr);} },
		{"contact.uri.user", [](const sip_t &sip)->string {return stringFromC(sip.sip_contact ? sip.sip_contact->m_url->url_user : nullptr);} },
		{"contact.uri.params", [](const sip_t &sip)->string {return stringFromC(sip.sip_contact ? sip.sip_contact->m_url->url_params : nullptr);} },

		{"user-agent", [](const sip_t &sip)->string {return stringFromC(sip.sip_user_agent ? sip.sip_user_agent->g_string : nullptr);} },

		{"call-id", [](const sip_t &sip)->string {return stringFromC(sip.sip_call_id ? sip.sip_call_id->i_id : nullptr);} },
		{"call-id.hash", [](const sip_t &sip)->string {
			ostringstream ostr;
			if (sip.sip_call_id) ostr << sip.sip_call_id->i_hash;
			return ostr.str();
		} },

		{"status.phrase", [](const sip_t &sip)->string {return stringFromC(sip.sip_status ? sip.sip_status->st_phrase : nullptr);} },
		{"status.code", [](const sip_t &sip)->string {
			ostringstream ostr;
			if (sip.sip_status) ostr << sip.sip_status->st_status;
			return ostr.str();
		} }
	},
	{
		{"is_request", [](const sip_t & sip)->bool {return sip.sip_request != nullptr;} },
		{"is_response", [](const sip_t & sip)->bool {return sip.sip_request == nullptr;} }
	}
};

SipBooleanExpressionBuilder::SipBooleanExpressionBuilder() : BooleanExpressionBuilder<sip_t>(rules){
}

SipBooleanExpressionBuilder &SipBooleanExpressionBuilder::get(){
	if (!sInstance) {
		sInstance = shared_ptr<SipBooleanExpressionBuilder>(new SipBooleanExpressionBuilder());
	}
	return *sInstance;
}

shared_ptr<SipBooleanExpression> SipBooleanExpressionBuilder::parse(const string &expression){
	return BooleanExpressionBuilder<sip_t>::parse(expression);
}

}//end of namespace
<|endoftext|>


<commit_before>#ifndef COMBINATIONS_HPP_
#define COMBINATIONS_HPP_

#include "iterbase.hpp"

#include <vector>
#include <type_traits>
#include <iterator>
#include <initializer_list>

namespace iter {
    template <typename Container>
    class Combinator;

    template <typename Container>
    Combinator<Container> combinations(Container&&, std::size_t);

    template <typename T>
    Combinator<std::initializer_list<T>> combinations(
            std::initializer_list<T>, std::size_t);

    template <typename Container>
    class Combinator {
        private:
            Container container;
            std::size_t length;

            friend Combinator combinations<Container>(Container&&,std::size_t);
            template <typename T>
            friend Combinator<std::initializer_list<T>> combinations(
                    std::initializer_list<T>, std::size_t);

            Combinator(Container in_container, std::size_t in_length)
                : container(std::forward<Container>(in_container)),
                length{in_length}
            { }

        public:

        class Iterator {
            private:
                Container& items;
                std::vector<iterator_type<Container>> indicies;
                bool not_done = true;

            public:
                Iterator(Container& i, std::size_t n)
                    : items(i),
                    indicies(n)
                {
                    if (n == 0) {
                        not_done = false;
                        return;
                    }
                    size_t inc = 0;
                    for (auto& iter : this->indicies) {
                        auto it = std::begin(this->items);
                        dumb_advance(it, std::end(this->items), inc);
                        if (it != std::end(this->items)) {
                            iter = it;
                            ++inc;
                        } else {
                            not_done = false;
                            break;
                        }
                    }
                }

                std::vector<collection_item_type<Container>> operator*() {
                    std::vector<collection_item_type<Container>> values;
                    for (auto i : indicies) {
                        values.push_back(*i);
                    }
                    return values;
                }

                Iterator& operator++() {
                    for (auto iter = indicies.rbegin();
                            iter != indicies.rend();
                            ++iter) {
                        ++(*iter);

                        //what we have to check here is if the distance between
                        //the index and the end of indicies is >= the distance
                        //between the item and end of item
                        auto dist = std::distance(
                                this->indicies.rbegin(),iter);

                        if (!(dumb_next(*iter, dist) !=
                                std::end(this->items))) {
                            if ( (iter + 1) != indicies.rend()) {
                                size_t inc = 1;
                                for (auto down = iter;
                                        down != indicies.rbegin()-1;
                                        --down) {
                                    (*down) = dumb_next(*(iter + 1), 1 + inc);
                                    ++inc;
                                }
                            } else {
                                not_done = false;
                                break;
                            }
                        } else {
                            break;
                        }
                        //we break because none of the rest of the items need
                        //to be incremented
                    }
                    return *this;
                }

                bool operator !=(const Iterator&)
                {
                    //because of the way this is done you have to start from
                    //the begining of the range and end at the end, you could
                    //break in the middle of the loop though, it's not
                    //different from the way that python's works
                    return not_done;
                }
        };

        Iterator begin() {
            return {this->container, this->length};
        }

        Iterator end() {
            return {this->container, this->length};
        }
    };

    template <typename Container>
    Combinator<Container> combinations(
            Container&& container, std::size_t length) {
        return {std::forward<Container>(container), length};
    }

    template <typename T>
    Combinator<std::initializer_list<T>> combinations(
            std::initializer_list<T> il, std::size_t length) {
        return {il, length};
    }
}
#endif //#ifndef COMBINATIONS_HPP_
<commit_msg>combination iterator inherits from std::iterator<commit_after>#ifndef ITER_COMBINATIONS_HPP_
#define ITER_COMBINATIONS_HPP_

#include "iterbase.hpp"

#include <vector>
#include <type_traits>
#include <iterator>
#include <initializer_list>

namespace iter {
    template <typename Container>
    class Combinator;

    template <typename Container>
    Combinator<Container> combinations(Container&&, std::size_t);

    template <typename T>
    Combinator<std::initializer_list<T>> combinations(
            std::initializer_list<T>, std::size_t);

    template <typename Container>
    class Combinator {
        private:
            Container container;
            std::size_t length;

            friend Combinator combinations<Container>(Container&&,std::size_t);
            template <typename T>
            friend Combinator<std::initializer_list<T>> combinations(
                    std::initializer_list<T>, std::size_t);

            Combinator(Container in_container, std::size_t in_length)
                : container(std::forward<Container>(in_container)),
                length{in_length}
            { }

            using CombIteratorDeref =
                std::vector<collection_item_type<Container>>;
        public:

        class Iterator :
            public std::iterator<std::input_iterator_tag, CombIteratorDeref>
        {
            private:
                Container& items;
                std::vector<iterator_type<Container>> indicies;
                bool not_done = true;

            public:
                Iterator(Container& i, std::size_t n)
                    : items(i),
                    indicies(n)
                {
                    if (n == 0) {
                        not_done = false;
                        return;
                    }
                    size_t inc = 0;
                    for (auto& iter : this->indicies) {
                        auto it = std::begin(this->items);
                        dumb_advance(it, std::end(this->items), inc);
                        if (it != std::end(this->items)) {
                            iter = it;
                            ++inc;
                        } else {
                            not_done = false;
                            break;
                        }
                    }
                }

                CombIteratorDeref operator*() {
                    CombIteratorDeref values;
                    for (auto i : indicies) {
                        values.push_back(*i);
                    }
                    return values;
                }

                Iterator& operator++() {
                    for (auto iter = indicies.rbegin();
                            iter != indicies.rend();
                            ++iter) {
                        ++(*iter);

                        //what we have to check here is if the distance between
                        //the index and the end of indicies is >= the distance
                        //between the item and end of item
                        auto dist = std::distance(
                                this->indicies.rbegin(),iter);

                        if (!(dumb_next(*iter, dist) !=
                                std::end(this->items))) {
                            if ( (iter + 1) != indicies.rend()) {
                                size_t inc = 1;
                                for (auto down = iter;
                                        down != indicies.rbegin()-1;
                                        --down) {
                                    (*down) = dumb_next(*(iter + 1), 1 + inc);
                                    ++inc;
                                }
                            } else {
                                not_done = false;
                                break;
                            }
                        } else {
                            break;
                        }
                        //we break because none of the rest of the items need
                        //to be incremented
                    }
                    return *this;
                }

                bool operator !=(const Iterator&)
                {
                    //because of the way this is done you have to start from
                    //the begining of the range and end at the end, you could
                    //break in the middle of the loop though, it's not
                    //different from the way that python's works
                    return not_done;
                }
        };

        Iterator begin() {
            return {this->container, this->length};
        }

        Iterator end() {
            return {this->container, this->length};
        }
    };

    template <typename Container>
    Combinator<Container> combinations(
            Container&& container, std::size_t length) {
        return {std::forward<Container>(container), length};
    }

    template <typename T>
    Combinator<std::initializer_list<T>> combinations(
            std::initializer_list<T> il, std::size_t length) {
        return {il, length};
    }
}
#endif
<|endoftext|>


<commit_before>/* vim: tabstop=2 shiftwidth=2 expandtab textwidth=80 linebreak wrap
 *
 * Copyright 2012 Matthew McCormick
 * Copyright 2015 Pawel 'l0ner' Soltys
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <sstream>

#include "memory.h"
#include "luts.h"
#include "conversions.h"
#include "powerline.h"

std::string mem_string( const MemoryStatus & mem_status,
  MEMORY_MODE mode,
  bool use_colors,
  bool use_powerline_left,
  bool use_powerline_right )
{
  std::ostringstream oss;
  // Change the percision for floats, for a pretty output
  oss.precision( 2 );
  oss.setf( std::ios::fixed | std::ios::right );

  unsigned int color = static_cast< unsigned int >((100 * mem_status.used_mem) / mem_status.total_mem);
  if( use_colors )
  {
    if( use_powerline_right )
    {
      oss << "#[bg=default]";
      powerline( oss, mem_lut[color], POWERLINE_RIGHT );
      oss << ' ';
    }
    else if( use_powerline_left )
    {
      //powerline( oss, mem_lut[color], POWERLINE_LEFT );
      // We do not know how to invert the default background color
      powerline( oss, mem_lut[color], NONE );
      oss << ' ';
    }
    else
    {
      powerline( oss, mem_lut[color], NONE );
    }
  }

  switch( mode )
  {
  case MEMORY_MODE_FREE_MEMORY: // Show free memory in MB or GB
    {
    const float free_mem = mem_status.total_mem - mem_status.used_mem;
    const float free_mem_in_gigabytes = convert_unit( free_mem, GIGABYTES, MEGABYTES );

    // if free memory is less than 1 GB, use MB instead
    if(  free_mem_in_gigabytes < 1.0f )
    {
      oss << free_mem << "MB";
    }
    else
    {
      oss << free_mem_in_gigabytes << "GB";
    }
    break;
    }
  case MEMORY_MODE_USAGE_PERCENTAGE:
    {
    // Calculate the percentage of used memory
    const float percentage_mem = mem_status.used_mem /
      static_cast<float>( mem_status.total_mem ) * 100.0;

    oss << percentage_mem << '%';
    break;
    }
  default: // Default mode, just show the used/total memory in MB
    if(mem_status.used_mem>100000 && mem_status.total_mem>100000) oss<<static_cast<unsigned int>(mem_status.used_mem/1024)<<"/"<<static_cast<unsigned int>(mem_status.total_mem/1024)<<"GB";
    else if(mem_status.used_mem<100000 && mem_status.total_mem>100000) oss<<static_cast<unsigned int>(mem_status.used_mem)<<"MB/"<<static_cast<unsigned int>(mem_status.total_mem/1024)<<"GB";
    else oss<<static_cast<unsigned int>(mem_status.used_mem)<<"/"<<static_cast<unsigned int>(mem_status.total_mem)<<"MB";
  }

  if( use_colors )
  {
    if( use_powerline_left )
    {
      powerline( oss, mem_lut[color], POWERLINE_LEFT, true );
    }
    else if( !use_powerline_right )
    {
      oss << "#[fg=default,bg=default]";
    }
  }

  return oss.str();
}

<commit_msg>Less sensitive memory default thresholds<commit_after>/* vim: tabstop=2 shiftwidth=2 expandtab textwidth=80 linebreak wrap
 *
 * Copyright 2012 Matthew McCormick
 * Copyright 2015 Pawel 'l0ner' Soltys
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <sstream>

#include "memory.h"
#include "luts.h"
#include "conversions.h"
#include "powerline.h"

std::string mem_string( const MemoryStatus & mem_status,
  MEMORY_MODE mode,
  bool use_colors,
  bool use_powerline_left,
  bool use_powerline_right )
{
  std::ostringstream oss;
  // Change the percision for floats, for a pretty output
  oss.precision( 2 );
  oss.setf( std::ios::fixed | std::ios::right );

  unsigned int color = static_cast< unsigned int >((100 * mem_status.used_mem) / mem_status.total_mem);
  if( use_colors )
  {
    if( use_powerline_right )
    {
      oss << "#[bg=default]";
      powerline( oss, mem_lut[color], POWERLINE_RIGHT );
      oss << ' ';
    }
    else if( use_powerline_left )
    {
      //powerline( oss, mem_lut[color], POWERLINE_LEFT );
      // We do not know how to invert the default background color
      powerline( oss, mem_lut[color], NONE );
      oss << ' ';
    }
    else
    {
      powerline( oss, mem_lut[color], NONE );
    }
  }

  switch( mode )
  {
  case MEMORY_MODE_FREE_MEMORY: // Show free memory in MB or GB
    {
    const float free_mem = mem_status.total_mem - mem_status.used_mem;
    const float free_mem_in_gigabytes = convert_unit( free_mem, GIGABYTES, MEGABYTES );

    // if free memory is less than 1 GB, use MB instead
    if(  free_mem_in_gigabytes < 1.0f )
    {
      oss << free_mem << "MB";
    }
    else
    {
      oss << free_mem_in_gigabytes << "GB";
    }
    break;
    }
  case MEMORY_MODE_USAGE_PERCENTAGE:
    {
    // Calculate the percentage of used memory
    const float percentage_mem = mem_status.used_mem /
      static_cast<float>( mem_status.total_mem ) * 100.0;

    oss << percentage_mem << '%';
    break;
    }
  default: // Default mode, just show the used/total memory in MB
    if(mem_status.used_mem>10000 && mem_status.total_mem>10000)
      oss<<static_cast<unsigned int>(mem_status.used_mem/1024)<<"/"<<static_cast<unsigned int>(mem_status.total_mem/1024)<<"GB";
    else if(mem_status.used_mem<10000 && mem_status.total_mem>10000)
      oss<<static_cast<unsigned int>(mem_status.used_mem)<<"MB/"<<static_cast<unsigned int>(mem_status.total_mem/1024)<<"GB";
    else
      oss<<static_cast<unsigned int>(mem_status.used_mem)<<"/"<<static_cast<unsigned int>(mem_status.total_mem)<<"MB";
  }

  if( use_colors )
  {
    if( use_powerline_left )
    {
      powerline( oss, mem_lut[color], POWERLINE_LEFT, true );
    }
    else if( !use_powerline_right )
    {
      oss << "#[fg=default,bg=default]";
    }
  }

  return oss.str();
}

<|endoftext|>