<commit_before>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#pragma once
#include "ork/ork.hpp"

#if ORK_USE_GLM
#    include "glm/fwd.hpp"
#endif // ORK_USE_GLM

namespace ork {

/*
From color.hpp
*/
enum class color_space;
#if ORK_USE_GLM
using color4 = glm::vec4;
#endif // ORK_USE_GLM

/*
From command_line.hpp
*/
#if ORK_USE_BOOST
class command_handler;
#endif // ORK_USE_BOOST

/*
From distribution.hpp
*/
#if ORK_USE_BOOST
class command_handler;
class random;
#endif // ORK_USE_BOOST
template<typename T>
class triangle_distribution;
template<typename T>
class trapezoid_distribution;

/*
From file_utils.hpp
*/
template<class functor, class iter_t, class sort>
struct directory_executer;
template<class functor, class search_type = flat_search, class sort_type = unsorted>
struct iterate_directory;
template<class T>
struct directory_range;

/*
From filter.hpp
*/
#if ORK_USE_BOOST
template<unsigned C>
struct ring;
template<unsigned order, unsigned inverse_alpha>
struct butterworth;
#endif // ORK_USE_BOOST

/*
From geometry.hpp
*/
enum class angle;
template<angle>
struct circle;

namespace GLM {

class bounding_box;
class interval;
struct segment;
class chain;

namespace MC {
struct view;
struct rotated_view;
} // namespace MC

} // namespace GLM

/*
From glm.hpp
*/
namespace GLM {

struct dunit3;
template<typename T>
struct default_epsilon_factor;

} // namespace GLM

/*
From html.hpp
*/
enum class align;
enum class border;

namespace html {

struct exportable;
struct pair;
struct string;
struct heading;
struct page_break;
struct padding;
struct image;
struct style;
struct image_style;
struct div_style;
struct table_style;
struct line_style;
struct style_set;
struct header;
struct line;
struct label;
struct table_element;
struct table;
struct div;
struct body;
struct document;

} // namespace html

} // namespace ork
<commit_msg>Added memory to fwd<commit_after>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#pragma once
#include "ork/ork.hpp"

#if ORK_USE_GLM
#    include "glm/fwd.hpp"
#endif // ORK_USE_GLM

namespace ork {

/*
From color.hpp
*/
enum class color_space;
#if ORK_USE_GLM
using color4 = glm::vec4;
#endif // ORK_USE_GLM

/*
From command_line.hpp
*/
#if ORK_USE_BOOST
class command_handler;
#endif // ORK_USE_BOOST

/*
From distribution.hpp
*/
#if ORK_USE_BOOST
class command_handler;
class random;
#endif // ORK_USE_BOOST
template<typename T>
class triangle_distribution;
template<typename T>
class trapezoid_distribution;

/*
From file_utils.hpp
*/
template<class functor, class iter_t, class sort>
struct directory_executer;
template<class functor, class search_type, class sort_type>
struct iterate_directory;
template<class T>
struct directory_range;

/*
From filter.hpp
*/
#if ORK_USE_BOOST
template<unsigned C>
struct ring;
template<unsigned order, unsigned inverse_alpha>
struct butterworth;
#endif // ORK_USE_BOOST

/*
From geometry.hpp
*/
enum class angle;
template<angle>
struct circle;

namespace GLM {

class bounding_box;
class interval;
struct segment;
class chain;

namespace MC {
struct view;
struct rotated_view;
} // namespace MC

} // namespace GLM

/*
From glm.hpp
*/
namespace GLM {

struct dunit3;
template<typename T>
struct default_epsilon_factor;

} // namespace GLM

/*
From html.hpp
*/
enum class align;
enum class border;

namespace html {

struct exportable;
struct pair;
struct string;
struct heading;
struct page_break;
struct padding;
struct image;
struct style;
struct image_style;
struct div_style;
struct table_style;
struct line_style;
struct style_set;
struct header;
struct line;
struct label;
struct table_element;
struct table;
struct div;
struct body;
struct document;

} // namespace html

/*
From memory.hpp
*/
template<typename T>
struct default_deleter;
template<typename T>
struct singleton_deleter;
template<class T, class D>
class value_ptr;
template<typename T, typename D>
class shared_ptr;

} // namespace ork
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef CPM_COMPAT_HPP
#define CPM_COMPAT_HPP

#ifdef __clang__
#define cpp14_constexpr constexpr
#else
#define cpp14_constexpr
#endif

//Fix an assertion failed in Intel C++ Compiler

#ifdef __INTEL_COMPILER
#define intel_decltype_auto auto
#else
#define intel_decltype_auto decltype(auto)
#endif

#endif //CPM_COMPAT_HPP
<commit_msg>Safety for macros<commit_after>//=======================================================================
// Copyright (c) 2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef CPM_COMPAT_HPP
#define CPM_COMPAT_HPP

#ifndef cpp14_constexpr
#ifdef __clang__
#define cpp14_constexpr constexpr
#else
#define cpp14_constexpr
#endif
#endif

//Fix an assertion failed in Intel C++ Compiler

#ifndef intel_decltype_auto
#ifdef __INTEL_COMPILER
#define intel_decltype_auto auto
#else
#define intel_decltype_auto decltype(auto)
#endif
#endif

#endif //CPM_COMPAT_HPP
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * Based on LLVM/Clang.
 *
 * This file is distributed under the University of Illinois Open Source
 * License. See LICENSE.TXT for details.
 *
 */

#ifndef PLUGIN_H
#define PLUGIN_H

#include <config_clang.h>

#include <clang/AST/ASTContext.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/Basic/FileManager.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Lex/Preprocessor.h>
#include <unordered_map>

#if __clang_major__ < 3 || __clang_major__ == 3 && __clang_minor__ < 2
#include <clang/Rewrite/Rewriter.h>
#else
#include <clang/Rewrite/Core/Rewriter.h>
#endif

using namespace clang;
using namespace llvm;
using namespace std;

namespace loplugin
{

class PluginHandler;

/**
    Base class for plugins.

    If you want to create a non-rewriter action, inherit from this class. Remember to also
    use Plugin::Registration.
*/
class Plugin
    {
    public:
        struct InstantiationData
            {
            const char* name;
            PluginHandler& handler;
            CompilerInstance& compiler;
            Rewriter* rewriter;
            };
        explicit Plugin( const InstantiationData& data );
        virtual ~Plugin();
        virtual void run() = 0;
        template< typename T > class Registration;
        enum { isPPCallback = false };
        // Returns location right after the end of the token that starts at the given location.
        SourceLocation locationAfterToken( SourceLocation location );
    protected:
        DiagnosticBuilder report( DiagnosticsEngine::Level level, StringRef message, SourceLocation loc = SourceLocation()) const;
        bool ignoreLocation( SourceLocation loc );
        bool ignoreLocation( const Decl* decl );
        bool ignoreLocation( const Stmt* stmt );
        CompilerInstance& compiler;
        PluginHandler& handler;
        /**
         Returns the parent of the given AST node. Clang's internal AST representation doesn't provide this information,
         it can only provide children, but getting the parent is often useful for inspecting a part of the AST.
        */
        const Stmt* parentStmt( const Stmt* stmt );
        Stmt* parentStmt( Stmt* stmt );
    private:
        static void registerPlugin( Plugin* (*create)( const InstantiationData& ), const char* optionName, bool isPPCallback, bool byDefault );
        template< typename T > static Plugin* createHelper( const InstantiationData& data );
        enum { isRewriter = false };
        const char* name;
        static unordered_map< const Stmt*, const Stmt* > parents;
        static void buildParents( CompilerInstance& compiler );
    };

/**
    Base class for rewriter plugins.

    Remember to also use Plugin::Registration.
*/
class RewritePlugin
    : public Plugin
    {
    public:
        explicit RewritePlugin( const InstantiationData& data );
    protected:
        enum RewriteOption
            {
            // This enum allows passing just 'RemoveLineIfEmpty' to functions below.
            // If the resulting line would be completely empty, it'll be removed.
            RemoveLineIfEmpty = 1 << 0,
            // Use this to remove the declaration/statement as a whole, i.e. all whitespace before the statement
            // and the trailing semicolor (is not part of the AST element range itself).
            // The trailing semicolon must be present.
            RemoveWholeStatement = 1 << 1,
            // Removes also all whitespace preceding and following the expression (completely, so that
            // the preceding and following tokens would be right next to each other, follow with insertText( " " )
            // if this is not wanted). Despite the name, indentation whitespace is not removed.
            RemoveAllWhitespace = 1 << 2
            };
        struct RewriteOptions
            : public Rewriter::RewriteOptions
            {
            RewriteOptions();
            RewriteOptions( RewriteOption option );
            const int flags;
            };
        // syntactic sugar to be able to write 'RemoveLineIfEmpty | RemoveWholeStatement'
        friend RewriteOption operator|( RewriteOption option1, RewriteOption option2 );
        // These following insert/remove/replaceText functions map to functions
        // in clang::Rewriter, with these differences:
        // - they (more intuitively) return false on failure rather than true
        // - they report a warning when the change cannot be done
        // - There are more options for easier removal of surroundings of a statement/expression.
        bool insertText( SourceLocation Loc, StringRef Str,
            bool InsertAfter = true, bool indentNewLines = false );
        bool insertTextAfter( SourceLocation Loc, StringRef Str );
        bool insertTextAfterToken( SourceLocation Loc, StringRef Str );
        bool insertTextBefore( SourceLocation Loc, StringRef Str );
        bool removeText( SourceLocation Start, unsigned Length, RewriteOptions opts = RewriteOptions());
        bool removeText( CharSourceRange range, RewriteOptions opts = RewriteOptions());
        bool removeText( SourceRange range, RewriteOptions opts = RewriteOptions());
        bool replaceText( SourceLocation Start, unsigned OrigLength, StringRef NewStr );
        bool replaceText( SourceRange range, StringRef NewStr );
        bool replaceText( SourceRange range, SourceRange replacementRange );
        Rewriter* rewriter;
    private:
        template< typename T > friend class Plugin::Registration;
        enum { isRewriter = true };
        bool reportEditFailure( SourceLocation loc );
        bool adjustRangeForOptions( CharSourceRange* range, RewriteOptions options );
    };

/**
    Plugin registration helper.

    If you create a new helper class, create also an instance of this class to automatically register it.
    The passed argument is name of the plugin, used for explicitly invoking rewriter plugins
    (it is ignored for non-rewriter plugins).

    @code
    static Plugin::Registration< NameOfClass > X( "nameofclass" );
    @endcode
*/
template< typename T >
class Plugin::Registration
    {
    public:
        Registration( const char* optionName, bool byDefault = !T::isRewriter );
    };

class RegistrationCreate
    {
    public:
        template< typename T, bool > static T* create( const Plugin::InstantiationData& data );
    };

/////

inline
Plugin::~Plugin()
    {
    }

inline
bool Plugin::ignoreLocation( const Decl* decl )
    {
    return ignoreLocation( decl->getLocation());
    }

inline
bool Plugin::ignoreLocation( const Stmt* stmt )
    {
    return ignoreLocation( stmt->getLocStart());
    }

template< typename T >
Plugin* Plugin::createHelper( const InstantiationData& data )
    {
    return new T( data );
    }

template< typename T >
inline
Plugin::Registration< T >::Registration( const char* optionName, bool byDefault )
    {
    registerPlugin( &T::template createHelper< T >, optionName, T::isPPCallback, byDefault );
    }

inline
RewritePlugin::RewriteOptions::RewriteOptions()
    : flags( 0 )
    {
    }

inline
RewritePlugin::RewriteOptions::RewriteOptions( RewriteOption option )
    : flags( option )
    {
    // Note that 'flags' stores also RemoveLineIfEmpty, it must be kept in sync with the base class.
    if( flags & RewritePlugin::RemoveLineIfEmpty )
        this->RemoveLineIfEmpty = true;
    }

inline
RewritePlugin::RewriteOption operator|( RewritePlugin::RewriteOption option1, RewritePlugin::RewriteOption option2 )
    {
    return static_cast< RewritePlugin::RewriteOption >( int( option1 ) | int( option2 ));
    }

} // namespace

