<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 "qgeoroutingmanagerengine.h"
#include "qgeoroutingmanagerengine_p.h"

QTM_BEGIN_NAMESPACE

/*!
    \class QGeoRoutingManagerEngine

    \brief The QGeoRoutingManagerEngine class provides an interface and
    convenience methods to implementers of QGeoServiceProvider plugins who want
    to provide access to geographic routing information.

    \ingroup maps-impl

    The QGeoRoutingManagerEngine class is used to define the service specific
    behaviour and metadata required by QGeoRoutingManager.

    Subclasses of QGeoRoutingManagerEngine need to provide an implementation of
    calculateRoute().

    In the default implementation, supportsRouteUpdates() returns false and
    updateRoute() returns a QGeoRouteReply object containing a
    QGeoRouteReply::UnsupportedOptionError.

    If the routing service supports updating routes as they are being
    travelled, the subclass should provide an implementation of updateRoute()
    and call setSupportsRouteUpdates(true) at some point in time before
    updateRoute() is called.

    The function setSeupportsRouteUpdates() is one of several functions which
    configure the reported capabilities of the engine.  If the capabilities
    of an engine differ from the default values these functions should be
    used so that the reported capabilies are accurate.

    It is important that this is done before calculateRoute(), updateRoute()
    or any of the capability reporting functions are used to prevent
    incorrect or inconsistent behaviour.

    \sa QGeoRoutingManager
*/

/*!
    Constructs a new engine with the specified \a parent, using \a parameters
    to pass any implementation specific data to the engine.
*/
QGeoRoutingManagerEngine::QGeoRoutingManagerEngine(const QMap<QString, QString> &parameters, QObject *parent)
        : QObject(parent),
        d_ptr(new QGeoRoutingManagerEnginePrivate(parameters)) {}

/*!
    Destroys this engine.
*/
QGeoRoutingManagerEngine::~QGeoRoutingManagerEngine()
{
    delete d_ptr;
}

/*!
    Sets the name which this engine implementation uses to distinguish itself
    from the implementations provided by other plugins to \a managerName.

    The combination of managerName() and managerVersion() should be unique
    amongst plugin implementations.
*/
void QGeoRoutingManagerEngine::setManagerName(const QString &managerName)
{
    d_ptr->managerName = managerName;
}

/*!
    Returns the name which this engine implementation uses to distinguish
    itself from the implementations provided by other plugins.

    The combination of managerName() and managerVersion() should be unique
    amongst plugin implementations.
*/
QString QGeoRoutingManagerEngine::managerName() const
{
    return d_ptr->managerName;
}

/*!
    Returns the parameters used in the creation of this engine object.
*/
QMap<QString, QString> QGeoRoutingManagerEngine::managerParameters() const
{
    return d_ptr->managerParameters;
}

/*!
    Sets the version of this engine implementation to \a managerVersion.

    The combination of managerName() and managerVersion() should be unique
    amongst plugin implementations.
*/
void QGeoRoutingManagerEngine::setManagerVersion(int managerVersion)
{
    d_ptr->managerVersion = managerVersion;
}

/*!
    Returns the version of this engine implementation.

    The combination of managerName() and managerVersion() should be unique
    amongst plugin implementations.
*/
int QGeoRoutingManagerEngine::managerVersion() const
{
    return d_ptr->managerVersion;
}

/*!
\fn QGeoRouteReply* QGeoRoutingManagerEngine::calculateRoute(const QGeoRouteRequest& request)

    Begins the calculation of the route specified by \a request.

    A QGeoRouteReply object will be returned, which can be used to manage the
    routing operation and to return the results of the operation.

    This engine and the returned QGeoRouteReply object will emit signals
    indicating if the operation completes or if errors occur.

    Once the operation has completed, QGeoRouteReply::routes can be used to
    retrieve the calculated route or routes.

    If \a request includes features which are not supported by this engine, as
    reported by the methods in this engine, then a
    QGeoRouteReply::UnsupportedOptionError will occur.

    The user is responsible for deleting the returned reply object, although
    this can be done in the slot connected to QGeoRoutingManagerEngine::finished(),
    QGeoRoutingManagerEngine::error(), QGeoRouteReply::finished() or
    QGeoRouteReply::error() with deleteLater().
*/

/*!
    Begins the process of updating \a route based on the current position \a
    position.

    A QGeoRouteReply object will be returned, which can be used to manage the
    routing operation and to return the results of the operation.

    This engine and the returned QGeoRouteReply object will emit signals
    indicating if the operation completes or if errors occur.

    If supportsRouteUpdates() returns false an
    QGeoRouteReply::UnsupportedOptionError will occur.

    Once the operation has completed, QGeoRouteReply::routes can be used to
    retrieve the updated route.

    The returned route could be entirely different to the original route,
    especially if \a position is far enough away from the initial route.
    Otherwise the route will be similar, although the remaining time and
    distance will be updated and any segments of the original route which
    have been traversed will be removed.

    The user is responsible for deleting the returned reply object, although
    this can be done in the slot connected to QGeoRoutingManagerEngine::finished(),
    QGeoRoutingManagerEngine::error(), QGeoRouteReply::finished() or
    QGeoRouteReply::error() with deleteLater().
*/
QGeoRouteReply* QGeoRoutingManagerEngine::updateRoute(const QGeoRoute &route, const QGeoCoordinate &position)
{
    Q_UNUSED(route)
    Q_UNUSED(position)
    return new QGeoRouteReply(QGeoRouteReply::UnsupportedOptionError,
                              "The updating of routes is not supported by this service provider.", this);
}

/*!
    Sets whether this engine supports updating routes to \a supported.

    It is important that subclasses use this method to ensure that the engine
    reports its capabilities correctly.  If this function is not used the
    engine will report that it does not support updating routes.
*/
void QGeoRoutingManagerEngine::setSupportsRouteUpdates(bool supported)
{
    d_ptr->supportsRouteUpdates = supported;
}

/*!
    Returns whether this engine supports updating routes.
*/
bool QGeoRoutingManagerEngine::supportsRouteUpdates() const
{
    return d_ptr->supportsRouteUpdates;
}

/*!
    Sets whether this engine supports request for alternative routes to \a supported.

    It is important that subclasses use this method to ensure that the engine
    reports its capabilities correctly.  If this function is not used the
    engine will report that it does not support alternative routes.
*/
void QGeoRoutingManagerEngine::setSupportsAlternativeRoutes(bool supported)
{
    d_ptr->supportsAlternativeRoutes = supported;
}

/*!
    Returns whether this engine supports request for alternative routes.
*/
bool QGeoRoutingManagerEngine::supportsAlternativeRoutes() const
{
    return d_ptr->supportsAlternativeRoutes;
}

/*!
    Sets the travel modes supported by this engine to \a travelModes.

    It is important that subclasses use this method to ensure that the engine
    reports its capabilities correctly.  If this function is not used the
    engine will report that it supports no travel modes at all.
*/
void QGeoRoutingManagerEngine::setSupportedTravelModes(QGeoRouteRequest::TravelModes travelModes)
{
    d_ptr->supportedTravelModes = travelModes;
}

/*!
    Returns the travel modes supported by this engine.
*/
QGeoRouteRequest::TravelModes QGeoRoutingManagerEngine::supportedTravelModes() const
{
    return d_ptr->supportedTravelModes;
}

/*!
    Sets the types of features that this engine can avoid during route planning to \a avoidFeatureTypes.

    It is important that subclasses use this method to ensure that the engine
    reports its capabilities correctly.  If this function is not used the
    engine will report that it does not support avoiding features.
*/
void QGeoRoutingManagerEngine::setSupportedAvoidFeatureTypes(QGeoRouteRequest::AvoidFeatureTypes avoidFeatureTypes)
{
    d_ptr->supportedAvoidFeatureTypes = avoidFeatureTypes;
}

/*!
    Returns the types of features that this engine can avoid during route planning.
*/
QGeoRouteRequest::AvoidFeatureTypes QGeoRoutingManagerEngine::supportedAvoidFeatureTypes() const
{
    return d_ptr->supportedAvoidFeatureTypes;
}

/*!
    Sets the route optimizations supported by this engine to \a optimizations.

    It is important that subclasses use this method to ensure that the engine
    reports its capabilities correctly.  If this function is not used the
    engine will report that it supports no route optimizations at all.
*/
void QGeoRoutingManagerEngine::setSupportedRouteOptimizations(QGeoRouteRequest::RouteOptimizations optimizations)
{
    d_ptr->supportedRouteOptimizations = optimizations;
}

/*!
    Returns the route optimizations supported by this engine.
*/
QGeoRouteRequest::RouteOptimizations QGeoRoutingManagerEngine::supportedRouteOptimizations() const
{
    return d_ptr->supportedRouteOptimizations;
}

/*!
    Sets the levels of detail for routing segments which can be
    requested by this engine to \a segmentDetails.

    It is important that subclasses use this method to ensure that the engine
    reports its capabilities correctly.  If this function is not used the
    engine will report that it supports no segment detail at all.
*/
void QGeoRoutingManagerEngine::setSupportedSegmentDetails(QGeoRouteRequest::SegmentDetails segmentDetails)
{
    d_ptr->supportedSegmentDetails = supportedSegmentDetails();
}

/*!
    Returns the levels of detail for routing segments which can be
    requested by this engine.
*/
QGeoRouteRequest::SegmentDetails QGeoRoutingManagerEngine::supportedSegmentDetails() const
{
    return d_ptr->supportedSegmentDetails;
}

/*!
    Sets the levels of detail for navigation instructions which can be
    requested by this engine to \a instructionDetails.

    It is important that subclasses use this method to ensure that the engine
    reports its capabilities correctly.  If this function is not used the
    engine will report that it supports no instruction detail at all.
*/
void QGeoRoutingManagerEngine::setSupportedInstructionDetails(QGeoRouteRequest::InstructionDetails instructionDetails)
{
    d_ptr->supportedInstructionDetails = instructionDetails;
}