#endif // COMPILEPLUGIN_H

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Handle ImplicitCastExpr w/ invalid loc from Objective C code<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * Based on LLVM/Clang.
 *
 * This file is distributed under the University of Illinois Open Source
 * License. See LICENSE.TXT for details.
 *
 */

#ifndef PLUGIN_H
#define PLUGIN_H

#include <config_clang.h>

#include <clang/AST/ASTContext.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/Basic/FileManager.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Lex/Preprocessor.h>
#include <unordered_map>

#if __clang_major__ < 3 || __clang_major__ == 3 && __clang_minor__ < 2
#include <clang/Rewrite/Rewriter.h>
#else
#include <clang/Rewrite/Core/Rewriter.h>
#endif

using namespace clang;
using namespace llvm;
using namespace std;

namespace loplugin
{

class PluginHandler;

/**
    Base class for plugins.

    If you want to create a non-rewriter action, inherit from this class. Remember to also
    use Plugin::Registration.
*/
class Plugin
    {
    public:
        struct InstantiationData
            {
            const char* name;
            PluginHandler& handler;
            CompilerInstance& compiler;
            Rewriter* rewriter;
            };
        explicit Plugin( const InstantiationData& data );
        virtual ~Plugin();
        virtual void run() = 0;
        template< typename T > class Registration;
        enum { isPPCallback = false };
        // Returns location right after the end of the token that starts at the given location.
        SourceLocation locationAfterToken( SourceLocation location );
    protected:
        DiagnosticBuilder report( DiagnosticsEngine::Level level, StringRef message, SourceLocation loc = SourceLocation()) const;
        bool ignoreLocation( SourceLocation loc );
        bool ignoreLocation( const Decl* decl );
        bool ignoreLocation( const Stmt* stmt );
        CompilerInstance& compiler;
        PluginHandler& handler;
        /**
         Returns the parent of the given AST node. Clang's internal AST representation doesn't provide this information,
         it can only provide children, but getting the parent is often useful for inspecting a part of the AST.
        */
        const Stmt* parentStmt( const Stmt* stmt );
        Stmt* parentStmt( Stmt* stmt );
    private:
        static void registerPlugin( Plugin* (*create)( const InstantiationData& ), const char* optionName, bool isPPCallback, bool byDefault );
        template< typename T > static Plugin* createHelper( const InstantiationData& data );
        enum { isRewriter = false };
        const char* name;
        static unordered_map< const Stmt*, const Stmt* > parents;
        static void buildParents( CompilerInstance& compiler );
    };

/**
    Base class for rewriter plugins.

    Remember to also use Plugin::Registration.
*/
class RewritePlugin
    : public Plugin
    {
    public:
        explicit RewritePlugin( const InstantiationData& data );
    protected:
        enum RewriteOption
            {
            // This enum allows passing just 'RemoveLineIfEmpty' to functions below.
            // If the resulting line would be completely empty, it'll be removed.
            RemoveLineIfEmpty = 1 << 0,
            // Use this to remove the declaration/statement as a whole, i.e. all whitespace before the statement
            // and the trailing semicolor (is not part of the AST element range itself).
            // The trailing semicolon must be present.
            RemoveWholeStatement = 1 << 1,
            // Removes also all whitespace preceding and following the expression (completely, so that
            // the preceding and following tokens would be right next to each other, follow with insertText( " " )
            // if this is not wanted). Despite the name, indentation whitespace is not removed.
            RemoveAllWhitespace = 1 << 2
            };
        struct RewriteOptions
            : public Rewriter::RewriteOptions
            {
            RewriteOptions();
            RewriteOptions( RewriteOption option );
            const int flags;
            };
        // syntactic sugar to be able to write 'RemoveLineIfEmpty | RemoveWholeStatement'
        friend RewriteOption operator|( RewriteOption option1, RewriteOption option2 );
        // These following insert/remove/replaceText functions map to functions
        // in clang::Rewriter, with these differences:
        // - they (more intuitively) return false on failure rather than true
        // - they report a warning when the change cannot be done
        // - There are more options for easier removal of surroundings of a statement/expression.
        bool insertText( SourceLocation Loc, StringRef Str,
            bool InsertAfter = true, bool indentNewLines = false );
        bool insertTextAfter( SourceLocation Loc, StringRef Str );
        bool insertTextAfterToken( SourceLocation Loc, StringRef Str );
        bool insertTextBefore( SourceLocation Loc, StringRef Str );
        bool removeText( SourceLocation Start, unsigned Length, RewriteOptions opts = RewriteOptions());
        bool removeText( CharSourceRange range, RewriteOptions opts = RewriteOptions());
        bool removeText( SourceRange range, RewriteOptions opts = RewriteOptions());
        bool replaceText( SourceLocation Start, unsigned OrigLength, StringRef NewStr );
        bool replaceText( SourceRange range, StringRef NewStr );
        bool replaceText( SourceRange range, SourceRange replacementRange );
        Rewriter* rewriter;
    private:
        template< typename T > friend class Plugin::Registration;
        enum { isRewriter = true };
        bool reportEditFailure( SourceLocation loc );
        bool adjustRangeForOptions( CharSourceRange* range, RewriteOptions options );
    };

/**
    Plugin registration helper.

    If you create a new helper class, create also an instance of this class to automatically register it.
    The passed argument is name of the plugin, used for explicitly invoking rewriter plugins
    (it is ignored for non-rewriter plugins).

    @code
    static Plugin::Registration< NameOfClass > X( "nameofclass" );
    @endcode
*/
template< typename T >
class Plugin::Registration
    {
    public:
        Registration( const char* optionName, bool byDefault = !T::isRewriter );
    };

class RegistrationCreate
    {
    public:
        template< typename T, bool > static T* create( const Plugin::InstantiationData& data );
    };

/////

inline
Plugin::~Plugin()
    {
    }

inline
bool Plugin::ignoreLocation( const Decl* decl )
    {
    return ignoreLocation( decl->getLocation());
    }

inline
bool Plugin::ignoreLocation( const Stmt* stmt )
    {
    // Invalid location can happen at least for ImplicitCastExpr of
    // ImplicitParam 'self' in Objective C method declarations:
    return stmt->getLocStart().isValid() && ignoreLocation( stmt->getLocStart());
    }

template< typename T >
Plugin* Plugin::createHelper( const InstantiationData& data )
    {
    return new T( data );
    }

template< typename T >
inline
Plugin::Registration< T >::Registration( const char* optionName, bool byDefault )
    {
    registerPlugin( &T::template createHelper< T >, optionName, T::isPPCallback, byDefault );
    }

inline
RewritePlugin::RewriteOptions::RewriteOptions()
    : flags( 0 )
    {
    }

inline
RewritePlugin::RewriteOptions::RewriteOptions( RewriteOption option )
    : flags( option )
    {
    // Note that 'flags' stores also RemoveLineIfEmpty, it must be kept in sync with the base class.
    if( flags & RewritePlugin::RemoveLineIfEmpty )
        this->RemoveLineIfEmpty = true;
    }

inline
RewritePlugin::RewriteOption operator|( RewritePlugin::RewriteOption option1, RewritePlugin::RewriteOption option2 )
    {
    return static_cast< RewritePlugin::RewriteOption >( int( option1 ) | int( option2 ));
    }

} // namespace

#endif // COMPILEPLUGIN_H

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 dresden elektronik ingenieurtechnik gmbh.
 * All rights reserved.
 *
 * The software in this package is published under the terms of the BSD
 * style license a copy of which has been included with this distribution in
 * the LICENSE.txt file.
 *
 */

#include <QApplication>
#include <QDesktopServices>
#include <QFile>
#include <QDir>
#include <QString>
#include <QProcess>
#include "de_web_plugin.h"
#include "de_web_plugin_private.h"

#define FW_IDLE_TIMEOUT (10 * 1000)
#define FW_WAIT_UPDATE_READY (2) //s
#define FW_IDLE_TIMEOUT_LONG (240 * 1000)
#define FW_WAIT_USER_TIMEOUT (120 * 1000)

/*! Inits the firmware update manager.
 */
void DeRestPluginPrivate::initFirmwareUpdate()
{
    fwProcess = 0;
    fwUpdateState = FW_Idle;

    Q_ASSERT(apsCtrl);
    apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateIdle);

    fwUpdateStartedByUser = false;
    fwUpdateTimer = new QTimer(this);
    fwUpdateTimer->setSingleShot(true);
    connect(fwUpdateTimer, SIGNAL(timeout()),
            this, SLOT(firmwareUpdateTimerFired()));
    fwUpdateTimer->start(5000);
}

/*! Starts the actual firmware update process.
 */
void DeRestPluginPrivate::updateFirmware()
{
    if (gwFirmwareNeedUpdate)
    {
        gwFirmwareNeedUpdate = false;
    }

    Q_ASSERT(apsCtrl);
    if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) == deCONZ::FirmwareUpdateIdle ||
        apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1)
    {
        DBG_Printf(DBG_INFO, "GW firmware update conditions not met, abort\n");
        fwUpdateState = FW_Idle;
        fwUpdateTimer->start(FW_IDLE_TIMEOUT);
        updateEtag(gwConfigEtag);
        return;
    }

    QString gcfFlasherBin = qApp->applicationDirPath() + "/GCFFlasher";
#ifdef Q_OS_WIN
    gcfFlasherBin.append(".exe");
    QString bin = gcfFlasherBin;
#elif defined(Q_OS_LINUX) && !defined(ARCH_ARM) // on RPi a normal sudo is ok since we don't need password there
    QString bin = "pkexec";
    gcfFlasherBin = "/usr/bin/GCFFlasher_internal";
    fwProcessArgs.prepend(gcfFlasherBin);