/*!
    Returns the levels of detail for navigation instructions which can be
    requested by this engine.
*/
QGeoRouteRequest::InstructionDetails QGeoRoutingManagerEngine::supportedInstructionDetails() const
{
    return d_ptr->supportedInstructionDetails;
}

/*!
\fn void QGeoRoutingManagerEngine::finished(QGeoRouteReply* reply)

This signal is emitted when \a reply has finished processing.

If reply::error() equals QGeoRouteReply::NoError then the processing
finished successfully.

This signal and QGeoRouteReply::finished() will be emitted at the same time.

\note Do no delete the \a reply object in the slot connected to this signal.
Use deleteLater() instead.
*/

/*!
\fn void QGeoRoutingManagerEngine::error(QGeoRouteReply* reply, QGeoRouteReply::Error error, QString errorString)

This signal is emitted when an error has been detected in the processing of
\a reply.  The QGeoRoutingManagerEngine::finished() signal will probably follow.

The error will be described by the error code \a error.  If \a errorString is
not empty it will contain a textual description of the error.

This signal and QGeoRouteReply::error() will be emitted at the same time.

\note Do no delete the \a reply object in the slot connected to this signal.
Use deleteLater() instead.
*/

/*******************************************************************************
*******************************************************************************/

QGeoRoutingManagerEnginePrivate::QGeoRoutingManagerEnginePrivate(const QMap<QString, QString> &parameters)
        : managerParameters(parameters),
        managerVersion(-1),
        supportsRouteUpdates(false),
        supportsAlternativeRoutes(false) {}

QGeoRoutingManagerEnginePrivate::QGeoRoutingManagerEnginePrivate(const QGeoRoutingManagerEnginePrivate &other)
        : managerName(other.managerName),
        managerParameters(other.managerParameters),
        managerVersion(other.managerVersion),
        supportsRouteUpdates(other.supportsRouteUpdates),
        supportsAlternativeRoutes(other.supportsAlternativeRoutes),
        supportedTravelModes(other.supportedTravelModes),
        supportedAvoidFeatureTypes(other.supportedAvoidFeatureTypes),
        supportedRouteOptimizations(other.supportedRouteOptimizations),
        supportedSegmentDetails(other.supportedSegmentDetails),
        supportedInstructionDetails(other.supportedInstructionDetails) {}

QGeoRoutingManagerEnginePrivate::~QGeoRoutingManagerEnginePrivate() {}

QGeoRoutingManagerEnginePrivate& QGeoRoutingManagerEnginePrivate::operator= (const QGeoRoutingManagerEnginePrivate & other)
{
    managerName = other.managerName;
    managerParameters = other.managerParameters;
    managerVersion = other.managerVersion;
    supportsRouteUpdates = other.supportsRouteUpdates;
    supportsAlternativeRoutes = other.supportsAlternativeRoutes;
    supportedTravelModes = other.supportedTravelModes;
    supportedAvoidFeatureTypes = other.supportedAvoidFeatureTypes;
    supportedRouteOptimizations = other.supportedRouteOptimizations;
    supportedSegmentDetails = other.supportedSegmentDetails;
    supportedInstructionDetails = other.supportedInstructionDetails;

    return *this;
}

#include "moc_qgeoroutingmanagerengine.cpp"

QTM_END_NAMESPACE
<commit_msg>Fix QGeoRoutingManagerEngine::setSupportedSegmentDetails<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 "qgeoroutingmanagerengine.h"
#include "qgeoroutingmanagerengine_p.h"

QTM_BEGIN_NAMESPACE

/*!
    \class QGeoRoutingManagerEngine

    \brief The QGeoRoutingManagerEngine class provides an interface and
    convenience methods to implementers of QGeoServiceProvider plugins who want
    to provide access to geographic routing information.

    \ingroup maps-impl

    The QGeoRoutingManagerEngine class is used to define the service specific
    behaviour and metadata required by QGeoRoutingManager.

    Subclasses of QGeoRoutingManagerEngine need to provide an implementation of
    calculateRoute().

    In the default implementation, supportsRouteUpdates() returns false and
    updateRoute() returns a QGeoRouteReply object containing a
    QGeoRouteReply::UnsupportedOptionError.

    If the routing service supports updating routes as they are being
    travelled, the subclass should provide an implementation of updateRoute()
    and call setSupportsRouteUpdates(true) at some point in time before
    updateRoute() is called.

    The function setSeupportsRouteUpdates() is one of several functions which
    configure the reported capabilities of the engine.  If the capabilities
    of an engine differ from the default values these functions should be
    used so that the reported capabilies are accurate.

    It is important that this is done before calculateRoute(), updateRoute()
    or any of the capability reporting functions are used to prevent
    incorrect or inconsistent behaviour.

    \sa QGeoRoutingManager
*/

/*!
    Constructs a new engine with the specified \a parent, using \a parameters
    to pass any implementation specific data to the engine.
*/
QGeoRoutingManagerEngine::QGeoRoutingManagerEngine(const QMap<QString, QString> &parameters, QObject *parent)
        : QObject(parent),
        d_ptr(new QGeoRoutingManagerEnginePrivate(parameters)) {}

/*!
    Destroys this engine.
*/
QGeoRoutingManagerEngine::~QGeoRoutingManagerEngine()
{
    delete d_ptr;
}

/*!
    Sets the name which this engine implementation uses to distinguish itself
    from the implementations provided by other plugins to \a managerName.

    The combination of managerName() and managerVersion() should be unique
    amongst plugin implementations.
*/
void QGeoRoutingManagerEngine::setManagerName(const QString &managerName)
{
    d_ptr->managerName = managerName;
}

/*!
    Returns the name which this engine implementation uses to distinguish
    itself from the implementations provided by other plugins.

    The combination of managerName() and managerVersion() should be unique
    amongst plugin implementations.
*/
QString QGeoRoutingManagerEngine::managerName() const
{
    return d_ptr->managerName;
}

/*!
    Returns the parameters used in the creation of this engine object.
*/
QMap<QString, QString> QGeoRoutingManagerEngine::managerParameters() const
{
    return d_ptr->managerParameters;
}

/*!
    Sets the version of this engine implementation to \a managerVersion.

    The combination of managerName() and managerVersion() should be unique
    amongst plugin implementations.
*/
void QGeoRoutingManagerEngine::setManagerVersion(int managerVersion)
{
    d_ptr->managerVersion = managerVersion;
}

/*!
    Returns the version of this engine implementation.

    The combination of managerName() and managerVersion() should be unique
    amongst plugin implementations.
*/
int QGeoRoutingManagerEngine::managerVersion() const
{
    return d_ptr->managerVersion;
}

/*!
\fn QGeoRouteReply* QGeoRoutingManagerEngine::calculateRoute(const QGeoRouteRequest& request)

    Begins the calculation of the route specified by \a request.

    A QGeoRouteReply object will be returned, which can be used to manage the
    routing operation and to return the results of the operation.

    This engine and the returned QGeoRouteReply object will emit signals
    indicating if the operation completes or if errors occur.

    Once the operation has completed, QGeoRouteReply::routes can be used to
    retrieve the calculated route or routes.

    If \a request includes features which are not supported by this engine, as
    reported by the methods in this engine, then a
    QGeoRouteReply::UnsupportedOptionError will occur.

    The user is responsible for deleting the returned reply object, although
    this can be done in the slot connected to QGeoRoutingManagerEngine::finished(),
    QGeoRoutingManagerEngine::error(), QGeoRouteReply::finished() or
    QGeoRouteReply::error() with deleteLater().
*/

/*!
    Begins the process of updating \a route based on the current position \a
    position.

    A QGeoRouteReply object will be returned, which can be used to manage the
    routing operation and to return the results of the operation.

    This engine and the returned QGeoRouteReply object will emit signals
    indicating if the operation completes or if errors occur.

    If supportsRouteUpdates() returns false an
    QGeoRouteReply::UnsupportedOptionError will occur.

    Once the operation has completed, QGeoRouteReply::routes can be used to
    retrieve the updated route.

    The returned route could be entirely different to the original route,
    especially if \a position is far enough away from the initial route.
    Otherwise the route will be similar, although the remaining time and
    distance will be updated and any segments of the original route which
    have been traversed will be removed.

    The user is responsible for deleting the returned reply object, although
    this can be done in the slot connected to QGeoRoutingManagerEngine::finished(),
    QGeoRoutingManagerEngine::error(), QGeoRouteReply::finished() or
    QGeoRouteReply::error() with deleteLater().
*/
QGeoRouteReply* QGeoRoutingManagerEngine::updateRoute(const QGeoRoute &route, const QGeoCoordinate &position)
{
    Q_UNUSED(route)
    Q_UNUSED(position)
    return new QGeoRouteReply(QGeoRouteReply::UnsupportedOptionError,
                              "The updating of routes is not supported by this service provider.", this);
}

/*!
    Sets whether this engine supports updating routes to \a supported.

    It is important that subclasses use this method to ensure that the engine
    reports its capabilities correctly.  If this function is not used the
    engine will report that it does not support updating routes.
*/
void QGeoRoutingManagerEngine::setSupportsRouteUpdates(bool supported)
{
    d_ptr->supportsRouteUpdates = supported;
}

/*!
    Returns whether this engine supports updating routes.
*/
bool QGeoRoutingManagerEngine::supportsRouteUpdates() const
{
    return d_ptr->supportsRouteUpdates;
}

/*!
    Sets whether this engine supports request for alternative routes to \a supported.

    It is important that subclasses use this method to ensure that the engine
    reports its capabilities correctly.  If this function is not used the
    engine will report that it does not support alternative routes.
*/
void QGeoRoutingManagerEngine::setSupportsAlternativeRoutes(bool supported)
{
    d_ptr->supportsAlternativeRoutes = supported;
}

/*!
    Returns whether this engine supports request for alternative routes.
*/
bool QGeoRoutingManagerEngine::supportsAlternativeRoutes() const
{
    return d_ptr->supportsAlternativeRoutes;
}

/*!
    Sets the travel modes supported by this engine to \a travelModes.

    It is important that subclasses use this method to ensure that the engine
    reports its capabilities correctly.  If this function is not used the
    engine will report that it supports no travel modes at all.
*/
void QGeoRoutingManagerEngine::setSupportedTravelModes(QGeoRouteRequest::TravelModes travelModes)
{
    d_ptr->supportedTravelModes = travelModes;
}

/*!
    Returns the travel modes supported by this engine.
*/
QGeoRouteRequest::TravelModes QGeoRoutingManagerEngine::supportedTravelModes() const
{
    return d_ptr->supportedTravelModes;
}

/*!
    Sets the types of features that this engine can avoid during route planning to \a avoidFeatureTypes.

    It is important that subclasses use this method to ensure that the engine
    reports its capabilities correctly.  If this function is not used the
    engine will report that it does not support avoiding features.
*/
void QGeoRoutingManagerEngine::setSupportedAvoidFeatureTypes(QGeoRouteRequest::AvoidFeatureTypes avoidFeatureTypes)
{
    d_ptr->supportedAvoidFeatureTypes = avoidFeatureTypes;
}

/*!
    Returns the types of features that this engine can avoid during route planning.
*/
QGeoRouteRequest::AvoidFeatureTypes QGeoRoutingManagerEngine::supportedAvoidFeatureTypes() const
{
    return d_ptr->supportedAvoidFeatureTypes;
}

/*!
    Sets the route optimizations supported by this engine to \a optimizations.

    It is important that subclasses use this method to ensure that the engine
    reports its capabilities correctly.  If this function is not used the
    engine will report that it supports no route optimizations at all.
*/
void QGeoRoutingManagerEngine::setSupportedRouteOptimizations(QGeoRouteRequest::RouteOptimizations optimizations)
{
    d_ptr->supportedRouteOptimizations = optimizations;
}

/*!
    Returns the route optimizations supported by this engine.
*/
QGeoRouteRequest::RouteOptimizations QGeoRoutingManagerEngine::supportedRouteOptimizations() const
{
    return d_ptr->supportedRouteOptimizations;
}

/*!
    Sets the levels of detail for routing segments which can be
    requested by this engine to \a segmentDetails.

    It is important that subclasses use this method to ensure that the engine
    reports its capabilities correctly.  If this function is not used the
    engine will report that it supports no segment detail at all.
*/
void QGeoRoutingManagerEngine::setSupportedSegmentDetails(QGeoRouteRequest::SegmentDetails segmentDetails)
{
    d_ptr->supportedSegmentDetails = segmentDetails;
}

/*!
    Returns the levels of detail for routing segments which can be
    requested by this engine.
*/
QGeoRouteRequest::SegmentDetails QGeoRoutingManagerEngine::supportedSegmentDetails() const
{
    return d_ptr->supportedSegmentDetails;
}

/*!
    Sets the levels of detail for navigation instructions which can be
    requested by this engine to \a instructionDetails.

    It is important that subclasses use this method to ensure that the engine
    reports its capabilities correctly.  If this function is not used the
    engine will report that it supports no instruction detail at all.
*/
void QGeoRoutingManagerEngine::setSupportedInstructionDetails(QGeoRouteRequest::InstructionDetails instructionDetails)
{
    d_ptr->supportedInstructionDetails = instructionDetails;
}

/*!
    Returns the levels of detail for navigation instructions which can be
    requested by this engine.
*/
QGeoRouteRequest::InstructionDetails QGeoRoutingManagerEngine::supportedInstructionDetails() const
{
    return d_ptr->supportedInstructionDetails;
}

/*!
\fn void QGeoRoutingManagerEngine::finished(QGeoRouteReply* reply)

This signal is emitted when \a reply has finished processing.

If reply::error() equals QGeoRouteReply::NoError then the processing
finished successfully.

This signal and QGeoRouteReply::finished() will be emitted at the same time.

\note Do no delete the \a reply object in the slot connected to this signal.
Use deleteLater() instead.
*/

/*!
\fn void QGeoRoutingManagerEngine::error(QGeoRouteReply* reply, QGeoRouteReply::Error error, QString errorString)

This signal is emitted when an error has been detected in the processing of
\a reply.  The QGeoRoutingManagerEngine::finished() signal will probably follow.

The error will be described by the error code \a error.  If \a errorString is
not empty it will contain a textual description of the error.

This signal and QGeoRouteReply::error() will be emitted at the same time.

\note Do no delete the \a reply object in the slot connected to this signal.
Use deleteLater() instead.
*/

/*******************************************************************************
*******************************************************************************/

QGeoRoutingManagerEnginePrivate::QGeoRoutingManagerEnginePrivate(const QMap<QString, QString> &parameters)
        : managerParameters(parameters),
        managerVersion(-1),
        supportsRouteUpdates(false),
        supportsAlternativeRoutes(false) {}

QGeoRoutingManagerEnginePrivate::QGeoRoutingManagerEnginePrivate(const QGeoRoutingManagerEnginePrivate &other)
        : managerName(other.managerName),
        managerParameters(other.managerParameters),
        managerVersion(other.managerVersion),
        supportsRouteUpdates(other.supportsRouteUpdates),
        supportsAlternativeRoutes(other.supportsAlternativeRoutes),
        supportedTravelModes(other.supportedTravelModes),
        supportedAvoidFeatureTypes(other.supportedAvoidFeatureTypes),
        supportedRouteOptimizations(other.supportedRouteOptimizations),
        supportedSegmentDetails(other.supportedSegmentDetails),
        supportedInstructionDetails(other.supportedInstructionDetails) {}

QGeoRoutingManagerEnginePrivate::~QGeoRoutingManagerEnginePrivate() {}

QGeoRoutingManagerEnginePrivate& QGeoRoutingManagerEnginePrivate::operator= (const QGeoRoutingManagerEnginePrivate & other)
{
    managerName = other.managerName;
    managerParameters = other.managerParameters;
    managerVersion = other.managerVersion;
    supportsRouteUpdates = other.supportsRouteUpdates;
    supportsAlternativeRoutes = other.supportsAlternativeRoutes;
    supportedTravelModes = other.supportedTravelModes;
    supportedAvoidFeatureTypes = other.supportedAvoidFeatureTypes;
    supportedRouteOptimizations = other.supportedRouteOptimizations;
    supportedSegmentDetails = other.supportedSegmentDetails;
    supportedInstructionDetails = other.supportedInstructionDetails;

    return *this;
}

#include "moc_qgeoroutingmanagerengine.cpp"

QTM_END_NAMESPACE
<|endoftext|>


<commit_before>#pragma once

#include <string>
#include <unordered_map>

namespace AnyODE {
    template<class T> void ignore( const T& ) { } // ignore compiler warnings about unused parameter

    enum class Status : int {success = 0, recoverable_error = 1, unrecoverable_error = -1};

    struct OdeSysBase {
        void * integrator = nullptr;
        std::unordered_map<std::string, int> last_integration_info;

        virtual ~OdeSysBase() {}
        virtual int get_ny() const = 0;
        virtual int get_mlower() const { return -1; } // -1 denotes "not banded"
        virtual int get_mupper() const { return -1; } // -1 denotes "not banded"
        virtual int get_nroots() const { return 0; } // Do not look for roots by default;

        virtual Status rhs(double t, const double * const y, double * const f) = 0;
        virtual Status roots(double xval, const double * const y, double * const out) {
            ignore(xval); ignore(y); ignore(out);
            return Status::unrecoverable_error;
        }
        virtual Status dense_jac_cmaj(double t,
                                    const double * const __restrict__ y,
                                    const double * const __restrict__ fy,
                                    double * const __restrict__ jac,
                                    long int ldim){
            ignore(t); ignore(y); ignore(fy); ignore(jac); ignore(ldim);
            return Status::unrecoverable_error;
        }
        virtual Status banded_jac_cmaj(double t,
                                       const double * const __restrict__ y,
                                       const double * const __restrict__ fy,
                                       double * const __restrict__ jac,
                                       long int ldim){
            ignore(t); ignore(y); ignore(fy); ignore(jac); ignore(ldim);
            throw std::runtime_error("banded_jac_cmaj not implemented.");
            return Status::unrecoverable_error;
        }
        virtual Status jac_times_vec(const double * const __restrict__ vec,
                                     double * const __restrict__ out,
                                     double t,
                                     const double * const __restrict__ y,
                                     const double * const __restrict__ fy
                                     )
        {
            ignore(vec);
            ignore(out);
            ignore(t);
            ignore(y);
            ignore(fy);
            return Status::unrecoverable_error;
        }
        virtual Status prec_setup(double t,
                                const double * const __restrict__ y,
                                const double * const __restrict__ fy,
                                bool jok,
                                bool& jac_recomputed,
                                double gamma)
        {
            ignore(t);
            ignore(y);
            ignore(fy);
            ignore(jok);
            ignore(jac_recomputed);
            ignore(gamma);
            return Status::unrecoverable_error;
        }
        virtual Status prec_solve_left(const double t,
                                       const double * const __restrict__ y,
                                       const double * const __restrict__ fy,
                                       const double * const __restrict__ r,
                                       double * const __restrict__ z,
                                       double gamma,
                                       double delta,
                                       const double * const __restrict__ ewt)
        {
            ignore(t);
            ignore(y);
            ignore(fy);
            ignore(r);
            ignore(z);
            ignore(gamma);
            ignore(delta);
            ignore(ewt);
            return Status::unrecoverable_error;
        }
    };
}
<commit_msg>Add dense_jac_rmaj<commit_after>#pragma once