#elif defined(Q_OS_OSX)
    // TODO
    // /usr/bin/osascript -e 'do shell script "make install" with administrator privileges'
    QString bin = "sudo";
    fwProcessArgs.prepend(gcfFlasherBin);
#else
    QString bin = "sudo";
    gcfFlasherBin = "/usr/bin/GCFFlasher_internal";
    fwProcessArgs.prepend(gcfFlasherBin);
#endif

    if (!fwProcess)
    {
        fwProcess = new QProcess(this);
    }

    fwProcessArgs << "-f" << fwUpdateFile;

    fwUpdateState = FW_UpdateWaitFinished;
    updateEtag(gwConfigEtag);
    fwUpdateTimer->start(250);

    fwProcess->start(bin, fwProcessArgs);
}

/*! Observes the firmware update process.
 */
void DeRestPluginPrivate::updateFirmwareWaitFinished()
{
    if (fwProcess)
    {
        if (fwProcess->bytesAvailable())
        {
            QByteArray data = fwProcess->readAllStandardOutput();
            DBG_Printf(DBG_INFO, "%s", qPrintable(data));

            if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) != deCONZ::FirmwareUpdateRunning)
            {
                if (data.contains("flashing"))
                {
                    apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateRunning);
                }
            }
        }

        if (fwProcess->state() == QProcess::Starting)
        {
            DBG_Printf(DBG_INFO, "GW firmware update starting ..\n");
        }
        else if (fwProcess->state() == QProcess::Running)
        {
            DBG_Printf(DBG_INFO_L2, "GW firmware update running ..\n");
        }
        else if (fwProcess->state() == QProcess::NotRunning)
        {
            if (fwProcess->exitStatus() == QProcess::NormalExit)
            {
                DBG_Printf(DBG_INFO, "GW firmware update exit code %d\n", fwProcess->exitCode());
            }
            else if (fwProcess->exitStatus() == QProcess::CrashExit)
            {
                DBG_Printf(DBG_INFO, "GW firmware update crashed %s\n", qPrintable(fwProcess->errorString()));
            }

            fwProcess->deleteLater();
            fwProcess = 0;
        }
    }

    // done
    if (fwProcess == 0)
    {
        fwUpdateStartedByUser = false;
        gwFirmwareNeedUpdate = false;
        updateEtag(gwConfigEtag);
        apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateIdle);
        fwUpdateState = FW_Idle;
        fwUpdateTimer->start(FW_IDLE_TIMEOUT);
    }
    else // recheck
    {
        fwUpdateTimer->start(250);
    }
}

/*! Starts the device disconnect so that the serial port is released.
 */
void DeRestPluginPrivate::updateFirmwareDisconnectDevice()
{
    Q_ASSERT(apsCtrl);
//    if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) == deCONZ::FirmwareUpdateIdle)
//    {
//        if (apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1)
//        {
//            DBG_Printf(DBG_INFO, "GW firmware disconnect device before update\n");
//        }
//    }

    if (apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1)
    {
        fwUpdateTimer->start(100); // recheck
    }
    else
    {
        DBG_Printf(DBG_INFO, "GW firmware start update (device not connected)\n");
        fwUpdateState = FW_Update;
        fwUpdateTimer->start(0);
        updateEtag(gwConfigEtag);
    }
}

/*! Starts the firmware update.
 */
bool DeRestPluginPrivate::startUpdateFirmware()
{
    fwUpdateStartedByUser = true;
    if (fwUpdateState == FW_WaitUserConfirm)
    {
        apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateRunning);
        updateEtag(gwConfigEtag);
        fwUpdateState = FW_DisconnectDevice;
        fwUpdateTimer->start(100);
        return true;
    }

    return false;
}

/*! Delayed trigger to update the firmware.
 */
void DeRestPluginPrivate::firmwareUpdateTimerFired()
{
    if (fwUpdateState == FW_Idle)
    {
        if (gwFirmwareNeedUpdate)
        {
            gwFirmwareNeedUpdate = false;
            updateEtag(gwConfigEtag);
        }
        fwUpdateState = FW_CheckDevices;
        fwUpdateTimer->start(0);
    }
    else if (fwUpdateState == FW_CheckDevices)
    {
        checkFirmwareDevices();
    }
    else if (fwUpdateState == FW_CheckVersion)
    {
        queryFirmwareVersion();
    }
    else if (fwUpdateState == FW_DisconnectDevice)
    {
        updateFirmwareDisconnectDevice();
    }
    else if (fwUpdateState == FW_Update)
    {
        updateFirmware();
    }
    else if (fwUpdateState == FW_UpdateWaitFinished)
    {
        updateFirmwareWaitFinished();
    }
    else if (fwUpdateState == FW_WaitUserConfirm)
    {
        fwUpdateState = FW_Idle;
        fwUpdateTimer->start(FW_IDLE_TIMEOUT);
    }
    else
    {
        fwUpdateState = FW_Idle;
        fwUpdateTimer->start(FW_IDLE_TIMEOUT);
    }
}

/*! Lazy query of firmware version.
    Because the device might not be connected at first optaining the
    firmware version must be delayed.

    If the firmware is older then the min required firmware for the platform
    and a proper firmware update file exists, the API will announce that a
    firmware update is available.
 */
void DeRestPluginPrivate::queryFirmwareVersion()
{
    Q_ASSERT(apsCtrl);
    if (!apsCtrl)
    {
        return;
    }

    { // check for GCFFlasher binary
        QString gcfFlasherBin = qApp->applicationDirPath() + "/GCFFlasher";
#ifdef Q_OS_WIN
        gcfFlasherBin.append(".exe");
#elif defined(Q_OS_LINUX) && !defined(ARCH_ARM) // on RPi a normal sudo is ok since we don't need password there
        gcfFlasherBin = "/usr/bin/GCFFlasher_internal";
#elif defined(Q_OS_OSX)
        // TODO
#else
        gcfFlasherBin = "/usr/bin/GCFFlasher_internal";
#endif

        if (!QFile::exists(gcfFlasherBin))
        {
            DBG_Printf(DBG_INFO, "GW update firmware failed, %s doesn't exist\n", qPrintable(gcfFlasherBin));
            fwUpdateState = FW_Idle;
            fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG);
            return;
        }
    }

    // does the update file exist?
    if (fwUpdateFile.isEmpty())
    {
        QString fileName;
        fileName.sprintf("deCONZ_Rpi_0x%08x.bin.GCF", GW_MIN_RPI_FW_VERSION);

        // search in different locations
        std::vector<QString> paths;
#ifdef Q_OS_LINUX
        paths.push_back(QLatin1String("/usr/share/deCONZ/firmware/"));
#endif
        paths.push_back(deCONZ::getStorageLocation(deCONZ::ApplicationsDataLocation) + QLatin1String("/firmware/"));
        paths.push_back(deCONZ::getStorageLocation(deCONZ::HomeLocation) + QLatin1String("/raspbee_firmware/"));
#ifdef Q_OS_OSX
        QDir dir(qApp->applicationDirPath());
        dir.cdUp();
        dir.cd("Resources");
        paths.push_back(dir.path() + "/");
#endif

        std::vector<QString>::const_iterator i = paths.begin();
        std::vector<QString>::const_iterator end = paths.end();
        for (; i != end; ++i)
        {
            if (QFile::exists(*i + fileName))
            {
                fwUpdateFile = *i + fileName;
                DBG_Printf(DBG_INFO, "GW update firmware found: %s\n", qPrintable(fwUpdateFile));
                break;
            }
        }
    }

    if (fwUpdateFile.isEmpty())
    {
        DBG_Printf(DBG_ERROR, "GW update firmware not found: %s\n", qPrintable(fwUpdateFile));
        fwUpdateState = FW_Idle;
        fwUpdateTimer->start(FW_IDLE_TIMEOUT);
        return;
    }

    uint8_t devConnected = apsCtrl->getParameter(deCONZ::ParamDeviceConnected);
    uint32_t fwVersion = apsCtrl->getParameter(deCONZ::ParamFirmwareVersion);

    Q_ASSERT(!gwFirmwareNeedUpdate);

    if (devConnected == 0 || fwVersion == 0)
    {
        // if even after some time no firmware was detected
        // ASSUME that a device is present and reachable but might not have firmware installed
//        if (getUptime() >= FW_WAIT_UPDATE_READY)
        {
            QString str;
            str.sprintf("0x%08x", GW_MIN_RPI_FW_VERSION);

            gwFirmwareVersion = "0x00000000"; // unknown
            gwFirmwareVersionUpdate = str;
            gwConfig["fwversion"] = gwFirmwareVersion;
            gwFirmwareNeedUpdate = true;
            updateEtag(gwConfigEtag);

            fwUpdateState = FW_WaitUserConfirm;
            fwUpdateTimer->start(FW_WAIT_USER_TIMEOUT);
            apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateReadyToStart);

            if (fwUpdateStartedByUser)
            {
                startUpdateFirmware();
            }
        }
        return;
    }
    else if (devConnected)
    {
        QString str;
        str.sprintf("0x%08x", fwVersion);

        if (gwFirmwareVersion != str)
        {
            gwFirmwareVersion = str;
            gwConfig["fwversion"] = str;
            updateEtag(gwConfigEtag);
        }

        DBG_Printf(DBG_INFO, "GW firmware version: %s\n", qPrintable(gwFirmwareVersion));

        // if the device is detected check that the firmware version is >= min version
        if ((fwVersion & FW_PLATFORM_MASK) == FW_PLATFORM_RPI)
        {
            if (fwVersion < GW_MIN_RPI_FW_VERSION)
            {
                gwFirmwareVersionUpdate.sprintf("0x%08x", GW_MIN_RPI_FW_VERSION);
                gwFirmwareNeedUpdate = true;
                updateEtag(gwConfigEtag);

                DBG_Printf(DBG_INFO, "GW firmware version shall be updated to: 0x%08x\n", GW_MIN_RPI_FW_VERSION);
                fwUpdateState = FW_WaitUserConfirm;
                fwUpdateTimer->start(FW_WAIT_USER_TIMEOUT);
                apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateReadyToStart);
                return;
            }
            else
            {
                DBG_Printf(DBG_INFO, "GW firmware version is up to date: 0x%08x\n", fwVersion);
                fwUpdateState = FW_Idle;
                fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG);
                return;
            }
        }

        if (!gwFirmwareVersionUpdate.isEmpty())
        {
            gwFirmwareVersionUpdate.clear();
            updateEtag(gwConfigEtag);
        }
    }

    fwUpdateState = FW_Idle;
    fwUpdateTimer->start(FW_IDLE_TIMEOUT);
}

/*! Checks if devices for firmware update are present.
 */