#include <string>
#include <unordered_map>

namespace AnyODE {
    template<class T> void ignore( const T& ) { } // ignore compiler warnings about unused parameter

    enum class Status : int {success = 0, recoverable_error = 1, unrecoverable_error = -1};

    struct OdeSysBase {
        void * integrator = nullptr;
        std::unordered_map<std::string, int> last_integration_info;

        virtual ~OdeSysBase() {}
        virtual int get_ny() const = 0;
        virtual int get_mlower() const { return -1; } // -1 denotes "not banded"
        virtual int get_mupper() const { return -1; } // -1 denotes "not banded"
        virtual int get_nroots() const { return 0; } // Do not look for roots by default;

        virtual Status rhs(double t, const double * const y, double * const f) = 0;
        virtual Status roots(double xval, const double * const y, double * const out) {
            ignore(xval); ignore(y); ignore(out);
            return Status::unrecoverable_error;
        }
        virtual Status dense_jac_cmaj(double t,
                                    const double * const __restrict__ y,
                                    const double * const __restrict__ fy,
                                    double * const __restrict__ jac,
                                    long int ldim){
            ignore(t); ignore(y); ignore(fy); ignore(jac); ignore(ldim);
            return Status::unrecoverable_error;
        }
        virtual Status dense_jac_rmaj(double t,
                                    const double * const __restrict__ y,
                                    const double * const __restrict__ fy,
                                    double * const __restrict__ jac,
                                    long int ldim){
            ignore(t); ignore(y); ignore(fy); ignore(jac); ignore(ldim);
            return Status::unrecoverable_error;
        }
        virtual Status banded_jac_cmaj(double t,
                                       const double * const __restrict__ y,
                                       const double * const __restrict__ fy,
                                       double * const __restrict__ jac,
                                       long int ldim){
            ignore(t); ignore(y); ignore(fy); ignore(jac); ignore(ldim);
            throw std::runtime_error("banded_jac_cmaj not implemented.");
            return Status::unrecoverable_error;
        }
        virtual Status jac_times_vec(const double * const __restrict__ vec,
                                     double * const __restrict__ out,
                                     double t,
                                     const double * const __restrict__ y,
                                     const double * const __restrict__ fy
                                     )
        {
            ignore(vec);
            ignore(out);
            ignore(t);
            ignore(y);
            ignore(fy);
            return Status::unrecoverable_error;
        }
        virtual Status prec_setup(double t,
                                const double * const __restrict__ y,
                                const double * const __restrict__ fy,
                                bool jok,
                                bool& jac_recomputed,
                                double gamma)
        {
            ignore(t);
            ignore(y);
            ignore(fy);
            ignore(jok);
            ignore(jac_recomputed);
            ignore(gamma);
            return Status::unrecoverable_error;
        }
        virtual Status prec_solve_left(const double t,
                                       const double * const __restrict__ y,
                                       const double * const __restrict__ fy,
                                       const double * const __restrict__ r,
                                       double * const __restrict__ z,
                                       double gamma,
                                       double delta,
                                       const double * const __restrict__ ewt)
        {
            ignore(t);
            ignore(y);
            ignore(fy);
            ignore(r);
            ignore(z);
            ignore(gamma);
            ignore(delta);
            ignore(ewt);
            return Status::unrecoverable_error;
        }
    };
}
<|endoftext|>


<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * Flacon - audio File Encoder
 * https://github.com/flacon/flacon
 *
 * Copyright: 2012-2013
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.

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

 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "splitter.h"
#include "disc.h"
#include "decoder.h"

#include <QDebug>

/************************************************
 *
 ************************************************/
Splitter::Splitter(const Disc *disc, const QString &workDir, bool extractPregap, PreGapType preGapType, QObject *parent):
    Worker(parent),
    mDisc(disc),
    mWorkDir(workDir),
    mExtractPregap(extractPregap),
    mPreGapType(preGapType)
{
}

/************************************************
 *
 ************************************************/
void Splitter::run()
{
    static QAtomicInteger<quint64> globalUid(1);
    QString uid = QString("%1").arg(globalUid.fetchAndAddRelaxed(1), 4, 10, QLatin1Char('0'));

    mCurrentTrack = nullptr;
    Decoder decoder;

    try
    {
        decoder.open(mDisc->audioFileName());
    }
    catch (FlaconError &err)
    {
        emit error(mTracks.first(),
              tr("I can't read %1:
%2",
                 "Splitter error. %1 is a file name, %2 is a system error text.")
              .arg(mDisc->audioFileName())
              .arg(err.what()));
        return;
    }

    // Extract pregap to separate file ....................
    if (mExtractPregap)
    {
        mCurrentTrack  = mDisc->preGapTrack();
        CueIndex start = mDisc->track(0)->cueIndex(0);
        CueIndex end   = mDisc->track(0)->cueIndex(1);
        QString outFileName = QString("%1/pregap-%2.wav").arg(mWorkDir).arg(uid);

        try
        {
            decoder.extract(start, end, outFileName);
        }
        catch (FlaconError &err)
        {
            qWarning() << "Splitter error for pregap track : " <<  err.what();
            deleteFile(outFileName);
            emit error(mCurrentTrack, err.what());
            return;
        }

        emit trackReady(mCurrentTrack, outFileName);
    }
    // Extract pregap to separate file ....................

    // We havn't pregap in the GUI and pregap is short so we suppress progress for pregap track
    connect(&decoder, SIGNAL(progress(int)),
            this, SLOT(decoderProgress(int)));

    qDebug() << "Start splitting" << mDisc->count() << "tracks from" << mDisc->audioFileName();
    for (int i=0; i<mDisc->count(); ++i)
    {
        mCurrentTrack = mDisc->track(i);
        if (!mTracks.contains(mCurrentTrack))
            continue;

        QString outFileName = QString("%1/track-%2_%3.wav").arg(mWorkDir).arg(uid).arg(i+1, 2, 10, QLatin1Char('0'));

        CueIndex start, end;
        if (i==0 && mPreGapType == PreGapType::AddToFirstTrack)
            start = CueTime("00:00:00");
        else
            start = mDisc->track(i)->cueIndex(1);

        if (i<mDisc->count()-1)
            end = mDisc->track(i+1)->cueIndex(01);

        try
        {
            decoder.extract(start, end, outFileName);
        }
        catch (FlaconError &err)
        {
            qWarning() << "Splitter error for track " << mCurrentTrack->trackNum() << ": " <<  err.what();
            deleteFile(outFileName);
            emit error(mCurrentTrack, err.what());

        }

        qDebug() << "Splitter trackReady:" << *mCurrentTrack << outFileName;
        emit trackReady(mCurrentTrack, outFileName);
    }
}

/************************************************
 *
 ************************************************/
void Splitter::decoderProgress(int percent)
{
    emit trackProgress(mCurrentTrack, TrackState::Splitting, percent);
}
<commit_msg>Close issue #127: Does not build on platforms without 64-bit atomics support<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * Flacon - audio File Encoder
 * https://github.com/flacon/flacon
 *
 * Copyright: 2012-2013
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.

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

 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "splitter.h"
#include "disc.h"
#include "decoder.h"

#include <QDebug>

/************************************************
 *
 ************************************************/
Splitter::Splitter(const Disc *disc, const QString &workDir, bool extractPregap, PreGapType preGapType, QObject *parent):
    Worker(parent),
    mDisc(disc),
    mWorkDir(workDir),
    mExtractPregap(extractPregap),
    mPreGapType(preGapType)
{
}

/************************************************
 *
 ************************************************/
void Splitter::run()
{
    static QAtomicInteger<quint32> globalUid(1);
    QString uid = QString("%1").arg(globalUid.fetchAndAddRelaxed(1), 4, 10, QLatin1Char('0'));

    mCurrentTrack = nullptr;
    Decoder decoder;

    try
    {
        decoder.open(mDisc->audioFileName());
    }
    catch (FlaconError &err)
    {
        emit error(mTracks.first(),
              tr("I can't read %1:
%2",
                 "Splitter error. %1 is a file name, %2 is a system error text.")
              .arg(mDisc->audioFileName())
              .arg(err.what()));
        return;
    }

    // Extract pregap to separate file ....................
    if (mExtractPregap)
    {
        mCurrentTrack  = mDisc->preGapTrack();
        CueIndex start = mDisc->track(0)->cueIndex(0);
        CueIndex end   = mDisc->track(0)->cueIndex(1);
        QString outFileName = QString("%1/pregap-%2.wav").arg(mWorkDir).arg(uid);

        try
        {
            decoder.extract(start, end, outFileName);
        }
        catch (FlaconError &err)
        {
            qWarning() << "Splitter error for pregap track : " <<  err.what();
            deleteFile(outFileName);
            emit error(mCurrentTrack, err.what());
            return;
        }

        emit trackReady(mCurrentTrack, outFileName);
    }
    // Extract pregap to separate file ....................

    // We havn't pregap in the GUI and pregap is short so we suppress progress for pregap track
    connect(&decoder, SIGNAL(progress(int)),
            this, SLOT(decoderProgress(int)));

    qDebug() << "Start splitting" << mDisc->count() << "tracks from" << mDisc->audioFileName();
    for (int i=0; i<mDisc->count(); ++i)
    {
        mCurrentTrack = mDisc->track(i);
        if (!mTracks.contains(mCurrentTrack))
            continue;

        QString outFileName = QString("%1/track-%2_%3.wav").arg(mWorkDir).arg(uid).arg(i+1, 2, 10, QLatin1Char('0'));

        CueIndex start, end;
        if (i==0 && mPreGapType == PreGapType::AddToFirstTrack)
            start = CueTime("00:00:00");
        else
            start = mDisc->track(i)->cueIndex(1);

        if (i<mDisc->count()-1)
            end = mDisc->track(i+1)->cueIndex(01);

        try
        {
            decoder.extract(start, end, outFileName);
        }
        catch (FlaconError &err)
        {
            qWarning() << "Splitter error for track " << mCurrentTrack->trackNum() << ": " <<  err.what();
            deleteFile(outFileName);
            emit error(mCurrentTrack, err.what());

        }

        qDebug() << "Splitter trackReady:" << *mCurrentTrack << outFileName;
        emit trackReady(mCurrentTrack, outFileName);
    }
}

/************************************************
 *
 ************************************************/
void Splitter::decoderProgress(int percent)
{
    emit trackProgress(mCurrentTrack, TrackState::Splitting, percent);
}
<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
  Arduino library to control a wide variety of WS2811- and WS2812-based RGB
  LED devices such as Adafruit FLORA RGB Smart Pixels and NeoPixel strips.
  Currently handles 400 and 800 KHz bitstreams on 8, 12 and 16 MHz ATmega
  MCUs, with LEDs wired for various color orders.  Handles most output pins
  (possible exception with upper PORT registers on the Arduino Mega).

  Written by Phil Burgess / Paint Your Dragon for Adafruit Industries,
  contributions by PJRC, Michael Miller and other members of the open
  source community.

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing products
  from Adafruit!

  -------------------------------------------------------------------------
  This file is part of the Adafruit NeoPixel library.

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

  NeoPixel 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 NeoPixel.  If not, see
  <http://www.gnu.org/licenses/>.

 - Ported v1.1.6 for Nol.A-SDK by Jongsoo Jeong (CoXlab Inc.)
  -------------------------------------------------------------------------*/

#include "Adafruit_NeoPixel.hpp"

// Constructor when length, pin and type are known at compile-time:
Adafruit_NeoPixel::Adafruit_NeoPixel(uint16_t n, uint8_t p, neoPixelType t) :
  begun(false), brightness(0), pixels(NULL), endTime(0)
{
  updateType(t);
  updateLength(n);
  setPin(p);
}

// via Michael Vogt/neophob: empty constructor is used when strand length
// isn't known at compile-time; situations where program config might be
// read from internal flash memory or an SD card, or arrive via serial
// command.  If using this constructor, MUST follow up with updateType(),
// updateLength(), etc. to establish the strand type, length and pin number!
Adafruit_NeoPixel::Adafruit_NeoPixel() :
  is800KHz(true),
  begun(false), numLEDs(0), numBytes(0), pin(-1), brightness(0), pixels(NULL),
  rOffset(1), gOffset(0), bOffset(2), wOffset(1), endTime(0)
{
}

Adafruit_NeoPixel::~Adafruit_NeoPixel() {
  if(pixels)   free(pixels);
  if(pin >= 0) pinMode(pin, INPUT);
}

void Adafruit_NeoPixel::begin(void) {
  if(pin >= 0) {
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW);
  }
  begun = true;

}

void Adafruit_NeoPixel::updateLength(uint16_t n) {
  if(pixels) free(pixels); // Free existing data (if any)

  // Allocate new data -- note: ALL PIXELS ARE CLEARED
  numBytes = n * ((wOffset == rOffset) ? 3 : 4);
  if((pixels = (uint8_t *)malloc(numBytes))) {
    memset(pixels, 0, numBytes);
    numLEDs = n;
  } else {
    numLEDs = numBytes = 0;
  }
}

void Adafruit_NeoPixel::updateType(neoPixelType t) {
  boolean oldThreeBytesPerPixel = (wOffset == rOffset); // false if RGBW

  wOffset = (t >> 6) & 0b11; // See notes in header file
  rOffset = (t >> 4) & 0b11; // regarding R/G/B/W offsets
  gOffset = (t >> 2) & 0b11;
  bOffset =  t       & 0b11;
  is800KHz = (t < 256);      // 400 KHz flag is 1<<8

  // If bytes-per-pixel has changed (and pixel data was previously
  // allocated), re-allocate to new size.  Will clear any data.
  if(pixels) {
    boolean newThreeBytesPerPixel = (wOffset == rOffset);
    if(newThreeBytesPerPixel != oldThreeBytesPerPixel) updateLength(numLEDs);
  }
}

void Adafruit_NeoPixel::show(void) {
  if(!pixels) return;

  while(!canShow());

  uint8_t *p, *end, pix, mask;
  uint32_t t, time0, time1, period, startTime; //in unit of ticks

  p = pixels;
  end = p + numBytes;
  pix = *p++;
  mask = 0x80;

  if (is800KHz) {
    time0  = System.ClockHz / 2500000;
    time1  = System.ClockHz / 1250000;
    period = System.ClockHz / 8000000;
  } else {
    time0  = System.ClockHz / 2000000;
    time1  = System.ClockHz / 833333;
    period = System.ClockHz / 400000;
  }

  while (System.MaxCycleCount - System.getCycleCount() < numBytes * period * 8) {
    // To avoid time overlap.
    System.feedWatchdog();
  }

  noInterrupts();
  for(;;) {
    if(pix & mask) {
      t = time1;
    } else {
      t = time0;
    }

    startTime = System.getCycleCount();
    digitalWrite(pin, HIGH);
    uint32_t highTime = (startTime + t) & System.MaxCycleCount;
    while (System.getCycleCount() < highTime);

    digitalWrite(pin, LOW);
    uint32_t lowTime = (startTime + period) & System.MaxCycleCount;
    while (System.getCycleCount() < lowTime);

    if(!(mask >>= 1)) {
      if(p >= end) break;
      pix  = *p++;
      mask = 0x80;
    }
  }
  interrupts();
}

// Set the output pin number
void Adafruit_NeoPixel::setPin(uint8_t p) {
  if(begun && (pin >= 0)) pinMode(pin, INPUT);
    pin = p;
    if(begun) {
      pinMode(p, OUTPUT);
      digitalWrite(p, LOW);
    }
}

// Set pixel color from separate R,G,B components:
void Adafruit_NeoPixel::setPixelColor(
 uint16_t n, uint8_t r, uint8_t g, uint8_t b) {

  if(n < numLEDs) {
    if(brightness) { // See notes in setBrightness()
      r = (r * brightness) >> 8;
      g = (g * brightness) >> 8;
      b = (b * brightness) >> 8;
    }
    uint8_t *p;
    if(wOffset == rOffset) { // Is an RGB-type strip
      p = &pixels[n * 3];    // 3 bytes per pixel
    } else {                 // Is a WRGB-type strip
      p = &pixels[n * 4];    // 4 bytes per pixel
      p[wOffset] = 0;        // But only R,G,B passed -- set W to 0
    }
    p[rOffset] = r;          // R,G,B always stored
    p[gOffset] = g;
    p[bOffset] = b;
  }
}

void Adafruit_NeoPixel::setPixelColor(
 uint16_t n, uint8_t r, uint8_t g, uint8_t b, uint8_t w) {

  if(n < numLEDs) {
    if(brightness) { // See notes in setBrightness()
      r = (r * brightness) >> 8;
      g = (g * brightness) >> 8;
      b = (b * brightness) >> 8;
      w = (w * brightness) >> 8;
    }
    uint8_t *p;
    if(wOffset == rOffset) { // Is an RGB-type strip
      p = &pixels[n * 3];    // 3 bytes per pixel (ignore W)
    } else {                 // Is a WRGB-type strip
      p = &pixels[n * 4];    // 4 bytes per pixel
      p[wOffset] = w;        // Store W
    }
    p[rOffset] = r;          // Store R,G,B
    p[gOffset] = g;
    p[bOffset] = b;
  }
}

// Set pixel color from 'packed' 32-bit RGB color:
void Adafruit_NeoPixel::setPixelColor(uint16_t n, uint32_t c) {
  if(n < numLEDs) {
    uint8_t *p,
      r = (uint8_t)(c >> 16),
      g = (uint8_t)(c >>  8),
      b = (uint8_t)c;
    if(brightness) { // See notes in setBrightness()
      r = (r * brightness) >> 8;
      g = (g * brightness) >> 8;
      b = (b * brightness) >> 8;
    }
    if(wOffset == rOffset) {
      p = &pixels[n * 3];
    } else {
      p = &pixels[n * 4];
      uint8_t w = (uint8_t)(c >> 24);
      p[wOffset] = brightness ? ((w * brightness) >> 8) : w;
    }
    p[rOffset] = r;
    p[gOffset] = g;
    p[bOffset] = b;
  }
}

// Convert separate R,G,B into packed 32-bit RGB color.
// Packed format is always RGB, regardless of LED strand color order.
uint32_t Adafruit_NeoPixel::Color(uint8_t r, uint8_t g, uint8_t b) {
  return ((uint32_t)r << 16) | ((uint32_t)g <<  8) | b;
}

// Convert separate R,G,B,W into packed 32-bit WRGB color.
// Packed format is always WRGB, regardless of LED strand color order.
uint32_t Adafruit_NeoPixel::Color(uint8_t r, uint8_t g, uint8_t b, uint8_t w) {
  return ((uint32_t)w << 24) | ((uint32_t)r << 16) | ((uint32_t)g <<  8) | b;
}