void DeRestPluginPrivate::checkFirmwareDevices()
{
    deCONZ::DeviceEnumerator devEnumerator;

    fwProcessArgs.clear();

    devEnumerator.listSerialPorts();
    const std::vector<deCONZ::DeviceEntry> &availPorts = devEnumerator.getList();

    std::vector<deCONZ::DeviceEntry>::const_iterator i = availPorts.begin();
    std::vector<deCONZ::DeviceEntry>::const_iterator end = availPorts.end();

    int raspBeeCount = 0;
    int usbDongleCount = 0;
    QString ttyPath;

    for (; i != end; ++i)
    {
        if (i->friendlyName.contains(QLatin1String("ConBee")))
        {
            usbDongleCount++;
        }
        else if (i->friendlyName.contains(QLatin1String("RaspBee")))
        {
            raspBeeCount = 1;
            ttyPath = i->path;
        }
    }

    if (usbDongleCount > 1)
    {
        DBG_Printf(DBG_INFO_L2, "GW firmware update too many USB devices connected, abort\n");
    }
    else if (usbDongleCount == 1)
    {
        DBG_Printf(DBG_INFO_L2, "GW firmware update select USB device\n");
        fwProcessArgs << "-d" << "0";
    }
    else if (raspBeeCount > 0 && usbDongleCount == 0 && !ttyPath.isEmpty())
    {
        DBG_Printf(DBG_INFO_L2, "GW firmware update select %s device\n", qPrintable(ttyPath));
        fwProcessArgs << "-d" << "RaspBee";
    }

    if (!fwProcessArgs.isEmpty())
    {
        fwUpdateState = FW_CheckVersion;
        fwUpdateTimer->start(0);
        return;
    }

    fwUpdateState = FW_Idle;
    fwUpdateTimer->start(FW_IDLE_TIMEOUT);
}
<commit_msg>Wait longer after firmware update before recheck new firmware<commit_after>/*
 * Copyright (c) 2016 dresden elektronik ingenieurtechnik gmbh.
 * All rights reserved.
 *
 * The software in this package is published under the terms of the BSD
 * style license a copy of which has been included with this distribution in
 * the LICENSE.txt file.
 *
 */

#include <QApplication>
#include <QDesktopServices>
#include <QFile>
#include <QDir>
#include <QString>
#include <QProcess>
#include "de_web_plugin.h"
#include "de_web_plugin_private.h"

#define FW_IDLE_TIMEOUT (10 * 1000)
#define FW_WAIT_UPDATE_READY (2) //s
#define FW_IDLE_TIMEOUT_LONG (240 * 1000)
#define FW_WAIT_USER_TIMEOUT (120 * 1000)

/*! Inits the firmware update manager.
 */
void DeRestPluginPrivate::initFirmwareUpdate()
{
    fwProcess = 0;
    fwUpdateState = FW_Idle;

    Q_ASSERT(apsCtrl);
    apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateIdle);

    fwUpdateStartedByUser = false;
    fwUpdateTimer = new QTimer(this);
    fwUpdateTimer->setSingleShot(true);
    connect(fwUpdateTimer, SIGNAL(timeout()),
            this, SLOT(firmwareUpdateTimerFired()));
    fwUpdateTimer->start(5000);
}

/*! Starts the actual firmware update process.
 */
void DeRestPluginPrivate::updateFirmware()
{
    if (gwFirmwareNeedUpdate)
    {
        gwFirmwareNeedUpdate = false;
    }

    Q_ASSERT(apsCtrl);
    if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) == deCONZ::FirmwareUpdateIdle ||
        apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1)
    {
        DBG_Printf(DBG_INFO, "GW firmware update conditions not met, abort\n");
        fwUpdateState = FW_Idle;
        fwUpdateTimer->start(FW_IDLE_TIMEOUT);
        updateEtag(gwConfigEtag);
        return;
    }

    QString gcfFlasherBin = qApp->applicationDirPath() + "/GCFFlasher";
#ifdef Q_OS_WIN
    gcfFlasherBin.append(".exe");
    QString bin = gcfFlasherBin;
#elif defined(Q_OS_LINUX) && !defined(ARCH_ARM) // on RPi a normal sudo is ok since we don't need password there
    QString bin = "pkexec";
    gcfFlasherBin = "/usr/bin/GCFFlasher_internal";
    fwProcessArgs.prepend(gcfFlasherBin);
#elif defined(Q_OS_OSX)
    // TODO
    // /usr/bin/osascript -e 'do shell script "make install" with administrator privileges'
    QString bin = "sudo";
    fwProcessArgs.prepend(gcfFlasherBin);
#else
    QString bin = "sudo";
    gcfFlasherBin = "/usr/bin/GCFFlasher_internal";
    fwProcessArgs.prepend(gcfFlasherBin);
#endif

    if (!fwProcess)
    {
        fwProcess = new QProcess(this);
    }

    fwProcessArgs << "-f" << fwUpdateFile;

    fwUpdateState = FW_UpdateWaitFinished;
    updateEtag(gwConfigEtag);
    fwUpdateTimer->start(250);

    fwProcess->start(bin, fwProcessArgs);
}

/*! Observes the firmware update process.
 */
void DeRestPluginPrivate::updateFirmwareWaitFinished()
{
    if (fwProcess)
    {
        if (fwProcess->bytesAvailable())
        {
            QByteArray data = fwProcess->readAllStandardOutput();
            DBG_Printf(DBG_INFO, "%s", qPrintable(data));

            if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) != deCONZ::FirmwareUpdateRunning)
            {
                if (data.contains("flashing"))
                {
                    apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateRunning);
                }
            }
        }

        if (fwProcess->state() == QProcess::Starting)
        {
            DBG_Printf(DBG_INFO, "GW firmware update starting ..\n");
        }
        else if (fwProcess->state() == QProcess::Running)
        {
            DBG_Printf(DBG_INFO_L2, "GW firmware update running ..\n");
        }
        else if (fwProcess->state() == QProcess::NotRunning)
        {
            if (fwProcess->exitStatus() == QProcess::NormalExit)
            {
                DBG_Printf(DBG_INFO, "GW firmware update exit code %d\n", fwProcess->exitCode());
            }
            else if (fwProcess->exitStatus() == QProcess::CrashExit)
            {
                DBG_Printf(DBG_INFO, "GW firmware update crashed %s\n", qPrintable(fwProcess->errorString()));
            }

            fwProcess->deleteLater();
            fwProcess = 0;
        }
    }

    // done
    if (fwProcess == 0)
    {
        fwUpdateStartedByUser = false;
        gwFirmwareNeedUpdate = false;
        updateEtag(gwConfigEtag);
        apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateIdle);
        fwUpdateState = FW_Idle;
        fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG);
    }
    else // recheck
    {
        fwUpdateTimer->start(250);
    }
}

/*! Starts the device disconnect so that the serial port is released.
 */
void DeRestPluginPrivate::updateFirmwareDisconnectDevice()
{
    Q_ASSERT(apsCtrl);
//    if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) == deCONZ::FirmwareUpdateIdle)
//    {
//        if (apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1)
//        {
//            DBG_Printf(DBG_INFO, "GW firmware disconnect device before update\n");
//        }
//    }

    if (apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1)
    {
        fwUpdateTimer->start(100); // recheck
    }
    else
    {
        DBG_Printf(DBG_INFO, "GW firmware start update (device not connected)\n");
        fwUpdateState = FW_Update;
        fwUpdateTimer->start(0);
        updateEtag(gwConfigEtag);
    }
}

/*! Starts the firmware update.
 */
bool DeRestPluginPrivate::startUpdateFirmware()
{
    fwUpdateStartedByUser = true;
    if (fwUpdateState == FW_WaitUserConfirm)
    {
        apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateRunning);
        updateEtag(gwConfigEtag);
        fwUpdateState = FW_DisconnectDevice;
        fwUpdateTimer->start(100);
        return true;
    }

    return false;
}

/*! Delayed trigger to update the firmware.
 */
void DeRestPluginPrivate::firmwareUpdateTimerFired()
{
    if (fwUpdateState == FW_Idle)
    {
        if (gwFirmwareNeedUpdate)
        {
            gwFirmwareNeedUpdate = false;
            updateEtag(gwConfigEtag);
        }
        fwUpdateState = FW_CheckDevices;
        fwUpdateTimer->start(0);
    }
    else if (fwUpdateState == FW_CheckDevices)
    {
        checkFirmwareDevices();
    }
    else if (fwUpdateState == FW_CheckVersion)
    {
        queryFirmwareVersion();
    }
    else if (fwUpdateState == FW_DisconnectDevice)
    {
        updateFirmwareDisconnectDevice();
    }
    else if (fwUpdateState == FW_Update)
    {
        updateFirmware();
    }
    else if (fwUpdateState == FW_UpdateWaitFinished)
    {
        updateFirmwareWaitFinished();
    }
    else if (fwUpdateState == FW_WaitUserConfirm)
    {
        fwUpdateState = FW_Idle;
        fwUpdateTimer->start(FW_IDLE_TIMEOUT);
    }
    else
    {
        fwUpdateState = FW_Idle;
        fwUpdateTimer->start(FW_IDLE_TIMEOUT);
    }
}

/*! Lazy query of firmware version.
    Because the device might not be connected at first optaining the
    firmware version must be delayed.

    If the firmware is older then the min required firmware for the platform
    and a proper firmware update file exists, the API will announce that a
    firmware update is available.
 */