// Query color from previously-set pixel (returns packed 32-bit RGB value)
uint32_t Adafruit_NeoPixel::getPixelColor(uint16_t n) const {
  if(n >= numLEDs) return 0; // Out of bounds, return no color.

  uint8_t *p;

  if(wOffset == rOffset) { // Is RGB-type device
    p = &pixels[n * 3];
    if(brightness) {
      // Stored color was decimated by setBrightness().  Returned value
      // attempts to scale back to an approximation of the original 24-bit
      // value used when setting the pixel color, but there will always be
      // some error -- those bits are simply gone.  Issue is most
      // pronounced at low brightness levels.
      return (((uint32_t)(p[rOffset] << 8) / brightness) << 16) |
             (((uint32_t)(p[gOffset] << 8) / brightness) <<  8) |
             ( (uint32_t)(p[bOffset] << 8) / brightness       );
    } else {
      // No brightness adjustment has been made -- return 'raw' color
      return ((uint32_t)p[rOffset] << 16) |
             ((uint32_t)p[gOffset] <<  8) |
              (uint32_t)p[bOffset];
    }
  } else {                 // Is RGBW-type device
    p = &pixels[n * 4];
    if(brightness) { // Return scaled color
      return (((uint32_t)(p[wOffset] << 8) / brightness) << 24) |
             (((uint32_t)(p[rOffset] << 8) / brightness) << 16) |
             (((uint32_t)(p[gOffset] << 8) / brightness) <<  8) |
             ( (uint32_t)(p[bOffset] << 8) / brightness       );
    } else { // Return raw color
      return ((uint32_t)p[wOffset] << 24) |
             ((uint32_t)p[rOffset] << 16) |
             ((uint32_t)p[gOffset] <<  8) |
              (uint32_t)p[bOffset];
    }
  }
}

// Returns pointer to pixels[] array.  Pixel data is stored in device-
// native format and is not translated here.  Application will need to be
// aware of specific pixel data format and handle colors appropriately.
uint8_t *Adafruit_NeoPixel::getPixels(void) const {
  return pixels;
}

uint16_t Adafruit_NeoPixel::numPixels(void) const {
  return numLEDs;
}

// Adjust output brightness; 0=darkest (off), 255=brightest.  This does
// NOT immediately affect what's currently displayed on the LEDs.  The
// next call to show() will refresh the LEDs at this level.  However,
// this process is potentially "lossy," especially when increasing
// brightness.  The tight timing in the WS2811/WS2812 code means there
// aren't enough free cycles to perform this scaling on the fly as data
// is issued.  So we make a pass through the existing color data in RAM
// and scale it (subsequent graphics commands also work at this
// brightness level).  If there's a significant step up in brightness,
// the limited number of steps (quantization) in the old data will be
// quite visible in the re-scaled version.  For a non-destructive
// change, you'll need to re-render the full strip data.  C'est la vie.
void Adafruit_NeoPixel::setBrightness(uint8_t b) {
  // Stored brightness value is different than what's passed.
  // This simplifies the actual scaling math later, allowing a fast
  // 8x8-bit multiply and taking the MSB.  'brightness' is a uint8_t,
  // adding 1 here may (intentionally) roll over...so 0 = max brightness
  // (color values are interpreted literally; no scaling), 1 = min
  // brightness (off), 255 = just below max brightness.
  uint8_t newBrightness = b + 1;
  if(newBrightness != brightness) { // Compare against prior value
    // Brightness has changed -- re-scale existing data in RAM
    uint8_t  c,
            *ptr           = pixels,
             oldBrightness = brightness - 1; // De-wrap old brightness value
    uint16_t scale;
    if(oldBrightness == 0) scale = 0; // Avoid /0
    else if(b == 255) scale = 65535 / oldBrightness;
    else scale = (((uint16_t)newBrightness << 8) - 1) / oldBrightness;
    for(uint16_t i=0; i<numBytes; i++) {
      c      = *ptr;
      *ptr++ = (c * scale) >> 8;
    }
    brightness = newBrightness;
  }
}

//Return the brightness value
uint8_t Adafruit_NeoPixel::getBrightness(void) const {
  return brightness - 1;
}

void Adafruit_NeoPixel::clear() {
  memset(pixels, 0, numBytes);
}
<commit_msg>PNK-1 Fixed to use System.waitCycle().<commit_after>/*-------------------------------------------------------------------------
  Arduino library to control a wide variety of WS2811- and WS2812-based RGB
  LED devices such as Adafruit FLORA RGB Smart Pixels and NeoPixel strips.
  Currently handles 400 and 800 KHz bitstreams on 8, 12 and 16 MHz ATmega
  MCUs, with LEDs wired for various color orders.  Handles most output pins
  (possible exception with upper PORT registers on the Arduino Mega).

  Written by Phil Burgess / Paint Your Dragon for Adafruit Industries,
  contributions by PJRC, Michael Miller and other members of the open
  source community.

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing products
  from Adafruit!

  -------------------------------------------------------------------------
  This file is part of the Adafruit NeoPixel library.

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

  NeoPixel 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 NeoPixel.  If not, see
  <http://www.gnu.org/licenses/>.

 - Ported v1.1.6 for Nol.A-SDK by Jongsoo Jeong (CoXlab Inc.)
  -------------------------------------------------------------------------*/

#include "Adafruit_NeoPixel.hpp"

// Constructor when length, pin and type are known at compile-time:
Adafruit_NeoPixel::Adafruit_NeoPixel(uint16_t n, uint8_t p, neoPixelType t) :
  begun(false), brightness(0), pixels(NULL), endTime(0)
{
  updateType(t);
  updateLength(n);
  setPin(p);
}

// via Michael Vogt/neophob: empty constructor is used when strand length
// isn't known at compile-time; situations where program config might be
// read from internal flash memory or an SD card, or arrive via serial
// command.  If using this constructor, MUST follow up with updateType(),
// updateLength(), etc. to establish the strand type, length and pin number!
Adafruit_NeoPixel::Adafruit_NeoPixel() :
  is800KHz(true),
  begun(false), numLEDs(0), numBytes(0), pin(-1), brightness(0), pixels(NULL),
  rOffset(1), gOffset(0), bOffset(2), wOffset(1), endTime(0)
{
}

Adafruit_NeoPixel::~Adafruit_NeoPixel() {
  if(pixels)   free(pixels);
  if(pin >= 0) pinMode(pin, INPUT);
}

void Adafruit_NeoPixel::begin(void) {
  if(pin >= 0) {
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW);
  }
  begun = true;

}

void Adafruit_NeoPixel::updateLength(uint16_t n) {
  if(pixels) free(pixels); // Free existing data (if any)

  // Allocate new data -- note: ALL PIXELS ARE CLEARED
  numBytes = n * ((wOffset == rOffset) ? 3 : 4);
  if((pixels = (uint8_t *)malloc(numBytes))) {
    memset(pixels, 0, numBytes);
    numLEDs = n;
  } else {
    numLEDs = numBytes = 0;
  }
}

void Adafruit_NeoPixel::updateType(neoPixelType t) {
  boolean oldThreeBytesPerPixel = (wOffset == rOffset); // false if RGBW

  wOffset = (t >> 6) & 0b11; // See notes in header file
  rOffset = (t >> 4) & 0b11; // regarding R/G/B/W offsets
  gOffset = (t >> 2) & 0b11;
  bOffset =  t       & 0b11;
  is800KHz = (t < 256);      // 400 KHz flag is 1<<8

  // If bytes-per-pixel has changed (and pixel data was previously
  // allocated), re-allocate to new size.  Will clear any data.
  if(pixels) {
    boolean newThreeBytesPerPixel = (wOffset == rOffset);
    if(newThreeBytesPerPixel != oldThreeBytesPerPixel) updateLength(numLEDs);
  }
}

void Adafruit_NeoPixel::show(void) {
  if(!pixels) return;

  while(!canShow());

  uint8_t *p, *end, pix, mask;
  uint32_t t, time0, time1, period, startTime; //in unit of ticks

  p = pixels;
  end = p + numBytes;
  pix = *p++;
  mask = 0x80;

  if (is800KHz) {
    time0  = System.ClockHz / 2500000;
    time1  = System.ClockHz / 1250000;
    period = System.ClockHz / 8000000;
  } else {
    time0  = System.ClockHz / 2000000;
    time1  = System.ClockHz / 833333;
    period = System.ClockHz / 400000;
  }

  noInterrupts();
  for(;;) {
    if(pix & mask) {
      t = time1;
    } else {
      t = time0;
    }

    startTime = System.getCycleCount();
    digitalWrite(pin, HIGH);
    System.waitCycle(startTime, t);

    digitalWrite(pin, LOW);
    System.waitCycle(startTime, period);

    if(!(mask >>= 1)) {
      if(p >= end) break;
      pix  = *p++;
      mask = 0x80;
    }
  }
  interrupts();
}

// Set the output pin number
void Adafruit_NeoPixel::setPin(uint8_t p) {
  if(begun && (pin >= 0)) pinMode(pin, INPUT);
    pin = p;
    if(begun) {
      pinMode(p, OUTPUT);
      digitalWrite(p, LOW);
    }
}

// Set pixel color from separate R,G,B components:
void Adafruit_NeoPixel::setPixelColor(
 uint16_t n, uint8_t r, uint8_t g, uint8_t b) {

  if(n < numLEDs) {
    if(brightness) { // See notes in setBrightness()
      r = (r * brightness) >> 8;
      g = (g * brightness) >> 8;
      b = (b * brightness) >> 8;
    }
    uint8_t *p;
    if(wOffset == rOffset) { // Is an RGB-type strip
      p = &pixels[n * 3];    // 3 bytes per pixel
    } else {                 // Is a WRGB-type strip
      p = &pixels[n * 4];    // 4 bytes per pixel
      p[wOffset] = 0;        // But only R,G,B passed -- set W to 0
    }
    p[rOffset] = r;          // R,G,B always stored
    p[gOffset] = g;
    p[bOffset] = b;
  }
}

void Adafruit_NeoPixel::setPixelColor(
 uint16_t n, uint8_t r, uint8_t g, uint8_t b, uint8_t w) {

  if(n < numLEDs) {
    if(brightness) { // See notes in setBrightness()
      r = (r * brightness) >> 8;
      g = (g * brightness) >> 8;
      b = (b * brightness) >> 8;
      w = (w * brightness) >> 8;
    }
    uint8_t *p;
    if(wOffset == rOffset) { // Is an RGB-type strip
      p = &pixels[n * 3];    // 3 bytes per pixel (ignore W)
    } else {                 // Is a WRGB-type strip
      p = &pixels[n * 4];    // 4 bytes per pixel
      p[wOffset] = w;        // Store W
    }
    p[rOffset] = r;          // Store R,G,B
    p[gOffset] = g;
    p[bOffset] = b;
  }
}

// Set pixel color from 'packed' 32-bit RGB color:
void Adafruit_NeoPixel::setPixelColor(uint16_t n, uint32_t c) {
  if(n < numLEDs) {
    uint8_t *p,
      r = (uint8_t)(c >> 16),
      g = (uint8_t)(c >>  8),
      b = (uint8_t)c;
    if(brightness) { // See notes in setBrightness()
      r = (r * brightness) >> 8;
      g = (g * brightness) >> 8;
      b = (b * brightness) >> 8;
    }
    if(wOffset == rOffset) {
      p = &pixels[n * 3];
    } else {
      p = &pixels[n * 4];
      uint8_t w = (uint8_t)(c >> 24);
      p[wOffset] = brightness ? ((w * brightness) >> 8) : w;
    }
    p[rOffset] = r;
    p[gOffset] = g;
    p[bOffset] = b;
  }
}

// Convert separate R,G,B into packed 32-bit RGB color.
// Packed format is always RGB, regardless of LED strand color order.
uint32_t Adafruit_NeoPixel::Color(uint8_t r, uint8_t g, uint8_t b) {
  return ((uint32_t)r << 16) | ((uint32_t)g <<  8) | b;
}

// Convert separate R,G,B,W into packed 32-bit WRGB color.
// Packed format is always WRGB, regardless of LED strand color order.
uint32_t Adafruit_NeoPixel::Color(uint8_t r, uint8_t g, uint8_t b, uint8_t w) {
  return ((uint32_t)w << 24) | ((uint32_t)r << 16) | ((uint32_t)g <<  8) | b;
}

// Query color from previously-set pixel (returns packed 32-bit RGB value)
uint32_t Adafruit_NeoPixel::getPixelColor(uint16_t n) const {
  if(n >= numLEDs) return 0; // Out of bounds, return no color.

  uint8_t *p;

  if(wOffset == rOffset) { // Is RGB-type device
    p = &pixels[n * 3];
    if(brightness) {
      // Stored color was decimated by setBrightness().  Returned value
      // attempts to scale back to an approximation of the original 24-bit
      // value used when setting the pixel color, but there will always be
      // some error -- those bits are simply gone.  Issue is most
      // pronounced at low brightness levels.
      return (((uint32_t)(p[rOffset] << 8) / brightness) << 16) |
             (((uint32_t)(p[gOffset] << 8) / brightness) <<  8) |
             ( (uint32_t)(p[bOffset] << 8) / brightness       );
    } else {
      // No brightness adjustment has been made -- return 'raw' color
      return ((uint32_t)p[rOffset] << 16) |
             ((uint32_t)p[gOffset] <<  8) |
              (uint32_t)p[bOffset];
    }
  } else {                 // Is RGBW-type device
    p = &pixels[n * 4];
    if(brightness) { // Return scaled color
      return (((uint32_t)(p[wOffset] << 8) / brightness) << 24) |
             (((uint32_t)(p[rOffset] << 8) / brightness) << 16) |
             (((uint32_t)(p[gOffset] << 8) / brightness) <<  8) |
             ( (uint32_t)(p[bOffset] << 8) / brightness       );
    } else { // Return raw color
      return ((uint32_t)p[wOffset] << 24) |
             ((uint32_t)p[rOffset] << 16) |
             ((uint32_t)p[gOffset] <<  8) |
              (uint32_t)p[bOffset];
    }
  }
}

// Returns pointer to pixels[] array.  Pixel data is stored in device-
// native format and is not translated here.  Application will need to be
// aware of specific pixel data format and handle colors appropriately.
uint8_t *Adafruit_NeoPixel::getPixels(void) const {
  return pixels;
}

uint16_t Adafruit_NeoPixel::numPixels(void) const {
  return numLEDs;
}

// Adjust output brightness; 0=darkest (off), 255=brightest.  This does
// NOT immediately affect what's currently displayed on the LEDs.  The
// next call to show() will refresh the LEDs at this level.  However,
// this process is potentially "lossy," especially when increasing
// brightness.  The tight timing in the WS2811/WS2812 code means there
// aren't enough free cycles to perform this scaling on the fly as data
// is issued.  So we make a pass through the existing color data in RAM
// and scale it (subsequent graphics commands also work at this
// brightness level).  If there's a significant step up in brightness,
// the limited number of steps (quantization) in the old data will be
// quite visible in the re-scaled version.  For a non-destructive
// change, you'll need to re-render the full strip data.  C'est la vie.
void Adafruit_NeoPixel::setBrightness(uint8_t b) {
  // Stored brightness value is different than what's passed.
  // This simplifies the actual scaling math later, allowing a fast
  // 8x8-bit multiply and taking the MSB.  'brightness' is a uint8_t,
  // adding 1 here may (intentionally) roll over...so 0 = max brightness
  // (color values are interpreted literally; no scaling), 1 = min
  // brightness (off), 255 = just below max brightness.
  uint8_t newBrightness = b + 1;
  if(newBrightness != brightness) { // Compare against prior value
    // Brightness has changed -- re-scale existing data in RAM
    uint8_t  c,
            *ptr           = pixels,
             oldBrightness = brightness - 1; // De-wrap old brightness value
    uint16_t scale;
    if(oldBrightness == 0) scale = 0; // Avoid /0
    else if(b == 255) scale = 65535 / oldBrightness;
    else scale = (((uint16_t)newBrightness << 8) - 1) / oldBrightness;
    for(uint16_t i=0; i<numBytes; i++) {
      c      = *ptr;
      *ptr++ = (c * scale) >> 8;
    }
    brightness = newBrightness;
  }
}

//Return the brightness value
uint8_t Adafruit_NeoPixel::getBrightness(void) const {
  return brightness - 1;
}

void Adafruit_NeoPixel::clear() {
  memset(pixels, 0, numBytes);
}
<|endoftext|>


<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.

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

Bohrium 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 General Public License for more details.

You should have received a copy of the
GNU Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.
*/

#include <string>
#include <cstring>
#include <bh.h>
#include "bh_fuse.h"
#include "bh_fuse_cache.h"
#include <fstream>
#include <exception>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/version.hpp>
#include <boost/algorithm/string/predicate.hpp> //For iequals()

using namespace std;
using namespace boost;
using namespace boost::filesystem;

namespace bohrium {

    // Constructor of the InstrHash class
    InstrHash::InstrHash(BatchHash &batch, const bh_instruction &instr)
    {
        int noperands = bh_operands(instr.opcode);
        this->append("OPC");
        this->append(lexical_cast<string>(instr.opcode));
        this->append("_");
        for(int oidx=0; oidx<noperands; ++oidx) {
            const bh_view& view = instr.operand[oidx];
            if (bh_is_constant(&view))  // Ignore constants
                continue;
            std::pair<size_t,bool> vid = batch.views.insert(view);
            size_t id = vid.first;
            this->append((char*)&id, sizeof(id));
        }
        const size_t sep = SIZE_MAX;
        this->append((char*)&sep, sizeof(sep)); // Instruction seperator symbol
    }

    //Constructor of the BatchHash class
    BatchHash::BatchHash(const vector<bh_instruction> &instr_list)
    {
        string data;
        BOOST_FOREACH(const bh_instruction &instr, instr_list)
        {
            data.append(InstrHash(*this, instr));
        }
        boost::hash<string> hasher;
        _hash = hasher(data);
    }

    InstrIndexesList &FuseCache::insert(const BatchHash &batch,
                                        const vector<bh_ir_kernel> &kernel_list)
    {
        cache[batch.hash()] = InstrIndexesList(kernel_list, batch.hash(), fuser_name);
        return cache[batch.hash()];
    }

    bool FuseCache::lookup(const BatchHash &batch,
                           bh_ir &bhir,
                           vector<bh_ir_kernel> &kernel_list) const
    {
        assert(kernel_list.size() == 0);
        CacheMap::const_iterator it = cache.find(batch.hash());
        if(it == cache.end())
        {
            return false;
        }
        else
        {
            it->second.fill_kernel_list(bhir, kernel_list);
          return true;
        }
    }

    void FuseCache::write_to_files() const
    {
        if(dir_path == NULL)
        {
            cout << "[FUSE-CACHE] Couldn't find the 'cache_path' key in "\
            "the configure file thus no cache files are written to disk!" << endl;
            return;
        }
        path cache_dir(dir_path);
        if(create_directories(cache_dir))
        {
            cout << "[FUSE-CACHE] Creating cache diretory " << cache_dir << endl;
        #if BOOST_VERSION > 104900
            permissions(cache_dir, all_all);
        #endif
        }

        path tmp_dir = cache_dir / unique_path();
        create_directories(tmp_dir);
        for(CacheMap::const_iterator it=cache.begin(); it != cache.end(); ++it)
        {
            string name;
            it->second.get_filename(name);
            path shared_name = cache_dir / name;

            if(exists(shared_name))
                continue;//No need to overwrite an existing file

            path unique_name = tmp_dir / name;
            ofstream ofs(unique_name.string().c_str());
            boost::archive::text_oarchive oa(ofs);
            oa << it->second;
            ofs.close();
        #if BOOST_VERSION > 104900
            permissions(unique_name, all_all);
        #endif
            rename(unique_name, shared_name);
        }
        remove(tmp_dir);
    }