void DeRestPluginPrivate::queryFirmwareVersion()
{
    Q_ASSERT(apsCtrl);
    if (!apsCtrl)
    {
        return;
    }

    { // check for GCFFlasher binary
        QString gcfFlasherBin = qApp->applicationDirPath() + "/GCFFlasher";
#ifdef Q_OS_WIN
        gcfFlasherBin.append(".exe");
#elif defined(Q_OS_LINUX) && !defined(ARCH_ARM) // on RPi a normal sudo is ok since we don't need password there
        gcfFlasherBin = "/usr/bin/GCFFlasher_internal";
#elif defined(Q_OS_OSX)
        // TODO
#else
        gcfFlasherBin = "/usr/bin/GCFFlasher_internal";
#endif

        if (!QFile::exists(gcfFlasherBin))
        {
            DBG_Printf(DBG_INFO, "GW update firmware failed, %s doesn't exist\n", qPrintable(gcfFlasherBin));
            fwUpdateState = FW_Idle;
            fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG);
            return;
        }
    }

    // does the update file exist?
    if (fwUpdateFile.isEmpty())
    {
        QString fileName;
        fileName.sprintf("deCONZ_Rpi_0x%08x.bin.GCF", GW_MIN_RPI_FW_VERSION);

        // search in different locations
        std::vector<QString> paths;
#ifdef Q_OS_LINUX
        paths.push_back(QLatin1String("/usr/share/deCONZ/firmware/"));
#endif
        paths.push_back(deCONZ::getStorageLocation(deCONZ::ApplicationsDataLocation) + QLatin1String("/firmware/"));
        paths.push_back(deCONZ::getStorageLocation(deCONZ::HomeLocation) + QLatin1String("/raspbee_firmware/"));
#ifdef Q_OS_OSX
        QDir dir(qApp->applicationDirPath());
        dir.cdUp();
        dir.cd("Resources");
        paths.push_back(dir.path() + "/");
#endif

        std::vector<QString>::const_iterator i = paths.begin();
        std::vector<QString>::const_iterator end = paths.end();
        for (; i != end; ++i)
        {
            if (QFile::exists(*i + fileName))
            {
                fwUpdateFile = *i + fileName;
                DBG_Printf(DBG_INFO, "GW update firmware found: %s\n", qPrintable(fwUpdateFile));
                break;
            }
        }
    }

    if (fwUpdateFile.isEmpty())
    {
        DBG_Printf(DBG_ERROR, "GW update firmware not found: %s\n", qPrintable(fwUpdateFile));
        fwUpdateState = FW_Idle;
        fwUpdateTimer->start(FW_IDLE_TIMEOUT);
        return;
    }

    uint8_t devConnected = apsCtrl->getParameter(deCONZ::ParamDeviceConnected);
    uint32_t fwVersion = apsCtrl->getParameter(deCONZ::ParamFirmwareVersion);

    Q_ASSERT(!gwFirmwareNeedUpdate);

    if (devConnected == 0 || fwVersion == 0)
    {
        // if even after some time no firmware was detected
        // ASSUME that a device is present and reachable but might not have firmware installed
//        if (getUptime() >= FW_WAIT_UPDATE_READY)
        {
            QString str;
            str.sprintf("0x%08x", GW_MIN_RPI_FW_VERSION);

            gwFirmwareVersion = "0x00000000"; // unknown
            gwFirmwareVersionUpdate = str;
            gwConfig["fwversion"] = gwFirmwareVersion;
            gwFirmwareNeedUpdate = true;
            updateEtag(gwConfigEtag);

            fwUpdateState = FW_WaitUserConfirm;
            fwUpdateTimer->start(FW_WAIT_USER_TIMEOUT);
            apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateReadyToStart);

            if (fwUpdateStartedByUser)
            {
                startUpdateFirmware();
            }
        }
        return;
    }
    else if (devConnected)
    {
        QString str;
        str.sprintf("0x%08x", fwVersion);

        if (gwFirmwareVersion != str)
        {
            gwFirmwareVersion = str;
            gwConfig["fwversion"] = str;
            updateEtag(gwConfigEtag);
        }

        DBG_Printf(DBG_INFO, "GW firmware version: %s\n", qPrintable(gwFirmwareVersion));

        // if the device is detected check that the firmware version is >= min version
        if ((fwVersion & FW_PLATFORM_MASK) == FW_PLATFORM_RPI)
        {
            if (fwVersion < GW_MIN_RPI_FW_VERSION)
            {
                gwFirmwareVersionUpdate.sprintf("0x%08x", GW_MIN_RPI_FW_VERSION);
                gwFirmwareNeedUpdate = true;
                updateEtag(gwConfigEtag);

                DBG_Printf(DBG_INFO, "GW firmware version shall be updated to: 0x%08x\n", GW_MIN_RPI_FW_VERSION);
                fwUpdateState = FW_WaitUserConfirm;
                fwUpdateTimer->start(FW_WAIT_USER_TIMEOUT);
                apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateReadyToStart);
                return;
            }
            else
            {
                DBG_Printf(DBG_INFO, "GW firmware version is up to date: 0x%08x\n", fwVersion);
                fwUpdateState = FW_Idle;
                fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG);
                return;
            }
        }

        if (!gwFirmwareVersionUpdate.isEmpty())
        {
            gwFirmwareVersionUpdate.clear();
            updateEtag(gwConfigEtag);
        }
    }

    fwUpdateState = FW_Idle;
    fwUpdateTimer->start(FW_IDLE_TIMEOUT);
}

/*! Checks if devices for firmware update are present.
 */
void DeRestPluginPrivate::checkFirmwareDevices()
{
    deCONZ::DeviceEnumerator devEnumerator;

    fwProcessArgs.clear();

    devEnumerator.listSerialPorts();
    const std::vector<deCONZ::DeviceEntry> &availPorts = devEnumerator.getList();

    std::vector<deCONZ::DeviceEntry>::const_iterator i = availPorts.begin();
    std::vector<deCONZ::DeviceEntry>::const_iterator end = availPorts.end();

    int raspBeeCount = 0;
    int usbDongleCount = 0;
    QString ttyPath;

    for (; i != end; ++i)
    {
        if (i->friendlyName.contains(QLatin1String("ConBee")))
        {
            usbDongleCount++;
        }
        else if (i->friendlyName.contains(QLatin1String("RaspBee")))
        {
            raspBeeCount = 1;
            ttyPath = i->path;
        }
    }

    if (usbDongleCount > 1)
    {
        DBG_Printf(DBG_INFO_L2, "GW firmware update too many USB devices connected, abort\n");
    }
    else if (usbDongleCount == 1)
    {
        DBG_Printf(DBG_INFO_L2, "GW firmware update select USB device\n");
        fwProcessArgs << "-d" << "0";
    }
    else if (raspBeeCount > 0 && usbDongleCount == 0 && !ttyPath.isEmpty())
    {
        DBG_Printf(DBG_INFO_L2, "GW firmware update select %s device\n", qPrintable(ttyPath));
        fwProcessArgs << "-d" << "RaspBee";
    }

    if (!fwProcessArgs.isEmpty())
    {
        fwUpdateState = FW_CheckVersion;
        fwUpdateTimer->start(0);
        return;
    }

    fwUpdateState = FW_Idle;
    fwUpdateTimer->start(FW_IDLE_TIMEOUT);
}
<|endoftext|>


<commit_before>/**
 * @file osc.cpp
 * @brief  Brief description of file.
 *
 */

#include "angort/angort.h"
#include "../wrappers.h"
#include <lo/lo.h>
#define THROWOSC(e) throw RUNT("ex$diamond",e.what())

using namespace angort;

static BasicWrapperType<lo_address> tLoAddr("LOAD");

%type LoAddr tLoAddr lo_address

%name osc
%shared

%wordargs makeport s (s ---) make a new OSC port on localhost, given the port name
{
    lo_address lo = lo_address_new(NULL,p0);
    if(!lo)
        a->pushNone();
    else
        tLoAddr.set(a->pushval(),lo);
}

%wordargs send lsA|LoAddr (floatlist path port -- ret) send to path from a port, returns none on fail.
{
    lo_message msg = lo_message_new();
    ArrayListIterator<Value> iter(p0);
    int i=0;
    for(iter.first();!iter.isDone();iter.next(),i++){
        lo_message_add_float(msg,iter.current()->toFloat());
    }
    int ret = lo_send_message(*p2,p1,msg);
    if(ret<0)
        a->pushNone();
    else
        a->pushInt(0);
    lo_message_free(msg);
}

%init
{
    fprintf(stderr,"Initialising OSC plugin (send only), %s %s\n",__DATE__,__TIME__);
}

%shutdown
{
}
<commit_msg>description<commit_after>/**
 * @file osc.cpp
 * @brief  Brief description of file.
 *
 */

#include "angort/angort.h"
#include "../wrappers.h"
#include <lo/lo.h>
#define THROWOSC(e) throw RUNT("ex$diamond",e.what())

using namespace angort;

static BasicWrapperType<lo_address> tLoAddr("LOAD");

%type LoAddr tLoAddr lo_address

%name osc
%shared

%wordargs makeport s (s ---) make a new OSC port on localhost, given the port name
{
    lo_address lo = lo_address_new(NULL,p0);
    if(!lo)
        a->pushNone();
    else
        tLoAddr.set(a->pushval(),lo);
}

%wordargs send lsA|LoAddr (floatlist path port -- ret) send to path on a port, returns none on fail.
{
    lo_message msg = lo_message_new();
    ArrayListIterator<Value> iter(p0);
    int i=0;
    for(iter.first();!iter.isDone();iter.next(),i++){
        lo_message_add_float(msg,iter.current()->toFloat());
    }
    int ret = lo_send_message(*p2,p1,msg);
    if(ret<0)
        a->pushNone();
    else
        a->pushInt(0);
    lo_message_free(msg);
}

%init
{
    fprintf(stderr,"Initialising OSC plugin (send only), %s %s\n",__DATE__,__TIME__);
}

%shutdown
{
}
<|endoftext|>


<commit_before>/* This file is part of Mapnik (c++ mapping toolkit)
 * Copyright (C) 2005 Artem Pavlenko
 *
 * Mapnik 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 2
 * of the License, or 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

//$Id$

#ifndef EXPRESSION_HPP
#define EXPRESSION_HPP

#include "value.hpp"
#include "filter_visitor.hpp"

namespace mapnik
{
    template <typename FeatureT> class filter_visitor;
    template <typename FeatureT>
    struct expression
    {
	virtual value get_value(FeatureT const& feature) const=0;
	virtual void accept(filter_visitor<FeatureT>& v)=0;
	virtual expression<FeatureT>* clone() const=0;
	virtual std::string to_string() const=0;
	virtual ~expression() {}
    };

    template <typename FeatureT>
    class literal : public expression<FeatureT>
    {
    public:
	literal(int val)
	    : expression<FeatureT>(),
	      value_(val) {}
	literal(double val)
	    : expression<FeatureT>(),
	      value_(val) {}
	literal(std::string const& val)
	    : expression<FeatureT>(),
	      value_(val) {}
	literal(literal const& other)
	    : expression<FeatureT>(),
	      value_(other.value_) {}

	value get_value(FeatureT const& /*feature*/) const
	{
	    return value_;
	}
	void accept(filter_visitor<FeatureT>& v)
	{
	    v.visit(*this);
	}
	expression<FeatureT>* clone() const
	{
	    return new literal(*this);
	}
	std::string to_string() const
	{
	    return "'"+value_.to_string()+"'";
	}
        ~literal() {}
    private:
	value value_;

    };

    template <typename FeatureT>
    class property : public expression<FeatureT>
    {
    public:
	property(std::string const& name)
	    : expression<FeatureT>(),
	      name_(name),
	      index_(0),
	      valid_(false) {}

	property(property const& other)
	    : expression<FeatureT>(),
	      name_(other.name_),
	      index_(other.index_),
	      valid_(other.valid_) {}

	value get_value(FeatureT const& feature) const
	{
	    return feature.get_property(index_);
	}
	void accept(filter_visitor<FeatureT>& v)
	{
	    v.visit(*this);
	}
	expression<FeatureT>* clone() const
	{
	    return new property(*this);
	}
	std::string const& name() const
	{
	    return name_;
	}
	void set_index(size_t index)
	{
	    index_=index;
	    valid_=true;
	}
	std::string to_string() const
	{
	    return "["+name_+"]";
	}
        ~property() {}
    private:
	std::string name_;
	size_t index_;
	bool valid_;
    };
}