    void FuseCache::load_from_files()
    {
        if(dir_path == NULL)
        {
            cout << "[FUSE-CACHE] Couldn't find the 'cache_path' key in "\
            "the configure file thus no cache files are loaded from disk!" << endl;
            return;
        }
        path p(dir_path);
        if(not (exists(p) and is_directory(p)))
            return;

        string fuse_model_name;
        fuse_model_text(fuse_get_selected_model(), fuse_model_name);

        //Iterate the 'dir_path' diretory and load each file
        directory_iterator it(p), eod;
        BOOST_FOREACH(const path &f, make_pair(it, eod))
        {
            if(is_regular_file(f))
            {
                int tries = 0;
                while(1)
                {
                    try
                    {
                        ifstream ifs(f.string().c_str());
                        boost::archive::text_iarchive ia(ifs);
                        InstrIndexesList t;
                        ia >> t;
                        if(iequals(t.fuser_name(), fuser_name) and
                           iequals(t.fuse_model(), fuse_model_name))
                        {
                            if(cache.find(t.hash()) != cache.end())
                            {
                                if(cache[t.hash()].cost() < t.cost())
                                {
                                    cout << "[FUSE-CACHE] ignoring cache file with higher cost" << endl;
                                    break;
                                }
                            }
                            cache[t.hash()] = t;
                        }
                    }
                    catch(const std::exception &e)
                    {
                        if(++tries >= 10)
                        {
                            cerr << "[FUSE-CACHE] failed to open file '" << f.string();
                            cerr << "' (" << tries << " tries): " << e.what() << endl;
                        }
                        else
                            continue;
                    }
                    break;
                }
            }
        }
    }
} //namespace bohrium
<commit_msg>New hash function for bh_fuse_cache: Now incooperates all features udes by the different fuse filters. Safe but now size dependant again<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.

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

Bohrium 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 General Public License for more details.

You should have received a copy of the
GNU Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.
*/

#include <string>
#include <cstring>
#include <bh.h>
#include "bh_fuse.h"
#include "bh_fuse_cache.h"
#include <fstream>
#include <exception>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/version.hpp>
#include <boost/algorithm/string/predicate.hpp> //For iequals()

using namespace std;
using namespace boost;
using namespace boost::filesystem;

namespace bohrium {

    // Constructor of the InstrHash class
    InstrHash::InstrHash(BatchHash &batch, const bh_instruction &instr)
    {
        /* The Instruction hash consists of the following fields:
         * <opcode> (<operant-id> <ndim> <shape>)[1] <sweep-dim>[2] <seperator>
         * 1: for each operand
         * 2: if the operation is a sweep operation
         */
        int noperands = bh_operands(instr.opcode);
        this->append((char*)&instr.opcode, sizeof(instr.opcode));               // <opcode>
        for(int oidx=0; oidx<noperands; ++oidx) {
            const bh_view& view = instr.operand[oidx];
            if (bh_is_constant(&view))
                continue;  // Ignore constants
            std::pair<size_t,bool> vid = batch.views.insert(view);
            size_t id = vid.first;
            this->append((char*)&id, sizeof(id));                               // <operant-id>
            this->append((char*)&view.ndim, sizeof(view.ndim));                 // <ndim>
            this->append((char*)&view.shape, sizeof(bh_index)*view.ndim);       // <shape>
        }
        if (bh_opcode_is_sweep(instr.opcode))
            this->append((char*)&instr.constant.value.int64, sizeof(bh_int64)); // <sweep-dim>
        const size_t sep = SIZE_MAX;
        this->append((char*)&sep, sizeof(sep));                                 // <separator>
    }

    //Constructor of the BatchHash class
    BatchHash::BatchHash(const vector<bh_instruction> &instr_list)
    {
        string data;
        BOOST_FOREACH(const bh_instruction &instr, instr_list)
        {
            data.append(InstrHash(*this, instr));
        }
        boost::hash<string> hasher;
        _hash = hasher(data);
    }

    InstrIndexesList &FuseCache::insert(const BatchHash &batch,
                                        const vector<bh_ir_kernel> &kernel_list)
    {
        cache[batch.hash()] = InstrIndexesList(kernel_list, batch.hash(), fuser_name);
        return cache[batch.hash()];
    }

    bool FuseCache::lookup(const BatchHash &batch,
                           bh_ir &bhir,
                           vector<bh_ir_kernel> &kernel_list) const
    {
        assert(kernel_list.size() == 0);
        CacheMap::const_iterator it = cache.find(batch.hash());
        if(it == cache.end())
        {
            return false;
        }
        else
        {
            it->second.fill_kernel_list(bhir, kernel_list);
          return true;
        }
    }

    void FuseCache::write_to_files() const
    {
        if(dir_path == NULL)
        {
            cout << "[FUSE-CACHE] Couldn't find the 'cache_path' key in "\
            "the configure file thus no cache files are written to disk!" << endl;
            return;
        }
        path cache_dir(dir_path);
        if(create_directories(cache_dir))
        {
            cout << "[FUSE-CACHE] Creating cache diretory " << cache_dir << endl;
        #if BOOST_VERSION > 104900
            permissions(cache_dir, all_all);
        #endif
        }

        path tmp_dir = cache_dir / unique_path();
        create_directories(tmp_dir);
        for(CacheMap::const_iterator it=cache.begin(); it != cache.end(); ++it)
        {
            string name;
            it->second.get_filename(name);
            path shared_name = cache_dir / name;

            if(exists(shared_name))
                continue;//No need to overwrite an existing file

            path unique_name = tmp_dir / name;
            ofstream ofs(unique_name.string().c_str());
            boost::archive::text_oarchive oa(ofs);
            oa << it->second;
            ofs.close();
        #if BOOST_VERSION > 104900
            permissions(unique_name, all_all);
        #endif
            rename(unique_name, shared_name);
        }
        remove(tmp_dir);
    }

    void FuseCache::load_from_files()
    {
        if(dir_path == NULL)
        {
            cout << "[FUSE-CACHE] Couldn't find the 'cache_path' key in "\
            "the configure file thus no cache files are loaded from disk!" << endl;
            return;
        }
        path p(dir_path);
        if(not (exists(p) and is_directory(p)))
            return;

        string fuse_model_name;
        fuse_model_text(fuse_get_selected_model(), fuse_model_name);

        //Iterate the 'dir_path' diretory and load each file
        directory_iterator it(p), eod;
        BOOST_FOREACH(const path &f, make_pair(it, eod))
        {
            if(is_regular_file(f))
            {
                int tries = 0;
                while(1)
                {
                    try
                    {
                        ifstream ifs(f.string().c_str());
                        boost::archive::text_iarchive ia(ifs);
                        InstrIndexesList t;
                        ia >> t;
                        if(iequals(t.fuser_name(), fuser_name) and
                           iequals(t.fuse_model(), fuse_model_name))
                        {
                            if(cache.find(t.hash()) != cache.end())
                            {
                                if(cache[t.hash()].cost() < t.cost())
                                {
                                    cout << "[FUSE-CACHE] ignoring cache file with higher cost" << endl;
                                    break;
                                }
                            }
                            cache[t.hash()] = t;
                        }
                    }
                    catch(const std::exception &e)
                    {
                        if(++tries >= 10)
                        {
                            cerr << "[FUSE-CACHE] failed to open file '" << f.string();
                            cerr << "' (" << tries << " tries): " << e.what() << endl;
                        }
                        else
                            continue;
                    }
                    break;
                }
            }
        }
    }
} //namespace bohrium
<|endoftext|>


<commit_before>/**
 * Project
 * #    #     #     ######   ######
 * #   #     # #    #     #  #     #
 * #  #     #   #   #     #  #     #
 * ###     #     #  ######   ######
 * #  #    #######  #   #    #   #
 * #   #   #     #  #    #   #    #
 * #    #  #     #  #     #  #     #
 *
 * Copyright (c) 2014, Project KARR
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "AngularInstrument.h"

AngularInstrument::AngularInstrument() : Instrument() {
}

AngularInstrument::~AngularInstrument() {
}

void AngularInstrument::draw() {
}

void AngularInstrument::update(float newVal) {
}

bool AngularInstrument::parseFromTree(boost::property_tree::ptree &instrumentTree) {

    for (auto &tags : instrumentTree) {
	if (tags.first == "id") {
	}
	else if (tags.first == "area") {
	}
	else if (tags.first == "background") {
	}
	else if (tags.first == "needle") {
	}
    }
    return true;
}
<commit_msg>Parse id.<commit_after>/**
 * Project
 * #    #     #     ######   ######
 * #   #     # #    #     #  #     #
 * #  #     #   #   #     #  #     #
 * ###     #     #  ######   ######
 * #  #    #######  #   #    #   #
 * #   #   #     #  #    #   #    #
 * #    #  #     #  #     #  #     #
 *
 * Copyright (c) 2014, Project KARR
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "AngularInstrument.h"

#include <string>

using namespace std;

AngularInstrument::AngularInstrument() : Instrument() {
}

AngularInstrument::~AngularInstrument() {
}

void AngularInstrument::draw() {
}

void AngularInstrument::update(float newVal) {
}

bool AngularInstrument::parseFromTree(boost::property_tree::ptree &instrumentTree) {

    for (auto &tags : instrumentTree) {
	if (tags.first == "id") {
	    mId = GetInstrumentIdForString(tags.second.get_value<string>());
	    if (mId == IID_UNKNOWN)
		return false;
	}
	else if (tags.first == "area") {
	}
	else if (tags.first == "background") {
	}
	else if (tags.first == "needle") {
	}
    }
    return true;
}
<|endoftext|>