#endif //EXPRESSION_HPP
<commit_msg> fixed to_string() method for filter expressions<commit_after>/* This file is part of Mapnik (c++ mapping toolkit)
 * Copyright (C) 2005 Artem Pavlenko
 *
 * Mapnik 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 2
 * of the License, or 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

//$Id$

#ifndef EXPRESSION_HPP
#define EXPRESSION_HPP

#include "value.hpp"
#include "filter_visitor.hpp"

namespace mapnik
{
    template <typename FeatureT> class filter_visitor;
    template <typename FeatureT>
    struct expression
    {
	virtual value get_value(FeatureT const& feature) const=0;
	virtual void accept(filter_visitor<FeatureT>& v)=0;
	virtual expression<FeatureT>* clone() const=0;
	virtual std::string to_string() const=0;
	virtual ~expression() {}
    };

    template <typename FeatureT>
    class literal : public expression<FeatureT>
    {
    public:
	literal(int val)
	    : expression<FeatureT>(),
	      value_(val) {}
	literal(double val)
	    : expression<FeatureT>(),
	      value_(val) {}
	literal(std::string const& val)
	    : expression<FeatureT>(),
	      value_(val) {}
	literal(literal const& other)
	    : expression<FeatureT>(),
	      value_(other.value_) {}

	value get_value(FeatureT const& /*feature*/) const
	{
	    return value_;
	}
	void accept(filter_visitor<FeatureT>& v)
	{
	    v.visit(*this);
	}
	expression<FeatureT>* clone() const
	{
	    return new literal(*this);
	}
	std::string to_string() const
	{
	    return value_.to_string();
	}
        ~literal() {}
    private:
	value value_;
    };

    template <typename FeatureT>
    class property : public expression<FeatureT>
    {
    public:
	property(std::string const& name)
	    : expression<FeatureT>(),
	      name_(name),
	      index_(0),
	      valid_(false) {}

	property(property const& other)
	    : expression<FeatureT>(),
	      name_(other.name_),
	      index_(other.index_),
	      valid_(other.valid_) {}

	value get_value(FeatureT const& feature) const
	{
	    return feature.get_property(index_);
	}
	void accept(filter_visitor<FeatureT>& v)
	{
	    v.visit(*this);
	}
	expression<FeatureT>* clone() const
	{
	    return new property(*this);
	}
	std::string const& name() const
	{
	    return name_;
	}
	void set_index(size_t index)
	{
	    index_=index;
	    valid_=true;
	}
	std::string to_string() const
	{
	    return "["+name_+"]";
	}
        ~property() {}
    private:
	std::string name_;
	size_t index_;
	bool valid_;
    };
}

#endif //EXPRESSION_HPP
<|endoftext|>


<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium team:
http://bohrium.bitbucket.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 <iostream>

#include "traits.hpp"           // Traits for assigning type to constants and multi_arrays.
#include "runtime.hpp"
#include <sstream>

namespace bh {

template <typename T>
void multi_array<T>::init()     // Pseudo-default constructor
{
    key     = keys++;
    temp    = false;
    storage.insert(key, new bh_array);
    assign_array_type<T>(&storage[key]);
}

template <typename T>           // Default constructor - rank 0
multi_array<T>::multi_array() : key(0), temp(false) { }

/**
 * Inherit ndim / shape from another operand
 * Does not copy data.
 *
 */
template <typename T>           // Copy constructor
multi_array<T>::multi_array(const multi_array<T>& operand)
{
    init();

    storage[key].data        = NULL;
    storage[key].base        = NULL;
    storage[key].ndim        = storage[operand.getKey()].ndim;
    storage[key].start       = storage[operand.getKey()].start;

    for(int64_t i=0; i< storage[operand.getKey()].ndim; i++) {
        storage[key].shape[i] = storage[operand.getKey()].shape[i];
    }
    for(int64_t i=0; i< storage[operand.getKey()].ndim; i++) {
        storage[key].stride[i] = storage[operand.getKey()].stride[i];
    }
}

template <typename T>
template <typename ...Dimensions>       // Variadic constructor
multi_array<T>::multi_array(Dimensions... shape)
{
    init();

    storage[key].data        = NULL;
    storage[key].base        = NULL;
    storage[key].ndim        = sizeof...(Dimensions);
    storage[key].start       = 0;

    unpack_shape(storage[key].shape, 0, shape...);

    int64_t stride = 1;                 // Setup strides
    for(int64_t i=storage[key].ndim-1; 0 <= i; --i) {
        storage[key].stride[i] = stride;
        stride *= storage[key].shape[i];
    }
}

template <typename T>                   // Deconstructor
multi_array<T>::~multi_array()
{
    if (key>0) {
        if (NULL == storage[key].base) {    // Only send free on base-array
            Runtime::instance()->enqueue((bh_opcode)BH_FREE, *this);
        }
        Runtime::instance()->enqueue((bh_opcode)BH_DISCARD, *this);
        Runtime::instance()->trash(key);
    }
}

template <typename T>
inline
size_t multi_array<T>::getKey() const
{
    return key;
}

template <typename T>
inline
unsigned long multi_array<T>::getRank() const
{
    return (unsigned long)*(&storage[key].ndim);
}

template <typename T>
inline
bool multi_array<T>::getTemp() const
{
    return temp;
}

template <typename T>
inline
void multi_array<T>::setTemp(bool temp)
{
    this->temp = temp;
}

template <typename T>
inline
size_t multi_array<T>::len()
{
    size_t nelements = 1;
    for (int i = 0; i < storage[key].ndim; ++i) {
        nelements *= storage[key].shape[i];
    }
    return nelements;
}

template <typename T>
typename multi_array<T>::iterator multi_array<T>::begin()
{
    Runtime::instance()->enqueue((bh_opcode)BH_SYNC, *this);
    Runtime::instance()->flush();

    return multi_array<T>::iterator(storage[this->key]);
}

template <typename T>
typename multi_array<T>::iterator multi_array<T>::end()
{
    return multi_array<T>::iterator();
}

//
// Increment / decrement
//
template <typename T>
multi_array<T>& multi_array<T>::operator++()
{
    Runtime::instance()->enqueue((bh_opcode)BH_ADD, *this, *this, (T)1);
    return *this;
}

template <typename T>
multi_array<T>& multi_array<T>::operator++(int)
{
    Runtime::instance()->enqueue((bh_opcode)BH_ADD, *this, *this, (T)1);
    return *this;
}

template <typename T>
multi_array<T>& multi_array<T>::operator--()
{
    Runtime::instance()->enqueue((bh_opcode)BH_SUBTRACT, *this, *this, (T)1);
    return *this;
}

template <typename T>
multi_array<T>& multi_array<T>::operator--(int)
{
    Runtime::instance()->enqueue((bh_opcode)BH_SUBTRACT, *this, *this, (T)1);
    return *this;
}

//
// Output / Printing
//
template <typename T>
std::ostream& operator<< (std::ostream& stream, multi_array<T>& rhs)
{
    bool first = true;
    typename multi_array<T>::iterator it  = rhs.begin();
    typename multi_array<T>::iterator end = rhs.end();

    stream << "[ ";
    for(; it != end; it++) {
        if (!first) {
            stream  << ", ";
        } else {
            first = false;
        }
        stream << *it;
    }
    stream << " ]" << std::endl;

    if (rhs.getTemp()) {    // Cleanup temporary
        delete &rhs;
    }

    return stream;
}

//
// Slicing
//
template <typename T>
slice<T>& multi_array<T>::operator[](int rhs) {
    return (*(new slice<T>(*this)))[rhs];
}

template <typename T>
slice<T>& multi_array<T>::operator[](slice_range& rhs) {
    return (*(new slice<T>(*this)))[rhs];
}

//
// Reshaping
//
template <typename T>
multi_array<T>& multi_array<T>::operator()(const T& n) {
    std::cout << "Reshape to: " << n << std::endl;
    return *this;
}

// Initialization
template <typename T>
multi_array<T>& multi_array<T>::operator=(const T& rhs)
{
    Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *this, rhs);
    return *this;
}

// Linking
template <typename T>
void multi_array<T>::link(const size_t ext_key)
{
    if (0!=key) {
        throw std::runtime_error("Dude you are ALREADY linked!");
    }
    key = ext_key;
}

template <typename T>
size_t multi_array<T>::unlink()
{
    if (0==key) {
        throw std::runtime_error("Dude! THis one aint linked at all!");
    }

    size_t retKey = key;
    key = 0;
    return retKey;
}

// Aliasing
template <typename T>
multi_array<T>& multi_array<T>::operator=(multi_array<T>& rhs)
{
    if (key != rhs.getKey()) {      // Prevent self-aliasing

        if (key>0) {                // Release current linkage
            if (NULL == storage[key].base) {
                Runtime::instance()->enqueue((bh_opcode)BH_FREE, *this);
            }
            Runtime::instance()->enqueue((bh_opcode)BH_DISCARD, *this);
            unlink();
        }

        if (rhs.getTemp()) {        // Take over temporary reference
            link(rhs.unlink());
            temp = false;
            delete &rhs;
        } else {                    // Create an alias of rhs.
            init();

            storage[key].data       = NULL;
            storage[key].base       = &storage[rhs.getKey()];
            storage[key].ndim       = storage[rhs.getKey()].ndim;
            storage[key].start      = storage[rhs.getKey()].start;
            for(int64_t i=0; i< storage[rhs.getKey()].ndim; i++) {
                storage[key].shape[i] = storage[rhs.getKey()].shape[i];
            }
            for(int64_t i=0; i< storage[rhs.getKey()].ndim; i++) {
                storage[key].stride[i] = storage[rhs.getKey()].stride[i];
            }
        }
    }

    return *this;
}

/**
 *  Aliasing via slicing
 *
 *  Construct a view based on a slice.
 *  Such as:
 *
 *  center = grid[_(1,-1,1)][_(1,-1,1)];
 *
 *  TODO: this is probobaly not entirely correct...
 */
template <typename T>
multi_array<T>& multi_array<T>::operator=(slice<T>& rhs)
{
    multi_array<T>* vv = &rhs.view();

    if (key>0) {                // Release current linkage
        if (NULL == storage[key].base) {
            Runtime::instance()->enqueue((bh_opcode)BH_FREE, *this);
        }
        Runtime::instance()->enqueue((bh_opcode)BH_DISCARD, *this);
        unlink();
    }

    link(vv->unlink());
    delete vv;

    return *this;
}

//
// Typecasting
//
template <typename T> template <typename Ret>
multi_array<Ret>& multi_array<T>::as()
{
    multi_array<Ret>* result = &Runtime::instance()->temp<Ret>();
    result->setTemp(true);

    storage[result->getKey()].base        = NULL;
    storage[result->getKey()].ndim        = storage[this->getKey()].ndim;
    storage[result->getKey()].start       = storage[this->getKey()].start;
    for(int64_t i=0; i< storage[this->getKey()].ndim; i++) {
        storage[result->getKey()].shape[i] = storage[this->getKey()].shape[i];
    }
    for(int64_t i=0; i< storage[this->getKey()].ndim; i++) {

        storage[result->getKey()].stride[i] = storage[this->getKey()].stride[i];
    }
    storage[result->getKey()].data        = NULL;

    Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *result, *this);

    return *result;
}

/**
 *  Update operand!
 */
template <typename T>
multi_array<T>& multi_array<T>::update(multi_array& rhs)
{
    if (1>key) {    // We do not have anything to update!
        throw std::runtime_error("Far out dude! you are trying to update "
                                 "something that does not exist!");
    }
    Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *this, rhs);

    return *this;
}

}

<commit_msg>cppb: Moved functionality of multi_array.update() to multi_array.operator().<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium team:
http://bohrium.bitbucket.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 <iostream>

#include "traits.hpp"           // Traits for assigning type to constants and multi_arrays.
#include "runtime.hpp"
#include <sstream>

namespace bh {

template <typename T>
void multi_array<T>::init()     // Pseudo-default constructor
{
    key     = keys++;
    temp    = false;
    storage.insert(key, new bh_array);
    assign_array_type<T>(&storage[key]);
}

template <typename T>           // Default constructor - rank 0
multi_array<T>::multi_array() : key(0), temp(false) { }

/**
 * Inherit ndim / shape from another operand
 * Does not copy data.
 *
 */
template <typename T>           // Copy constructor
multi_array<T>::multi_array(const multi_array<T>& operand)
{
    init();

    storage[key].data        = NULL;
    storage[key].base        = NULL;
    storage[key].ndim        = storage[operand.getKey()].ndim;
    storage[key].start       = storage[operand.getKey()].start;

    for(int64_t i=0; i< storage[operand.getKey()].ndim; i++) {
        storage[key].shape[i] = storage[operand.getKey()].shape[i];
    }
    for(int64_t i=0; i< storage[operand.getKey()].ndim; i++) {
        storage[key].stride[i] = storage[operand.getKey()].stride[i];
    }
}

template <typename T>
template <typename ...Dimensions>       // Variadic constructor
multi_array<T>::multi_array(Dimensions... shape)
{
    init();

    storage[key].data        = NULL;
    storage[key].base        = NULL;
    storage[key].ndim        = sizeof...(Dimensions);
    storage[key].start       = 0;

    unpack_shape(storage[key].shape, 0, shape...);

    int64_t stride = 1;                 // Setup strides
    for(int64_t i=storage[key].ndim-1; 0 <= i; --i) {
        storage[key].stride[i] = stride;
        stride *= storage[key].shape[i];
    }
}

template <typename T>                   // Deconstructor
multi_array<T>::~multi_array()
{
    if (key>0) {
        if (NULL == storage[key].base) {    // Only send free on base-array
            Runtime::instance()->enqueue((bh_opcode)BH_FREE, *this);
        }
        Runtime::instance()->enqueue((bh_opcode)BH_DISCARD, *this);
        Runtime::instance()->trash(key);
    }
}

template <typename T>
inline
size_t multi_array<T>::getKey() const
{
    return key;
}

template <typename T>
inline
unsigned long multi_array<T>::getRank() const
{
    return (unsigned long)*(&storage[key].ndim);
}

template <typename T>
inline
bool multi_array<T>::getTemp() const
{
    return temp;
}

template <typename T>
inline
void multi_array<T>::setTemp(bool temp)
{
    this->temp = temp;
}

template <typename T>
inline
size_t multi_array<T>::len()
{
    size_t nelements = 1;
    for (int i = 0; i < storage[key].ndim; ++i) {
        nelements *= storage[key].shape[i];
    }
    return nelements;
}

template <typename T>
typename multi_array<T>::iterator multi_array<T>::begin()
{
    Runtime::instance()->enqueue((bh_opcode)BH_SYNC, *this);
    Runtime::instance()->flush();

    return multi_array<T>::iterator(storage[this->key]);
}

template <typename T>
typename multi_array<T>::iterator multi_array<T>::end()
{
    return multi_array<T>::iterator();
}

//
// Increment / decrement
//
template <typename T>
multi_array<T>& multi_array<T>::operator++()
{
    Runtime::instance()->enqueue((bh_opcode)BH_ADD, *this, *this, (T)1);
    return *this;
}

template <typename T>
multi_array<T>& multi_array<T>::operator++(int)
{
    Runtime::instance()->enqueue((bh_opcode)BH_ADD, *this, *this, (T)1);
    return *this;
}

template <typename T>
multi_array<T>& multi_array<T>::operator--()
{
    Runtime::instance()->enqueue((bh_opcode)BH_SUBTRACT, *this, *this, (T)1);
    return *this;
}

template <typename T>
multi_array<T>& multi_array<T>::operator--(int)
{
    Runtime::instance()->enqueue((bh_opcode)BH_SUBTRACT, *this, *this, (T)1);
    return *this;
}

//
// Output / Printing
//
template <typename T>
std::ostream& operator<< (std::ostream& stream, multi_array<T>& rhs)
{
    bool first = true;
    typename multi_array<T>::iterator it  = rhs.begin();
    typename multi_array<T>::iterator end = rhs.end();

    stream << "[ ";
    for(; it != end; it++) {
        if (!first) {
            stream  << ", ";
        } else {
            first = false;
        }
        stream << *it;
    }
    stream << " ]" << std::endl;

    if (rhs.getTemp()) {    // Cleanup temporary
        delete &rhs;
    }

    return stream;
}

//
// Slicing
//
template <typename T>
slice<T>& multi_array<T>::operator[](int rhs) {
    return (*(new slice<T>(*this)))[rhs];
}

template <typename T>
slice<T>& multi_array<T>::operator[](slice_range& rhs) {
    return (*(new slice<T>(*this)))[rhs];
}

// Initialization
template <typename T>
multi_array<T>& multi_array<T>::operator=(const T& rhs)
{
    Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *this, rhs);
    return *this;
}

// Linking
template <typename T>
void multi_array<T>::link(const size_t ext_key)
{
    if (0!=key) {
        throw std::runtime_error("Dude you are ALREADY linked!");
    }
    key = ext_key;
}

template <typename T>
size_t multi_array<T>::unlink()
{
    if (0==key) {
        throw std::runtime_error("Dude! THis one aint linked at all!");
    }

    size_t retKey = key;
    key = 0;
    return retKey;
}

// Aliasing
template <typename T>
multi_array<T>& multi_array<T>::operator=(multi_array<T>& rhs)
{
    if (key != rhs.getKey()) {      // Prevent self-aliasing

        if (key>0) {                // Release current linkage
            if (NULL == storage[key].base) {
                Runtime::instance()->enqueue((bh_opcode)BH_FREE, *this);
            }
            Runtime::instance()->enqueue((bh_opcode)BH_DISCARD, *this);
            unlink();
        }

        if (rhs.getTemp()) {        // Take over temporary reference
            link(rhs.unlink());
            temp = false;
            delete &rhs;
        } else {                    // Create an alias of rhs.
            init();

            storage[key].data       = NULL;
            storage[key].base       = &storage[rhs.getKey()];
            storage[key].ndim       = storage[rhs.getKey()].ndim;
            storage[key].start      = storage[rhs.getKey()].start;
            for(int64_t i=0; i< storage[rhs.getKey()].ndim; i++) {
                storage[key].shape[i] = storage[rhs.getKey()].shape[i];
            }
            for(int64_t i=0; i< storage[rhs.getKey()].ndim; i++) {
                storage[key].stride[i] = storage[rhs.getKey()].stride[i];
            }
        }
    }

    return *this;
}

/**
 *  Aliasing via slicing
 *
 *  Construct a view based on a slice.
 *  Such as:
 *
 *  center = grid[_(1,-1,1)][_(1,-1,1)];
 *
 *  TODO: this is probobaly not entirely correct...
 */
template <typename T>
multi_array<T>& multi_array<T>::operator=(slice<T>& rhs)
{
    multi_array<T>* vv = &rhs.view();

    if (key>0) {                // Release current linkage
        if (NULL == storage[key].base) {
            Runtime::instance()->enqueue((bh_opcode)BH_FREE, *this);
        }
        Runtime::instance()->enqueue((bh_opcode)BH_DISCARD, *this);
        unlink();
    }

    link(vv->unlink());
    delete vv;

    return *this;
}

//
// Typecasting
//
template <typename T> template <typename Ret>
multi_array<Ret>& multi_array<T>::as()
{
    multi_array<Ret>* result = &Runtime::instance()->temp<Ret>();
    result->setTemp(true);

    storage[result->getKey()].base        = NULL;
    storage[result->getKey()].ndim        = storage[this->getKey()].ndim;
    storage[result->getKey()].start       = storage[this->getKey()].start;
    for(int64_t i=0; i< storage[this->getKey()].ndim; i++) {
        storage[result->getKey()].shape[i] = storage[this->getKey()].shape[i];
    }
    for(int64_t i=0; i< storage[this->getKey()].ndim; i++) {

        storage[result->getKey()].stride[i] = storage[this->getKey()].stride[i];
    }
    storage[result->getKey()].data        = NULL;

    Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *result, *this);

    return *result;
}

//
// Update
//
template <typename T>
multi_array<T>& multi_array<T>::operator()(multi_array& rhs)
{
    if (1>key) {    // We do not have anything to update!
        throw std::runtime_error("Far out dude! you are trying to update "
                                 "something that does not exist!");
    }
    Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *this, rhs);

    return *this;
}

template <typename T>
multi_array<T>& multi_array<T>::operator()(const T& value) {

    if (1>key) {    // We do not have anything to update!
        throw std::runtime_error("Far out dude! you are trying to update "
                                 "something that does not exist!");
    }
    Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *this, value);

    return *this;
}

}

<|endoftext|>


<commit_before>/*
 * Firmware flashing tool for Blu-Ray drives using the Mediatek MT1939 chip.
 * Copyright (c) 2014 Micah Elizabeth Scott
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include <algorithm>
#include "mt1939.h"

int main(int argc, char** argv)
{
    TinySCSI scsi;
    MT1939::DeviceInfo info;
    MT1939::FirmwareImage fw;

    if (!MT1939::open(scsi)) {
        return 1;
    }

    if (!MT1939::deviceInfo(scsi, &info)) {
        return 1;
    }
    info.print();

    // Various usage formats...

    if (argc == 1) {
        return 0;

    } else if (argc == 2 && !strcmp("--erase", argv[1])) {
        fw.erase();

    } else if (argc >= 3 && !strcmp("--scsi", argv[1])) {

        uint8_t cdb[12];
        const char *dumpfile = "result.log";
        static uint8_t data[1024*1024*128];
        unsigned len = std::min<unsigned>(strtol(argv[2], 0, 16), sizeof data - 1);

        memset(cdb, 0, sizeof cdb);
        for (int i = 0; i < sizeof cdb; i++) {
            const char *arg = argv[3+i];
            if (!arg) {
                break;
            }
            cdb[i] = strtol(arg, 0, 16);
        }

        fprintf(stderr, "\nCDB:\n");
        hexdump(cdb, sizeof cdb);
        if (scsi.in(cdb, sizeof cdb, data, len)) {
            fprintf(stderr, "\nData returned:\n");
            hexdump(data, len);

            if (len) {
                FILE *f = fopen(dumpfile, "wb");
                if (f && fwrite(data, len, 1, f) == 1) {
                    fprintf(stderr, "Saved %d bytes to %s\n", len, dumpfile);
                    fclose(f);
                }
            }
        }
        return 0;

    } else if (argc == 2 && fw.open(argv[1])) {
        fprintf(stderr, "Firmware image loaded from disk\n");

    } else {
        fprintf(stderr,
            "\n"
            "usage:\n"
            "    mtflash           Shows device version info, changes nothing\n"
            "    mtflash fw.bin    Program a 2MB raw firmware image file.\n"
            "                      The first 64 kiB is locked and can't be programmed,\n"
            "                      so these bytes in the image are ignored.\n"
            "    mtflash --erase   Send an image of all 0xFFs, erasing the unlocked\n"
            "                      portions of flash.\n"
            "    mtflash --scsi    Send a low level SCSI command.\n"
            "\n"
            "scsi examples:\n"
            "    mtflash --scsi 60 12 00 00 00 60                    Long inquiry command\n"
            "    mtflash --scsi 8 ff 00 ff                           Firmware version\n"
            "    mtflash --scsi 2 ff 00 05                           Read appselect bit0\n"
            "    mtflash --scsi 0 ff 00 04 00 00 01                  Set appselect bit0\n"
            "    mtflash --scsi 0 ff 00 04 00 00 00                  Clear appselect bit0\n"
            "    mtflash --scsi ffff 3c 6 0 0 0 0 0 ff ff            Read first 64k of DRAM\n"
            );
        return 1;
    }

    fw.print();

    unsigned delay = 2;
    fprintf(stderr, "--- WRITING in %d seconds ---\n", delay);
    sleep(delay);

    if (!MT1939::writeFirmware(scsi, &fw)) {
        return 1;
    }

    return 0;
}
<commit_msg>Remove pre-flash delay<commit_after>/*
 * Firmware flashing tool for Blu-Ray drives using the Mediatek MT1939 chip.
 * Copyright (c) 2014 Micah Elizabeth Scott
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include <algorithm>
#include "mt1939.h"

int main(int argc, char** argv)
{
    TinySCSI scsi;
    MT1939::DeviceInfo info;
    MT1939::FirmwareImage fw;

    if (!MT1939::open(scsi)) {
        return 1;
    }

    if (!MT1939::deviceInfo(scsi, &info)) {
        return 1;
    }
    info.print();

    // Various usage formats...

    if (argc == 1) {
        return 0;

    } else if (argc == 2 && !strcmp("--erase", argv[1])) {
        fw.erase();

    } else if (argc >= 3 && !strcmp("--scsi", argv[1])) {

        uint8_t cdb[12];
        const char *dumpfile = "result.log";
        static uint8_t data[1024*1024*128];
        unsigned len = std::min<unsigned>(strtol(argv[2], 0, 16), sizeof data - 1);

        memset(cdb, 0, sizeof cdb);
        for (int i = 0; i < sizeof cdb; i++) {
            const char *arg = argv[3+i];
            if (!arg) {
                break;
            }
            cdb[i] = strtol(arg, 0, 16);
        }

        fprintf(stderr, "\nCDB:\n");
        hexdump(cdb, sizeof cdb);
        if (scsi.in(cdb, sizeof cdb, data, len)) {
            fprintf(stderr, "\nData returned:\n");
            hexdump(data, len);

            if (len) {
                FILE *f = fopen(dumpfile, "wb");
                if (f && fwrite(data, len, 1, f) == 1) {
                    fprintf(stderr, "Saved %d bytes to %s\n", len, dumpfile);
                    fclose(f);
                }
            }
        }
        return 0;

    } else if (argc == 2 && fw.open(argv[1])) {
        fprintf(stderr, "Firmware image loaded from disk\n");

    } else {
        fprintf(stderr,
            "\n"
            "usage:\n"
            "    mtflash           Shows device version info, changes nothing\n"
            "    mtflash fw.bin    Program a 2MB raw firmware image file.\n"
            "                      The first 64 kiB is locked and can't be programmed,\n"
            "                      so these bytes in the image are ignored.\n"
            "    mtflash --erase   Send an image of all 0xFFs, erasing the unlocked\n"
            "                      portions of flash.\n"
            "    mtflash --scsi    Send a low level SCSI command.\n"
            "\n"
            "scsi examples:\n"
            "    mtflash --scsi 60 12 00 00 00 60                    Long inquiry command\n"
            "    mtflash --scsi 8 ff 00 ff                           Firmware version\n"
            "    mtflash --scsi 2 ff 00 05                           Read appselect bit0\n"
            "    mtflash --scsi 0 ff 00 04 00 00 01                  Set appselect bit0\n"
            "    mtflash --scsi 0 ff 00 04 00 00 00                  Clear appselect bit0\n"
            "    mtflash --scsi ffff 3c 6 0 0 0 0 0 ff ff            Read first 64k of DRAM\n"
            );
        return 1;
    }

    fw.print();

    if (!MT1939::writeFirmware(scsi, &fw)) {
        return 1;
    }

    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: FDatabaseMetaDataResultSetMetaData.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 06:37:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_
#define _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_

#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HPP_
#include <com/sun/star/sdbc/XResultSetMetaData.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _VECTOR_
#include <vector>
#endif
#ifndef _CONNECTIVITY_FDATABASEMETADATARESULTSET_HXX_
#include "FDatabaseMetaDataResultSet.hxx"
#endif
#ifndef _CONNECTIVITY_COLUMN_HXX_
#include "OColumn.hxx"
#endif
#ifndef CONNECTIVITY_STDTYPEDEFS_HXX
#include "connectivity/StdTypeDefs.hxx"
#endif

namespace connectivity
{
    //**************************************************************
    //************ Class: ODatabaseMetaDataResultSetMetaData
    //**************************************************************
    typedef ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData>   ODatabaseMetaResultSetMetaData_BASE;

    class ODatabaseMetaDataResultSetMetaData :  public  ODatabaseMetaResultSetMetaData_BASE
    {
        TIntVector                                  m_vMapping; // when not every column is needed
        ::std::map<sal_Int32,connectivity::OColumn> m_mColumns;
        ::std::map<sal_Int32,connectivity::OColumn>::const_iterator m_mColumnsIter;

        sal_Int32                                   m_nColCount;
    protected:
        virtual ~ODatabaseMetaDataResultSetMetaData();
    public:
        // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
        ODatabaseMetaDataResultSetMetaData( )
                :   m_nColCount(0)
        {
        }
        /// Avoid ambigous cast error from the compiler.
        inline operator ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > () throw()
        { return this; }

        virtual sal_Int32 SAL_CALL getColumnCount(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

        // methods to set the right column mapping
        void setColumnPrivilegesMap();
        void setColumnsMap();
        void setTablesMap();
        void setProcedureColumnsMap();
        void setPrimaryKeysMap();
        void setIndexInfoMap();
        void setTablePrivilegesMap();
        void setCrossReferenceMap();
        void setTypeInfoMap();
        void setProceduresMap();
        void setTableTypes();
        void setBestRowIdentifierMap() { setVersionColumnsMap();}
        void setVersionColumnsMap();
        void setExportedKeysMap() { setCrossReferenceMap(); }
        void setImportedKeysMap() { setCrossReferenceMap(); }
        void setCatalogsMap();
        void setSchemasMap();
    };
}
#endif // _CONNECTIVITY_FILE_ADATABASEMETARESULTSETMETADATA_HXX_

<commit_msg>INTEGRATION: CWS oj14 (1.5.26); FILE MERGED 2006/11/08 08:00:58 oj 1.5.26.1: add missing methods<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: FDatabaseMetaDataResultSetMetaData.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-06 06:48:34 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_
#define _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_

#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HPP_
#include <com/sun/star/sdbc/XResultSetMetaData.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _VECTOR_
#include <vector>
#endif
#ifndef _CONNECTIVITY_FDATABASEMETADATARESULTSET_HXX_
#include "FDatabaseMetaDataResultSet.hxx"
#endif
#ifndef _CONNECTIVITY_COLUMN_HXX_
#include "OColumn.hxx"
#endif
#ifndef CONNECTIVITY_STDTYPEDEFS_HXX
#include "connectivity/StdTypeDefs.hxx"
#endif

namespace connectivity
{
    //**************************************************************
    //************ Class: ODatabaseMetaDataResultSetMetaData
    //**************************************************************
    typedef ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData>   ODatabaseMetaResultSetMetaData_BASE;

    class ODatabaseMetaDataResultSetMetaData :  public  ODatabaseMetaResultSetMetaData_BASE
    {
        TIntVector                                  m_vMapping; // when not every column is needed
        ::std::map<sal_Int32,connectivity::OColumn> m_mColumns;
        ::std::map<sal_Int32,connectivity::OColumn>::const_iterator m_mColumnsIter;

        sal_Int32                                   m_nColCount;
    protected:
        virtual ~ODatabaseMetaDataResultSetMetaData();
    public:
        // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
        ODatabaseMetaDataResultSetMetaData( )
                :   m_nColCount(0)
        {
        }
        /// Avoid ambigous cast error from the compiler.
        inline operator ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > () throw()
        { return this; }

        virtual sal_Int32 SAL_CALL getColumnCount(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

        // methods to set the right column mapping
        void setColumnPrivilegesMap();
        void setColumnMap();
        void setColumnsMap();
        void setTableNameMap();
        void setTablesMap();
        void setProcedureColumnsMap();
        void setPrimaryKeysMap();
        void setIndexInfoMap();
        void setTablePrivilegesMap();
        void setCrossReferenceMap();
        void setTypeInfoMap();
        void setProcedureNameMap();
        void setProceduresMap();
        void setTableTypes();
        void setBestRowIdentifierMap() { setVersionColumnsMap();}
        void setVersionColumnsMap();
        void setExportedKeysMap() { setCrossReferenceMap(); }
        void setImportedKeysMap() { setCrossReferenceMap(); }
        void setCatalogsMap();
        void setSchemasMap();
    };
}
#endif // _CONNECTIVITY_FILE_ADATABASEMETARESULTSETMETADATA_HXX_

<|endoftext|>