<commit_before>#include "execHelperOptions.h"

#include <iostream>
#include <string>

#include <boost/program_options.hpp>

#include "log/log.h"
#include "yaml/yaml.h"
#include "config/settingsNode.h"
#include "compiler.h"
#include "mode.h"
#include "executorInterface.h"

using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::shared_ptr;
using std::make_shared;

using boost::program_options::options_description;
using boost::program_options::variables_map;
using boost::program_options::store;
using boost::program_options::notify;
using boost::program_options::command_line_parser;
using boost::program_options::value;
using boost::program_options::positional_options_description;

using execHelper::core::CommandCollection;
using execHelper::core::TargetDescription;
using execHelper::core::CompilerDescription;
using execHelper::core::AnalyzeDescription;

using execHelper::config::SettingsNode;

using execHelper::yaml::Yaml;
using execHelper::yaml::YamlFile;

namespace {
    options_description getOptionDescriptions() {
        options_description descriptions("Allowed options");
        descriptions.add_options()
            ("help,h", "Produce help message")
            ("verbose,v", "Set verbosity")
            ("command,z", value<CommandCollection>()->multitoken(), "Set commands")
            ("target,t", value<TargetDescription::TargetCollection>()->multitoken(), "Set targets")
            ("run-target,r", value<TargetDescription::RunTargetCollection>()->multitoken(), "Set run targets")
            ("compiler,c", value<CompilerDescription::CompilerNames>()->multitoken(), "Set compilers")
            ("mode,m", value<CompilerDescription::ModeNames>()->multitoken(), "Set modes")
            ("architecture,a", value<CompilerDescription::ArchitectureNames>()->multitoken(), "Set architecture")
            ("distribution,d", value<CompilerDescription::DistributionNames>()->multitoken(), "Set distribution")
            ("analyze,y", value<AnalyzeDescription::AnalyzeCollection>()->multitoken(), "Set analyze methods")
            ("settings-file,s", value<string>(), "Set settings file")
            ("single-threaded,u", "Set multithreaded")
        ;
        return descriptions;
    }

    variables_map getOptionsMap(int argc, const char* const * argv) {
        const options_description optionDescriptions = getOptionDescriptions();

        // Assign positional arguments
        positional_options_description positionalOptionsDesc;
        positionalOptionsDesc.add("command", -1);

        variables_map optionsMap;
        store(command_line_parser(argc, argv).options(optionDescriptions).positional(positionalOptionsDesc).run(), optionsMap);
        notify(optionsMap);
        return optionsMap;
    }

}

namespace execHelper { namespace core {
    ExecHelperOptions::ExecHelperOptions() noexcept :
        m_help(false),
        m_verbose(false),
        m_singleThreaded(false),
        m_target(new TargetDescription({"all"}, {"all"})),
        m_compiler(new CompilerDescription({Compiler("gcc")}, {Mode("release")}, {Architecture("x64")}, {Distribution("arch-linux")})),
        m_analyze(new AnalyzeDescription({"cppcheck", "clang-static-analyzer"}))
    {
        ;
    }

    ExecHelperOptions::ExecHelperOptions(const ExecHelperOptions& other) noexcept :
        m_help(other.m_help),
        m_verbose(other.m_verbose),
        m_singleThreaded(other.m_singleThreaded),
        m_target(new TargetDescription(other.getTarget().getTargets(), other.getTarget().getRunTargets())),
        m_compiler(new CompilerDescription(other.getCompiler().getCompilers(), other.getCompiler().getModes(), other.getCompiler().getArchitectures(), other.getCompiler().getDistributions())),
        m_analyze(new AnalyzeDescription(other.getAnalyzeMethods())),
        m_settings(other.m_settings),
        m_executor(other.m_executor)
    {
        ;
    }

    bool ExecHelperOptions::getVerbosity() const noexcept {
        return m_verbose;
    }

    bool ExecHelperOptions::getSingleThreaded() const noexcept {
        return m_singleThreaded;
    }

    const CommandCollection& ExecHelperOptions::getCommands() const noexcept {
        return m_commands;
    }

    const CompilerDescription& ExecHelperOptions::getCompiler() const noexcept {
        assert(m_compiler);
        return *m_compiler;
    }

    const TargetDescription& ExecHelperOptions::getTarget() const noexcept {
        assert(m_target);
        return *m_target;
    }

    const AnalyzeDescription& ExecHelperOptions::getAnalyzeMethods() const noexcept {
        assert(m_analyze);
        return *m_analyze;
    }

    string ExecHelperOptions::getSettingsFile(int argc, const char* const * argv) const noexcept {
        variables_map optionsMap = getOptionsMap(argc, argv);
        if(optionsMap.count("settings-file")) {
            return optionsMap["settings-file"].as<string>();
        }
        return ".exec-helper";
    }

    bool ExecHelperOptions::parse(int argc, const char* const * argv) {
        variables_map optionsMap = getOptionsMap(argc, argv);
        if(optionsMap.count("help")) {
            m_help = true;
            return true;
        }

        if(optionsMap.count("verbose")) {
            m_verbose = true;
        }

        if(optionsMap.count("single-threaded")) {
            m_singleThreaded = true;
        }

        if(optionsMap.count("command")) {
            m_commands.clear();
            m_commands = optionsMap["command"].as<CommandCollection>();
        }

        if(optionsMap.count("target")) {
            TargetDescription::TargetCollection targets = optionsMap["target"].as<TargetDescription::TargetCollection>();
            m_target.reset(new TargetDescription(targets, m_target->getRunTargets()));
        }

        if(optionsMap.count("run-target")) {
            TargetDescription::RunTargetCollection runTargets = optionsMap["run-target"].as<TargetDescription::RunTargetCollection>();
            m_target.reset(new TargetDescription(m_target->getTargets(), runTargets));
        }

        if(optionsMap.count("compiler")) {
            CompilerDescription::CompilerCollection compilers = CompilerDescription::convertToCompilerCollection(optionsMap["compiler"].as<CompilerDescription::CompilerNames>());
            m_compiler.reset(new CompilerDescription(compilers, m_compiler->getModes(), m_compiler->getArchitectures(), m_compiler->getDistributions()));
        }

        if(optionsMap.count("mode")) {
            CompilerDescription::ModeCollection modes = CompilerDescription::convertToModeCollection(optionsMap["mode"].as<CompilerDescription::ModeNames>());
            m_compiler.reset(new CompilerDescription(m_compiler->getCompilers(), modes, m_compiler->getArchitectures(), m_compiler->getDistributions()));
        }

        if(optionsMap.count("architecture")) {
            CompilerDescription::ArchitectureCollection architectures = CompilerDescription::convertToArchitectureCollection(optionsMap["architecture"].as<CompilerDescription::ArchitectureNames>());
            m_compiler.reset(new CompilerDescription(m_compiler->getCompilers(), m_compiler->getModes(), architectures, m_compiler->getDistributions()));
        }

        if(optionsMap.count("distribution")) {
            CompilerDescription::DistributionCollection distributions = CompilerDescription::convertToDistributionCollection(optionsMap["distribution"].as<CompilerDescription::DistributionNames>());
            m_compiler.reset(new CompilerDescription(m_compiler->getCompilers(), m_compiler->getModes(), m_compiler->getArchitectures(), distributions));
        }

        if(optionsMap.count("analyze")) {
            AnalyzeDescription::AnalyzeCollection analyzeMethods = optionsMap["analyze"].as<AnalyzeDescription::AnalyzeCollection>();
            m_analyze.reset(new AnalyzeDescription(analyzeMethods));
        }

        return true;
    }

    bool ExecHelperOptions::parseSettingsFile(const std::string& file) noexcept {
        YamlFile yamlFile;
        yamlFile.file = file;
        Yaml yaml(yamlFile);
        if(! yaml.getTree({}, m_settings)) {
            LOG("Could not get settings tree");
            return false;
        }

        if(m_settings.contains("default-targets")) {
            TargetDescription::TargetCollection targets = m_settings["default-targets"].toStringCollection();
            m_target.reset(new TargetDescription(targets, m_target->getRunTargets()));
        }

        if(m_settings.contains("default-run-targets")) {
            TargetDescription::RunTargetCollection runTargets = m_settings["default-run-targets"].toStringCollection();
            m_target.reset(new TargetDescription(m_target->getTargets(), runTargets));
        }

        if(m_settings.contains("default-compilers")) {
            CompilerDescription::CompilerCollection compilers = CompilerDescription::convertToCompilerCollection(m_settings["default-compilers"].toStringCollection());
            m_compiler.reset(new CompilerDescription(compilers, m_compiler->getModes(), m_compiler->getArchitectures(), m_compiler->getDistributions()));
        }

        if(m_settings.contains("default-modes")) {
            CompilerDescription::ModeCollection modes = CompilerDescription::convertToModeCollection(m_settings["default-modes"].toStringCollection());
            m_compiler.reset(new CompilerDescription(m_compiler->getCompilers(), modes, m_compiler->getArchitectures(), m_compiler->getDistributions()));
        }

        if(m_settings.contains("default-architectures")) {
            CompilerDescription::ArchitectureCollection architectures = CompilerDescription::convertToArchitectureCollection(m_settings["default-architectures"].toStringCollection());
            m_compiler.reset(new CompilerDescription(m_compiler->getCompilers(), m_compiler->getModes(), architectures, m_compiler->getDistributions()));
        }

        if(m_settings.contains("default-distributions")) {
            CompilerDescription::DistributionCollection distributions = CompilerDescription::convertToDistributionCollection(m_settings["default-distributions"].toStringCollection());
            m_compiler.reset(new CompilerDescription(m_compiler->getCompilers(), m_compiler->getModes(), m_compiler->getArchitectures(), distributions));
        }
        return true;
    }

    bool ExecHelperOptions::containsHelp() const noexcept {
        return m_help;
    }

    const config::SettingsNode& ExecHelperOptions::getSettings() const noexcept {
        return m_settings;
    }

    config::SettingsNode& ExecHelperOptions::getSettings(const std::string& key) noexcept {
        if(m_settings.contains(key)) {
            return m_settings[key];
        }
        return m_settings;
    }

    const config::SettingsNode& ExecHelperOptions::getSettings(const std::string& key) const noexcept {
        if(m_settings.contains(key)) {
            return m_settings[key];
        }
        return m_settings;
    }

    void ExecHelperOptions::setExecutor(ExecutorInterface* const executor) noexcept {
        m_executor = executor;
    }

    ExecutorInterface* ExecHelperOptions::getExecutor() const noexcept {
        return m_executor;
    }

    void ExecHelperOptions::printHelp() const noexcept {
        user_feedback(getOptionDescriptions());
    }

    shared_ptr<Options> ExecHelperOptions::clone() const noexcept {
        return make_shared<ExecHelperOptions>(*this);
    }
} }
<commit_msg>Preparation for adding options at runtime later on.<commit_after>#include "execHelperOptions.h"

#include <iostream>
#include <string>

#include <boost/program_options.hpp>

#include "log/log.h"
#include "yaml/yaml.h"
#include "config/settingsNode.h"
#include "compiler.h"
#include "mode.h"
#include "executorInterface.h"

using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::shared_ptr;
using std::make_shared;

using boost::program_options::options_description;
using boost::program_options::variables_map;
using boost::program_options::store;
using boost::program_options::notify;
using boost::program_options::command_line_parser;
using boost::program_options::value;
using boost::program_options::positional_options_description;

using execHelper::core::CommandCollection;
using execHelper::core::TargetDescription;
using execHelper::core::CompilerDescription;
using execHelper::core::AnalyzeDescription;

using execHelper::config::SettingsNode;

using execHelper::yaml::Yaml;
using execHelper::yaml::YamlFile;

namespace {
    class OptionDescriptions {
        public:
            OptionDescriptions() {
                // Add the default options
                m_optionDescription.add_options()
                    ("help,h", "Produce help message")
                    ("verbose,v", "Set verbosity")
                    ("command,z", value<CommandCollection>()->multitoken(), "Set commands")
                    ("target,t", value<TargetDescription::TargetCollection>()->multitoken(), "Set targets")
                    ("run-target,r", value<TargetDescription::RunTargetCollection>()->multitoken(), "Set run targets")
                    ("compiler,c", value<CompilerDescription::CompilerNames>()->multitoken(), "Set compilers")
                    ("mode,m", value<CompilerDescription::ModeNames>()->multitoken(), "Set modes")
                    ("architecture,a", value<CompilerDescription::ArchitectureNames>()->multitoken(), "Set architecture")
                    ("distribution,d", value<CompilerDescription::DistributionNames>()->multitoken(), "Set distribution")
                    ("analyze,y", value<AnalyzeDescription::AnalyzeCollection>()->multitoken(), "Set analyze methods")
                    ("settings-file,s", value<string>(), "Set settings file")
                    ("single-threaded,u", "Set multithreaded")
                ;
            }

            options_description getOptionDescriptions() {
                return m_optionDescription;
            }

            variables_map getOptionsMap(int argc, const char* const* argv, bool allowUnregistered = false) {
                // Assign positional arguments
                positional_options_description positionalOptionsDesc;
                positionalOptionsDesc.add("command", -1);

                variables_map optionsMap;
                if(! allowUnregistered) {
                    store(command_line_parser(argc, argv).options(m_optionDescription).positional(positionalOptionsDesc).run(), optionsMap);
                } else {
                    store(command_line_parser(argc, argv).options(m_optionDescription).positional(positionalOptionsDesc).options(m_optionDescription).allow_unregistered().run(), optionsMap);
                }
                notify(optionsMap);
                return optionsMap;
            }

        private:
            options_description m_optionDescription;
    };

    OptionDescriptions optionsDescriptions;
}

namespace execHelper { namespace core {
    ExecHelperOptions::ExecHelperOptions() noexcept :
        m_help(false),
        m_verbose(false),
        m_singleThreaded(false),
        m_target(new TargetDescription({"all"}, {"all"})),
        m_compiler(new CompilerDescription({Compiler("gcc")}, {Mode("release")}, {Architecture("x64")}, {Distribution("arch-linux")})),
        m_analyze(new AnalyzeDescription({"cppcheck", "clang-static-analyzer"}))
    {
        ;
    }

    ExecHelperOptions::ExecHelperOptions(const ExecHelperOptions& other) noexcept :
        m_help(other.m_help),
        m_verbose(other.m_verbose),
        m_singleThreaded(other.m_singleThreaded),
        m_target(new TargetDescription(other.getTarget().getTargets(), other.getTarget().getRunTargets())),
        m_compiler(new CompilerDescription(other.getCompiler().getCompilers(), other.getCompiler().getModes(), other.getCompiler().getArchitectures(), other.getCompiler().getDistributions())),
        m_analyze(new AnalyzeDescription(other.getAnalyzeMethods())),
        m_settings(other.m_settings),
        m_executor(other.m_executor)
    {
        ;
    }

    bool ExecHelperOptions::getVerbosity() const noexcept {
        return m_verbose;
    }

    bool ExecHelperOptions::getSingleThreaded() const noexcept {
        return m_singleThreaded;
    }

    const CommandCollection& ExecHelperOptions::getCommands() const noexcept {
        return m_commands;
    }

    const CompilerDescription& ExecHelperOptions::getCompiler() const noexcept {
        assert(m_compiler);
        return *m_compiler;
    }

    const TargetDescription& ExecHelperOptions::getTarget() const noexcept {
        assert(m_target);
        return *m_target;
    }

    const AnalyzeDescription& ExecHelperOptions::getAnalyzeMethods() const noexcept {
        assert(m_analyze);
        return *m_analyze;
    }

    string ExecHelperOptions::getSettingsFile(int argc, const char* const * argv) const noexcept {
        variables_map optionsMap = optionsDescriptions.getOptionsMap(argc, argv, true);
        if(optionsMap.count("settings-file")) {
            return optionsMap["settings-file"].as<string>();
        }
        return ".exec-helper";
    }

    bool ExecHelperOptions::parse(int argc, const char* const * argv) {
        variables_map optionsMap = optionsDescriptions.getOptionsMap(argc, argv);
        if(optionsMap.count("help")) {
            m_help = true;
            return true;
        }

        if(optionsMap.count("verbose")) {
            m_verbose = true;
        }

        if(optionsMap.count("single-threaded")) {
            m_singleThreaded = true;
        }

        if(optionsMap.count("command")) {
            m_commands.clear();
            m_commands = optionsMap["command"].as<CommandCollection>();
        }

        if(optionsMap.count("target")) {
            TargetDescription::TargetCollection targets = optionsMap["target"].as<TargetDescription::TargetCollection>();
            m_target.reset(new TargetDescription(targets, m_target->getRunTargets()));
        }

        if(optionsMap.count("run-target")) {
            TargetDescription::RunTargetCollection runTargets = optionsMap["run-target"].as<TargetDescription::RunTargetCollection>();
            m_target.reset(new TargetDescription(m_target->getTargets(), runTargets));
        }

        if(optionsMap.count("compiler")) {
            CompilerDescription::CompilerCollection compilers = CompilerDescription::convertToCompilerCollection(optionsMap["compiler"].as<CompilerDescription::CompilerNames>());
            m_compiler.reset(new CompilerDescription(compilers, m_compiler->getModes(), m_compiler->getArchitectures(), m_compiler->getDistributions()));
        }

        if(optionsMap.count("mode")) {
            CompilerDescription::ModeCollection modes = CompilerDescription::convertToModeCollection(optionsMap["mode"].as<CompilerDescription::ModeNames>());
            m_compiler.reset(new CompilerDescription(m_compiler->getCompilers(), modes, m_compiler->getArchitectures(), m_compiler->getDistributions()));
        }

        if(optionsMap.count("architecture")) {
            CompilerDescription::ArchitectureCollection architectures = CompilerDescription::convertToArchitectureCollection(optionsMap["architecture"].as<CompilerDescription::ArchitectureNames>());
            m_compiler.reset(new CompilerDescription(m_compiler->getCompilers(), m_compiler->getModes(), architectures, m_compiler->getDistributions()));
        }

        if(optionsMap.count("distribution")) {
            CompilerDescription::DistributionCollection distributions = CompilerDescription::convertToDistributionCollection(optionsMap["distribution"].as<CompilerDescription::DistributionNames>());
            m_compiler.reset(new CompilerDescription(m_compiler->getCompilers(), m_compiler->getModes(), m_compiler->getArchitectures(), distributions));
        }

        if(optionsMap.count("analyze")) {
            AnalyzeDescription::AnalyzeCollection analyzeMethods = optionsMap["analyze"].as<AnalyzeDescription::AnalyzeCollection>();
            m_analyze.reset(new AnalyzeDescription(analyzeMethods));
        }

        return true;
    }

    bool ExecHelperOptions::parseSettingsFile(const std::string& file) noexcept {
        YamlFile yamlFile;
        yamlFile.file = file;
        Yaml yaml(yamlFile);
        if(! yaml.getTree({}, m_settings)) {
            LOG("Could not get settings tree");
            return false;
        }

        if(m_settings.contains("default-targets")) {
            TargetDescription::TargetCollection targets = m_settings["default-targets"].toStringCollection();
            m_target.reset(new TargetDescription(targets, m_target->getRunTargets()));
        }

        if(m_settings.contains("default-run-targets")) {
            TargetDescription::RunTargetCollection runTargets = m_settings["default-run-targets"].toStringCollection();
            m_target.reset(new TargetDescription(m_target->getTargets(), runTargets));
        }

        if(m_settings.contains("default-compilers")) {
            CompilerDescription::CompilerCollection compilers = CompilerDescription::convertToCompilerCollection(m_settings["default-compilers"].toStringCollection());
            m_compiler.reset(new CompilerDescription(compilers, m_compiler->getModes(), m_compiler->getArchitectures(), m_compiler->getDistributions()));
        }

        if(m_settings.contains("default-modes")) {
            CompilerDescription::ModeCollection modes = CompilerDescription::convertToModeCollection(m_settings["default-modes"].toStringCollection());
            m_compiler.reset(new CompilerDescription(m_compiler->getCompilers(), modes, m_compiler->getArchitectures(), m_compiler->getDistributions()));
        }

        if(m_settings.contains("default-architectures")) {
            CompilerDescription::ArchitectureCollection architectures = CompilerDescription::convertToArchitectureCollection(m_settings["default-architectures"].toStringCollection());
            m_compiler.reset(new CompilerDescription(m_compiler->getCompilers(), m_compiler->getModes(), architectures, m_compiler->getDistributions()));
        }

        if(m_settings.contains("default-distributions")) {
            CompilerDescription::DistributionCollection distributions = CompilerDescription::convertToDistributionCollection(m_settings["default-distributions"].toStringCollection());
            m_compiler.reset(new CompilerDescription(m_compiler->getCompilers(), m_compiler->getModes(), m_compiler->getArchitectures(), distributions));
        }
        return true;
    }

    bool ExecHelperOptions::containsHelp() const noexcept {
        return m_help;
    }

    const config::SettingsNode& ExecHelperOptions::getSettings() const noexcept {
        return m_settings;
    }

    config::SettingsNode& ExecHelperOptions::getSettings(const std::string& key) noexcept {
        if(m_settings.contains(key)) {
            return m_settings[key];
        }
        return m_settings;
    }

    const config::SettingsNode& ExecHelperOptions::getSettings(const std::string& key) const noexcept {
        if(m_settings.contains(key)) {
            return m_settings[key];
        }
        return m_settings;
    }

    void ExecHelperOptions::setExecutor(ExecutorInterface* const executor) noexcept {
        m_executor = executor;
    }

    ExecutorInterface* ExecHelperOptions::getExecutor() const noexcept {
        return m_executor;
    }

    void ExecHelperOptions::printHelp() const noexcept {
        user_feedback(optionsDescriptions.getOptionDescriptions());
    }

    shared_ptr<Options> ExecHelperOptions::clone() const noexcept {
        return make_shared<ExecHelperOptions>(*this);
    }
} }
<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <MTheme>

#include "mcontainer.h"
#include "mcontainer_p.h"

#include "mwidgetcreator.h"
M_REGISTER_WIDGET(MContainer)

MContainerPrivate::MContainerPrivate()
{
}

MContainerPrivate::~MContainerPrivate()
{
}

void MContainerPrivate::_q_onCentralWidgetDestroyed()
{
    Q_Q(MContainer);
    q->model()->setCentralWidget(0);
}

void MContainerPrivate::init(const QString &newTitle)
{
    Q_Q(MContainer);

    q->model()->setCentralWidget(new MWidget(q));

    q->setTitle(newTitle);
}

MContainer::MContainer(QGraphicsItem *parent)
    : MWidgetController(new MContainerPrivate(), new MContainerModel(), parent)
{
    Q_D(MContainer);

    d->init();
}

MContainer::MContainer(const QString &title, QGraphicsItem *parent)
    : MWidgetController(new MContainerPrivate(), new MContainerModel(), parent)
{
    Q_D(MContainer);

    d->init(title);
}

MContainer::~MContainer()
{
}

QGraphicsWidget *MContainer::centralWidget()
{
    return model()->centralWidget();
}

void MContainer::setCentralWidget(QGraphicsWidget *centralWidget, bool destroy)
{
    QGraphicsWidget *oldCentralWidget = model()->centralWidget();

    // Set the new central widget
    model()->setCentralWidget(centralWidget);

    // Destroy the old central widget if requested
    if (destroy) {
        delete oldCentralWidget;

        if (centralWidget)
            connect(centralWidget, SIGNAL(destroyed()), SLOT(_q_onCentralWidgetDestroyed()));
    } else {
        // pass the ownership back to the caller.
        oldCentralWidget->setParentItem(0);
        oldCentralWidget->setParent(0);
        if (scene())
            scene()->removeItem(oldCentralWidget);

        if (oldCentralWidget)
            disconnect(oldCentralWidget, SIGNAL(destroyed()), this, SLOT(_q_onCentralWidgetDestroyed()));
    }

}

QString MContainer::title() const
{
    return model()->title();
}

void MContainer::setTitle(const QString &newTitle)
{
    model()->setTitle(newTitle);
}

QString MContainer::text() const
{
    return model()->text();
}

void MContainer::setText(const QString &text)
{
    model()->setText(text);
}

QString MContainer::iconID() const
{
    return model()->icon();
}

void MContainer::setIconID(const QString &iconID)
{
    model()->setIcon(iconID);
}

bool MContainer::headerVisible() const
{
    return model()->headerVisible();
}

void MContainer::setHeaderVisible(const bool visibility)
{
    model()->setHeaderVisible(visibility);
}

void MContainer::toggleHeaderVisible()
{
    setHeaderVisible(!model()->headerVisible());
}

bool MContainer::isProgressIndicatorVisible() const
{
    return model()->progressIndicatorVisible();
}

void MContainer::setProgressIndicatorVisible(bool visibility)
{
    model()->setProgressIndicatorVisible(visibility);
}

void MContainer::toggleProgressIndicatorVisible()
{
    setProgressIndicatorVisible(!isProgressIndicatorVisible());
}

#include "moc_mcontainer.cpp"
<commit_msg>Revert "Changes: MContainer should set only one size policy."<commit_after>/***************************************************************************
**
** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <MTheme>

#include "mcontainer.h"
#include "mcontainer_p.h"

#include "mwidgetcreator.h"
M_REGISTER_WIDGET(MContainer)

MContainerPrivate::MContainerPrivate()
{
}

MContainerPrivate::~MContainerPrivate()
{
}

void MContainerPrivate::_q_onCentralWidgetDestroyed()
{
    Q_Q(MContainer);
    q->model()->setCentralWidget(0);
}

void MContainerPrivate::init(const QString &newTitle)
{
    Q_Q(MContainer);

    q->model()->setCentralWidget(new MWidget(q));

    q->setTitle(newTitle);

    q->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}

MContainer::MContainer(QGraphicsItem *parent)
    : MWidgetController(new MContainerPrivate(), new MContainerModel(), parent)
{
    Q_D(MContainer);

    d->init();
}

MContainer::MContainer(const QString &title, QGraphicsItem *parent)
    : MWidgetController(new MContainerPrivate(), new MContainerModel(), parent)
{
    Q_D(MContainer);

    d->init(title);
}

MContainer::~MContainer()
{
}

QGraphicsWidget *MContainer::centralWidget()
{
    return model()->centralWidget();
}

void MContainer::setCentralWidget(QGraphicsWidget *centralWidget, bool destroy)
{
    QGraphicsWidget *oldCentralWidget = model()->centralWidget();

    // Set the new central widget
    model()->setCentralWidget(centralWidget);

    // Destroy the old central widget if requested
    if (destroy) {
        delete oldCentralWidget;

        if (centralWidget)
            connect(centralWidget, SIGNAL(destroyed()), SLOT(_q_onCentralWidgetDestroyed()));
    } else {
        // pass the ownership back to the caller.
        oldCentralWidget->setParentItem(0);
        oldCentralWidget->setParent(0);
        if (scene())
            scene()->removeItem(oldCentralWidget);

        if (oldCentralWidget)
            disconnect(oldCentralWidget, SIGNAL(destroyed()), this, SLOT(_q_onCentralWidgetDestroyed()));
    }

}

QString MContainer::title() const
{
    return model()->title();
}

void MContainer::setTitle(const QString &newTitle)
{
    model()->setTitle(newTitle);
}

QString MContainer::text() const
{
    return model()->text();
}

void MContainer::setText(const QString &text)
{
    model()->setText(text);
}

QString MContainer::iconID() const
{
    return model()->icon();
}

void MContainer::setIconID(const QString &iconID)
{
    model()->setIcon(iconID);
}

bool MContainer::headerVisible() const
{
    return model()->headerVisible();
}

void MContainer::setHeaderVisible(const bool visibility)
{
    model()->setHeaderVisible(visibility);
}

void MContainer::toggleHeaderVisible()
{
    setHeaderVisible(!model()->headerVisible());
}

bool MContainer::isProgressIndicatorVisible() const
{
    return model()->progressIndicatorVisible();
}

void MContainer::setProgressIndicatorVisible(bool visibility)
{
    model()->setProgressIndicatorVisible(visibility);
}

void MContainer::toggleProgressIndicatorVisible()
{
    setProgressIndicatorVisible(!isProgressIndicatorVisible());
}

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


<commit_before>/*
*    Copyright (c) <2002-2009> <Jean-Philippe Barrette-LaPierre>
*
*    Permission is hereby granted, free of charge, to any person obtaining
*    a copy of this software and associated documentation files
*    (curlpp), 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 "curlpp/internal/global.h"
#include "curlpp/internal/CurlHandle.hpp"

#include "curlpp/cURLpp.hpp"
#include "curlpp/Exception.hpp"

#include <string>
#include <iostream>
#include <memory>
#include <cstring>

using std::memset;
using std::auto_ptr;

namespace curlpp
{

namespace internal
{

void CurlHandle::perform()
{
	CURLcode code;

	code = curl_easy_perform(mCurl);
	throwException();
	libcurlRuntimeAssert(mErrorBuffer, code); //if we got an error
}

void CurlHandle::reset()
{
	curl_easy_reset(mCurl);
	memset(mErrorBuffer,0,CURL_ERROR_SIZE + 1);
	errorBuffer(mErrorBuffer);
}

CURL * CurlHandle::getHandle() const
{
	return mCurl;
}

CurlHandle::CurlHandle()
	: mException(NULL)
{
	memset(mErrorBuffer,0,CURL_ERROR_SIZE + 1);
	mCurl = curl_easy_init();
	runtimeAssert("Error when trying to curl_easy_init() a handle", mCurl != NULL);
	errorBuffer(mErrorBuffer);
}

CurlHandle::CurlHandle(CURL * handle)
	: mException(NULL)
{
	memset(mErrorBuffer,0,CURL_ERROR_SIZE + 1);
	mCurl = handle;
	runtimeAssert("Error when trying to curl_easy_init() a handle", mCurl != NULL);
	errorBuffer(mErrorBuffer);
}

std::auto_ptr<CurlHandle>
CurlHandle::clone() const
{
	CURL * cHandle = curl_easy_duphandle(mCurl);
	runtimeAssert("Error when trying to curl_easy_duphandle() a handle", cHandle != NULL);
	auto_ptr<CurlHandle> newHandle(new CurlHandle(cHandle));

	return newHandle;
}

CurlHandle::~CurlHandle()
{
	if (mException)
	{
		delete mException;
		mException = NULL;
	}
	curl_easy_cleanup(mCurl);
}

void
CurlHandle::setException(curlpp::CallbackExceptionBase * e)
{
	if(mException)
	{
		delete mException;
	}

	mException = e;
}

void
CurlHandle::errorBuffer(char * buffer)
{
	option(CURLOPT_ERRORBUFFER, (void *)buffer);
}

template<typename FunctorType>
typename FunctorType::ResultType
CurlHandle::execute(FunctorType functor, typename FunctorType::ParamList params)
{
	if (!functor)
	{
	 	setException(new CallbackException<curlpp::LogicError>(curlpp::LogicError("Null functor")));
		return CURLE_ABORTED_BY_CALLBACK;
	}

	try
	{
		return functor(params);
	}

	catch(curlpp::CallbackExceptionBase * e)
	{
		setException(e);
	}

	catch(...)
	{
		setException(new CallbackException<curlpp::UnknowException>(curlpp::UnknowException()));
	}

	return CURLE_ABORTED_BY_CALLBACK;
}

size_t
CurlHandle::executeWriteFunctor(char * buffer, size_t size, size_t nitems)
{
	if (!mWriteFunctor)
	{
		setException(new CallbackException<curlpp::LogicError>(curlpp::LogicError("Null write functor")));
		return CURLE_ABORTED_BY_CALLBACK;
	}

	try
	{
		return mWriteFunctor(buffer, size, nitems);
	}

	catch(curlpp::CallbackExceptionBase * e)
	{
		setException(e);
	}

	catch(...)
	{
		setException(new CallbackException<curlpp::UnknowException>(curlpp::UnknowException()));
	}

	return CURLE_ABORTED_BY_CALLBACK;
}

size_t
CurlHandle::executeHeaderFunctor(char * buffer, size_t size, size_t nitems)
{
	if (!mHeaderFunctor)
	{
		setException(new CallbackException<curlpp::LogicError>(curlpp::LogicError("Null write functor")));
		return CURLE_ABORTED_BY_CALLBACK;
	}

	try
	{
		return mHeaderFunctor(buffer, size, nitems);
	}

	catch(curlpp::CallbackExceptionBase * e)
	{
		setException(e);
	}

	catch(...)
	{
		setException(new CallbackException<curlpp::UnknowException>(curlpp::UnknowException()));
	}

	return CURLE_ABORTED_BY_CALLBACK;
}

size_t
CurlHandle::executeReadFunctor(char * buffer, size_t size, size_t nitems)
{
	if(!mReadFunctor)
	{
		setException(new CallbackException<curlpp::LogicError>(curlpp::LogicError("Null write functor")));
		return CURLE_ABORTED_BY_CALLBACK;
	}

	try
	{
		return mReadFunctor(buffer, size, nitems);
	}

	catch(curlpp::CallbackExceptionBase * e)
	{
		setException(e);
	}

	catch(...)
	{
		setException(new CallbackException<curlpp::UnknowException>(curlpp::UnknowException()));
	}

	return CURLE_ABORTED_BY_CALLBACK;
}

int
CurlHandle::executeProgressFunctor(double dltotal,
																	 double dlnow,
																	 double ultotal,
																	 double ulnow)
{
	if (!mProgressFunctor)
	{
		setException(new CallbackException<curlpp::LogicError>(curlpp::LogicError("Null write functor")));
		return CURLE_ABORTED_BY_CALLBACK;
	}

	try
	{
		return mProgressFunctor(dltotal, dlnow, ultotal, ulnow);
	}

	catch(curlpp::CallbackExceptionBase * e)
	{
		setException(e);
	}

	catch(...)
	{
		setException(new CallbackException<curlpp::UnknowException>(curlpp::UnknowException()));
	}

	return CURLE_ABORTED_BY_CALLBACK;
}

int
CurlHandle::executeDebugFunctor(curl_infotype info, char * buffer, size_t size)
{
	if (!mDebugFunctor)
	{
		setException(new CallbackException<curlpp::LogicError>(curlpp::LogicError("Null write functor")));
		return CURLE_ABORTED_BY_CALLBACK;
	}

	try
	{
		return mDebugFunctor(info, buffer, size);
	}

	catch(curlpp::CallbackExceptionBase * e)
	{
		setException(e);
	}

	catch(...)
	{
		setException(new CallbackException<curlpp::UnknowException>(curlpp::UnknowException()));
	}

	return CURLE_ABORTED_BY_CALLBACK;
}

CURLcode
CurlHandle::executeSslCtxFunctor(void * ssl_ctx)
{
	if (!mSslFunctor)
	{
		setException(new CallbackException<curlpp::LogicError>(curlpp::LogicError("Null write functor")));
		return CURLE_ABORTED_BY_CALLBACK;
	}

	try
	{
		return mSslFunctor(ssl_ctx);
	}

	catch(curlpp::CallbackExceptionBase * e)
	{
		setException(e);
	}

	catch(...)
	{
		setException(new CallbackException<curlpp::UnknowException>(curlpp::UnknowException()));
	}

	return CURLE_ABORTED_BY_CALLBACK;
}

void
CurlHandle::throwException()
{
	if(mException)
		mException->throwMe();
}

} // namespace internal

} // namespace curlpp
<commit_msg>now releasing exception handler after throwing<commit_after>/*
*    Copyright (c) <2002-2009> <Jean-Philippe Barrette-LaPierre>
*
*    Permission is hereby granted, free of charge, to any person obtaining
*    a copy of this software and associated documentation files
*    (curlpp), 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 "curlpp/internal/global.h"
#include "curlpp/internal/CurlHandle.hpp"

#include "curlpp/cURLpp.hpp"
#include "curlpp/Exception.hpp"

#include <string>
#include <iostream>
#include <memory>
#include <cstring>

using std::memset;
using std::auto_ptr;

namespace curlpp
{

namespace internal
{

void CurlHandle::perform()
{
	CURLcode code;

	code = curl_easy_perform(mCurl);
	throwException();
	libcurlRuntimeAssert(mErrorBuffer, code); //if we got an error
}

void CurlHandle::reset()
{
	curl_easy_reset(mCurl);
	memset(mErrorBuffer,0,CURL_ERROR_SIZE + 1);
	errorBuffer(mErrorBuffer);
}

CURL * CurlHandle::getHandle() const
{
	return mCurl;
}

CurlHandle::CurlHandle()
	: mException(NULL)
{
	memset(mErrorBuffer,0,CURL_ERROR_SIZE + 1);
	mCurl = curl_easy_init();
	runtimeAssert("Error when trying to curl_easy_init() a handle", mCurl != NULL);
	errorBuffer(mErrorBuffer);
}

CurlHandle::CurlHandle(CURL * handle)
	: mException(NULL)
{
	memset(mErrorBuffer,0,CURL_ERROR_SIZE + 1);
	mCurl = handle;
	runtimeAssert("Error when trying to curl_easy_init() a handle", mCurl != NULL);
	errorBuffer(mErrorBuffer);
}

std::auto_ptr<CurlHandle>
CurlHandle::clone() const
{
	CURL * cHandle = curl_easy_duphandle(mCurl);
	runtimeAssert("Error when trying to curl_easy_duphandle() a handle", cHandle != NULL);
	auto_ptr<CurlHandle> newHandle(new CurlHandle(cHandle));

	return newHandle;
}

CurlHandle::~CurlHandle()
{
	if (mException)
	{
		delete mException;
		mException = NULL;
	}
	curl_easy_cleanup(mCurl);
}

void
CurlHandle::setException(curlpp::CallbackExceptionBase * e)
{
	if(mException)
	{
		delete mException;
	}

	mException = e;
}

void
CurlHandle::errorBuffer(char * buffer)
{
	option(CURLOPT_ERRORBUFFER, (void *)buffer);
}

template<typename FunctorType>
typename FunctorType::ResultType
CurlHandle::execute(FunctorType functor, typename FunctorType::ParamList params)
{
	if (!functor)
	{
	 	setException(new CallbackException<curlpp::LogicError>(curlpp::LogicError("Null functor")));
		return CURLE_ABORTED_BY_CALLBACK;
	}

	try
	{
		return functor(params);
	}

	catch(curlpp::CallbackExceptionBase * e)
	{
		setException(e);
	}

	catch(...)
	{
		setException(new CallbackException<curlpp::UnknowException>(curlpp::UnknowException()));
	}

	return CURLE_ABORTED_BY_CALLBACK;
}

size_t
CurlHandle::executeWriteFunctor(char * buffer, size_t size, size_t nitems)
{
	if (!mWriteFunctor)
	{
		setException(new CallbackException<curlpp::LogicError>(curlpp::LogicError("Null write functor")));
		return CURLE_ABORTED_BY_CALLBACK;
	}

	try
	{
		return mWriteFunctor(buffer, size, nitems);
	}

	catch(curlpp::CallbackExceptionBase * e)
	{
		setException(e);
	}

	catch(...)
	{
		setException(new CallbackException<curlpp::UnknowException>(curlpp::UnknowException()));
	}

	return CURLE_ABORTED_BY_CALLBACK;
}

size_t
CurlHandle::executeHeaderFunctor(char * buffer, size_t size, size_t nitems)
{
	if (!mHeaderFunctor)
	{
		setException(new CallbackException<curlpp::LogicError>(curlpp::LogicError("Null write functor")));
		return CURLE_ABORTED_BY_CALLBACK;
	}

	try
	{
		return mHeaderFunctor(buffer, size, nitems);
	}

	catch(curlpp::CallbackExceptionBase * e)
	{
		setException(e);
	}

	catch(...)
	{
		setException(new CallbackException<curlpp::UnknowException>(curlpp::UnknowException()));
	}

	return CURLE_ABORTED_BY_CALLBACK;
}

size_t
CurlHandle::executeReadFunctor(char * buffer, size_t size, size_t nitems)
{
	if(!mReadFunctor)
	{
		setException(new CallbackException<curlpp::LogicError>(curlpp::LogicError("Null write functor")));
		return CURLE_ABORTED_BY_CALLBACK;
	}

	try
	{
		return mReadFunctor(buffer, size, nitems);
	}

	catch(curlpp::CallbackExceptionBase * e)
	{
		setException(e);
	}

	catch(...)
	{
		setException(new CallbackException<curlpp::UnknowException>(curlpp::UnknowException()));
	}

	return CURLE_ABORTED_BY_CALLBACK;
}

int
CurlHandle::executeProgressFunctor(double dltotal,
																	 double dlnow,
																	 double ultotal,
																	 double ulnow)
{
	if (!mProgressFunctor)
	{
		setException(new CallbackException<curlpp::LogicError>(curlpp::LogicError("Null write functor")));
		return CURLE_ABORTED_BY_CALLBACK;
	}

	try
	{
		return mProgressFunctor(dltotal, dlnow, ultotal, ulnow);
	}

	catch(curlpp::CallbackExceptionBase * e)
	{
		setException(e);
	}

	catch(...)
	{
		setException(new CallbackException<curlpp::UnknowException>(curlpp::UnknowException()));
	}

	return CURLE_ABORTED_BY_CALLBACK;
}

int
CurlHandle::executeDebugFunctor(curl_infotype info, char * buffer, size_t size)
{
	if (!mDebugFunctor)
	{
		setException(new CallbackException<curlpp::LogicError>(curlpp::LogicError("Null write functor")));
		return CURLE_ABORTED_BY_CALLBACK;
	}

	try
	{
		return mDebugFunctor(info, buffer, size);
	}

	catch(curlpp::CallbackExceptionBase * e)
	{
		setException(e);
	}

	catch(...)
	{
		setException(new CallbackException<curlpp::UnknowException>(curlpp::UnknowException()));
	}

	return CURLE_ABORTED_BY_CALLBACK;
}

CURLcode
CurlHandle::executeSslCtxFunctor(void * ssl_ctx)
{
	if (!mSslFunctor)
	{
		setException(new CallbackException<curlpp::LogicError>(curlpp::LogicError("Null write functor")));
		return CURLE_ABORTED_BY_CALLBACK;
	}

	try
	{
		return mSslFunctor(ssl_ctx);
	}

	catch(curlpp::CallbackExceptionBase * e)
	{
		setException(e);
	}

	catch(...)
	{
		setException(new CallbackException<curlpp::UnknowException>(curlpp::UnknowException()));
	}

	return CURLE_ABORTED_BY_CALLBACK;
}

void
CurlHandle::throwException()
{
  if(mException)
  {
    std::auto_ptr< cURLpp::CallbackExceptionBase > e(mException);
    mException = NULL;
    e->throwMe();
  }
}

} // namespace internal

} // namespace curlpp
<|endoftext|>


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

#include <QNetworkInterface>
#include <QTimer>

#include "interfacemonitor.h"

InterfaceMonitor::InterfaceMonitor()
{
    connect(&timer, &QTimer::timeout, this, &InterfaceMonitor::refresh);
    connect(Settings::instance(), &Settings::settingChanged, this, &InterfaceMonitor::settingChanged);

    timer.setSingleShot(true);
    reload();
}

void InterfaceMonitor::start()
{
    refresh();
}

void InterfaceMonitor::refresh()
{
    QSet<QString> newNames;

    foreach(QNetworkInterface interface, QNetworkInterface::allInterfaces()) {
        if(interface.flags() && QNetworkInterface::CanMulticast)
            newNames.insert(interface.name());

        // TODO: verify that an IPv6 address is available since the
        // interface may only provide an IPv4 multicast address
    }

    foreach(QString name, newNames - oldNames) {
        emit interfaceAdded(name);
    }

    foreach(QString name, oldNames - newNames) {
        emit interfaceRemoved(name);
    }

    oldNames = newNames;

    timer.start();
}

void InterfaceMonitor::settingChanged(Settings::Key key)
{
    if(key == Settings::InterfaceMonitorInterval) {
        timer.stop();
        reload();
        timer.start();
    }
}

void InterfaceMonitor::reload()
{
    timer.setInterval(Settings::get<int>(Settings::InterfaceMonitorInterval));
}
<commit_msg>Timer in InterfaceMonitor is no longer single shot.<commit_after>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Nathan Osman
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 **/

#include <QNetworkInterface>
#include <QTimer>

#include "interfacemonitor.h"

InterfaceMonitor::InterfaceMonitor()
{
    connect(&timer, &QTimer::timeout, this, &InterfaceMonitor::refresh);
    connect(Settings::instance(), &Settings::settingChanged, this, &InterfaceMonitor::settingChanged);

    reload();
}

void InterfaceMonitor::start()
{
    refresh();
    timer.start();
}

void InterfaceMonitor::refresh()
{
    QSet<QString> newNames;

    foreach(QNetworkInterface interface, QNetworkInterface::allInterfaces()) {
        if(interface.flags() && QNetworkInterface::CanMulticast)
            newNames.insert(interface.name());

        // TODO: verify that an IPv6 address is available since the
        // interface may only provide an IPv4 multicast address
    }

    foreach(QString name, newNames - oldNames) {
        emit interfaceAdded(name);
    }

    foreach(QString name, oldNames - newNames) {
        emit interfaceRemoved(name);
    }

    oldNames = newNames;
}

void InterfaceMonitor::settingChanged(Settings::Key key)
{
    if(key == Settings::InterfaceMonitorInterval) {
        timer.stop();
        reload();
        timer.start();
    }
}

void InterfaceMonitor::reload()
{
    timer.setInterval(Settings::get<int>(Settings::InterfaceMonitorInterval));
}
<|endoftext|>


<commit_before>#include "precompiled.h"

#include "engine/EngineSystem.h"
#include "engine/math/AABB.h"
#include "engine/render/RenderSystem.h"
#include "engine/world/Room.h"
#include "engine/world/Tile.h"
#include "engine/UI/ContainerBase.h"

namespace engine {
namespace render {

	RenderSystem::RenderSystem(world::WorldSystem *worldSystem,UI::UISystem *uiSystem)
	: worldSystem(worldSystem),
	  uiSystem(uiSystem)
	{}

	bool RenderSystem::init(){
		initscr();
		if(has_colors() == false){
			endwin();
			printf("Your terminal doesn't support colors...\nFind more modern system/terminal.");
			return false;
		}

		start_color();

		cameraPos.x = 0;
		cameraPos.y = 0;
		cameraPos.z = 0;

		return true;
	}

	void RenderSystem::uninit(){
		clear();
		endwin();
		return;
	}

	void RenderSystem::update(){
		clear();

		//Render world position info on top of the screen..
		move(0,0);
		printw("World x: %i y: %i z: %i",cameraPos.x,cameraPos.y,cameraPos.z);

		//Check that the camera is not out of bounds...
		if(cameraPos.x < 0 || cameraPos.x >= WORLD_WIDTH){
			LOG_ERROR("Camera out of bounds! (x)");
			return;
		}

		if(cameraPos.y < 0 || cameraPos.y >= WORLD_HEIGHT){
			LOG_ERROR("Camera out of bounds! (y)");
			return;
		}

		if(cameraPos.z < 0 || cameraPos.z >= WORLD_DEPTH){
			LOG_ERROR("Camera out of bounds! (z)");
			return;
		}

		/* RENDER MAP */
		world::Room *currentRoom = worldSystem->getRoom(cameraPos);

		vec2 pos;
		for(int x = 0;x < ROOM_WIDTH;++x){
			for(int y = 0;y < ROOM_HEIGHT;++y){
				pos.x = (x + 2);
				pos.y = (y + 2);
				drawChar(pos,currentRoom->getTile(x,y)->visual);
			}
		}

		/* RENDER UI ON TOP OF EVERYTHING */

		for(int i = 0;i < uiSystem->windows.size();++i){
			//Render window decorations
			vec2 pos  = uiSystem->windows[i].getPos();
			vec2 size = uiSystem->windows[i].getSize();

			for(int x = pos.x; x < pos.x + size.x + 1; ++x){
				for(int y = pos.y; y < pos.y + size.y + 1; ++y){
					drawChar(vec2(x,y), ' ');

					if(x == pos.x){
						drawChar(vec2(x,y), '|');
					}

					if(x == pos.x + size.x){
						drawChar(vec2(x,y), '|');
					}

					if(y == pos.y){
						drawChar(vec2(x,y), '-');
					}

					if(y == pos.y + size.y){
						drawChar(vec2(x,y), '-');
					}
				}
			}

			//Corners
			drawChar(pos,'/');
			drawChar(vec2(pos.x + size.x , pos.y),'\\');
			drawChar(vec2(pos.x , pos.y + size.y),'\\');
			drawChar(vec2(pos.x + size.x , pos.y + size.y),'/');

			//lets place window title nicely to the middle
			if(uiSystem->windows[i].getName().size() > size.x){
				LOG_WARNING("Window name too long!");
			}else{
				move(pos.y,pos.x + 2);
				printw("[%s]",uiSystem->windows[i].getName().c_str());
			}

			//render contents to windows
			UI::ContainerBase *container = uiSystem->windows[i].getContainer();

			if(container != NULL){
				//AABB where the container is allowed to draw

				AABB bounds;

				bounds.pos = uiSystem->windows[i].getPos();
				bounds.size = uiSystem->windows[i].getSize();

				//The bounds are INSIDE the window, not the same size as the window
				++bounds.pos.x;
				++bounds.pos.y;
				--bounds.size.x;
				--bounds.size.y;

				container->render(bounds);
			}else{
				LOG_ERROR("Window doesn't have container!");
			}
		}

		return;
	}

	void RenderSystem::drawChar(vec2 pos,int character){
		move(pos.y,pos.x);
		printw("%c",character);
	}

	void drawCharTobounds(AABB bounds,vec2 pos,int character){
		//Check if pos is too far...

		if(pos.x < 0 || pos.y < 0){
			//Position negative...
			LOG_WARNING("Trying to draw outside of window (negative)");
			return;
		}

		//check if its outside of the window area
		if(pos.x > bounds.size.x || pos.y > bounds.size.y){
			LOG_WARNING("Trying to draw outside of the window (positive)");
			return;
		}

		//move the pos to the window area
		pos.x -= bounds.x;
		pos.y -= bounds.y;
	}
}
}
<commit_msg>Fixed invalid build<commit_after>#include "precompiled.h"

#include "engine/EngineSystem.h"
#include "engine/math/AABB.h"
#include "engine/render/RenderSystem.h"
#include "engine/world/Room.h"
#include "engine/world/Tile.h"
#include "engine/UI/ContainerBase.h"

namespace engine {
namespace render {

	RenderSystem::RenderSystem(world::WorldSystem *worldSystem,UI::UISystem *uiSystem)
	: worldSystem(worldSystem),
	  uiSystem(uiSystem)
	{}

	bool RenderSystem::init(){
		initscr();
		if(has_colors() == false){
			endwin();
			printf("Your terminal doesn't support colors...\nFind more modern system/terminal.");
			return false;
		}

		start_color();

		cameraPos.x = 0;
		cameraPos.y = 0;
		cameraPos.z = 0;

		return true;
	}

	void RenderSystem::uninit(){
		clear();
		endwin();
		return;
	}

	void RenderSystem::update(){
		clear();

		//Render world position info on top of the screen..
		move(0,0);
		printw("World x: %i y: %i z: %i",cameraPos.x,cameraPos.y,cameraPos.z);

		//Check that the camera is not out of bounds...
		if(cameraPos.x < 0 || cameraPos.x >= WORLD_WIDTH){
			LOG_ERROR("Camera out of bounds! (x)");
			return;
		}

		if(cameraPos.y < 0 || cameraPos.y >= WORLD_HEIGHT){
			LOG_ERROR("Camera out of bounds! (y)");
			return;
		}

		if(cameraPos.z < 0 || cameraPos.z >= WORLD_DEPTH){
			LOG_ERROR("Camera out of bounds! (z)");
			return;
		}

		/* RENDER MAP */
		world::Room *currentRoom = worldSystem->getRoom(cameraPos);

		vec2 pos;
		for(int x = 0;x < ROOM_WIDTH;++x){
			for(int y = 0;y < ROOM_HEIGHT;++y){
				pos.x = (x + 2);
				pos.y = (y + 2);
				drawChar(pos,currentRoom->getTile(x,y)->visual);
			}
		}

		/* RENDER UI ON TOP OF EVERYTHING */

		for(int i = 0;i < uiSystem->windows.size();++i){
			//Render window decorations
			vec2 pos  = uiSystem->windows[i].getPos();
			vec2 size = uiSystem->windows[i].getSize();

			for(int x = pos.x; x < pos.x + size.x + 1; ++x){
				for(int y = pos.y; y < pos.y + size.y + 1; ++y){
					drawChar(vec2(x,y), ' ');

					if(x == pos.x){
						drawChar(vec2(x,y), '|');
					}

					if(x == pos.x + size.x){
						drawChar(vec2(x,y), '|');
					}

					if(y == pos.y){
						drawChar(vec2(x,y), '-');
					}

					if(y == pos.y + size.y){
						drawChar(vec2(x,y), '-');
					}
				}
			}

			//Corners
			drawChar(pos,'/');
			drawChar(vec2(pos.x + size.x , pos.y),'\\');
			drawChar(vec2(pos.x , pos.y + size.y),'\\');
			drawChar(vec2(pos.x + size.x , pos.y + size.y),'/');

			//lets place window title nicely to the middle
			if(uiSystem->windows[i].getName().size() > size.x){
				LOG_WARNING("Window name too long!");
			}else{
				move(pos.y,pos.x + 2);
				printw("[%s]",uiSystem->windows[i].getName().c_str());
			}

			//render contents to windows
			UI::ContainerBase *container = uiSystem->windows[i].getContainer();

			if(container != NULL){
				//AABB where the container is allowed to draw

				AABB bounds;

				bounds.pos = uiSystem->windows[i].getPos();
				bounds.size = uiSystem->windows[i].getSize();

				//The bounds are INSIDE the window, not the same size as the window
				++bounds.pos.x;
				++bounds.pos.y;
				--bounds.size.x;
				--bounds.size.y;

				container->render(bounds);
			}else{
				LOG_ERROR("Window doesn't have container!");
			}
		}

		return;
	}

	void RenderSystem::drawChar(vec2 pos,int character){
		move(pos.y,pos.x);
		printw("%c",character);
	}

	void drawCharTobounds(AABB bounds,vec2 pos,int character){
		//Check if pos is too far...

		if(pos.x < 0 || pos.y < 0){
			//Position negative...
			LOG_WARNING("Trying to draw outside of window (negative)");
			return;
		}

		//check if its outside of the window area
		if(pos.x > bounds.size.x || pos.y > bounds.size.y){
			LOG_WARNING("Trying to draw outside of the window (positive)");
			return;
		}

		//move the pos to the window area
		pos.x -= bounds.pos.x;
		pos.y -= bounds.pos.y;
	}
}
}
<|endoftext|>


<commit_before>/**
 * @brief Executor for sequential scan node.
 *
 * Copyright(c) 2015, CMU
 */

#include "executor/seq_scan_executor.h"

#include <memory>
#include <utility>
#include <vector>

#include "catalog/manager.h"
#include "common/types.h"
#include "executor/logical_tile.h"
#include "executor/logical_tile_factory.h"
#include "expression/abstract_expression.h"
#include "planner/seq_scan_node.h"
#include "storage/table.h"
#include "storage/tile.h"
#include "storage/tile_group.h"
#include "storage/tile_iterator.h"
#include "storage/tuple.h"

namespace nstore {
namespace executor {

/**
 * @brief Constructor for seqscan executor.
 * @param node Seqscan node corresponding to this executor.
 */
SeqScanExecutor::SeqScanExecutor(planner::AbstractPlanNode *node)
  : AbstractExecutor(node) {
}

/**
 * @brief Nothing to init at the moment.
 * @return true on success, false otherwise.
 */
bool SeqScanExecutor::DInit() {
  assert(children_.size() == 0);
  return true;
}

/**
 * @brief Creates logical tile from tile group and applys scan predicate.
 * @return true on success, false otherwise.
 */
bool SeqScanExecutor::DExecute() {
  assert(children_.size() == 0);

  // Grab data from plan node.
  const planner::SeqScanNode &node = GetNode<planner::SeqScanNode>();
  const oid_t table_id = node.table_id();
  const expression::AbstractExpression *predicate = node.predicate();
  const std::vector<id_t> &column_ids = node.column_ids();

  auto &locator = catalog::Manager::GetInstance().locator;
  // TODO Do this in DInit() to amortize lookup over all tiles.
  // Do we have to do some kind of synchronization to ensure that the table
  // doesn't disappear midway through our request?
  auto it = locator.find(table_id);
  if (it == locator.end()) {
    return false;
  }

  // Retrieve next available physical (base) tile.
  // TODO Are we supposed to go through database or catalog::Table first?
  storage::Table *table = static_cast<storage::Table *>(it->second);
  //TODO Create iterators for table and tile groups?
  if (current_tile_group_id_ == table->NumTileGroups()) {
    return false;
  }
  storage::TileGroup *tile_group = table->GetTileGroup(current_tile_group_id_);
  if (current_tile_id_ == tile_group->NumTiles()) {
    current_tile_group_id_++;
    current_tile_id_ = 0;
    if (current_tile_group_id_ == table->NumTileGroups()) {
      return false;
    }
    tile_group = table->GetTileGroup(current_tile_group_id_);
    assert(tile_group->NumTiles() > 0);
  }
  storage::Tile *base_tile = tile_group->GetTile(current_tile_id_++);

  // Construct position list by looping through tile group and
  // applying the predicate.
  std::vector<id_t> position_list;
  storage::TileIterator tile_it(base_tile);
  storage::Tuple tuple(&base_tile->GetSchema());
  while (tile_it.Next(tuple)) {
    if (predicate->Evaluate(&tuple, nullptr).IsTrue()) {
      // GetLocation() returns the id of the next tuple.
      assert(tile_it.GetLocation() > 0);
      position_list.push_back(tile_it.GetLocation() - 1);
    }
  }

  // Construct logical tile.
  std::unique_ptr<LogicalTile> logical_tile(LogicalTileFactory::GetTile());
  const bool own_base_tile = false;
  const int position_list_idx = 0;
  logical_tile->AddPositionList(std::move(position_list));
  for (id_t origin_column_id : column_ids) {
    logical_tile->AddColumn(
        base_tile,
        own_base_tile,
        origin_column_id,
        position_list_idx);
  }

  SetOutput(logical_tile.release());
  return true;
}

} // namespace executor
} // namespace nstore
<commit_msg>Added case when seq scan pred is null.<commit_after>/**
 * @brief Executor for sequential scan node.
 *
 * Copyright(c) 2015, CMU
 */

#include "executor/seq_scan_executor.h"

#include <memory>
#include <utility>
#include <vector>

#include "catalog/manager.h"
#include "common/types.h"
#include "executor/logical_tile.h"
#include "executor/logical_tile_factory.h"
#include "expression/abstract_expression.h"
#include "planner/seq_scan_node.h"
#include "storage/table.h"
#include "storage/tile.h"
#include "storage/tile_group.h"
#include "storage/tile_iterator.h"
#include "storage/tuple.h"

namespace nstore {
namespace executor {

/**
 * @brief Constructor for seqscan executor.
 * @param node Seqscan node corresponding to this executor.
 */
SeqScanExecutor::SeqScanExecutor(planner::AbstractPlanNode *node)
  : AbstractExecutor(node) {
}

/**
 * @brief Nothing to init at the moment.
 * @return true on success, false otherwise.
 */
bool SeqScanExecutor::DInit() {
  assert(children_.size() == 0);
  return true;
}

/**
 * @brief Creates logical tile from tile group and applys scan predicate.
 * @return true on success, false otherwise.
 */
bool SeqScanExecutor::DExecute() {
  assert(children_.size() == 0);

  // Grab data from plan node.
  const planner::SeqScanNode &node = GetNode<planner::SeqScanNode>();
  const oid_t table_id = node.table_id();
  const expression::AbstractExpression *predicate = node.predicate();
  const std::vector<id_t> &column_ids = node.column_ids();

  auto &locator = catalog::Manager::GetInstance().locator;
  // TODO Do this in DInit() to amortize lookup over all tiles.
  // Do we have to do some kind of synchronization to ensure that the table
  // doesn't disappear midway through our request?
  auto it = locator.find(table_id);
  if (it == locator.end()) {
    return false;
  }

  // Retrieve next available physical (base) tile.
  // TODO Are we supposed to go through database or catalog::Table first?
  storage::Table *table = static_cast<storage::Table *>(it->second);
  //TODO Create iterators for table and tile groups?
  if (current_tile_group_id_ == table->NumTileGroups()) {
    return false;
  }
  storage::TileGroup *tile_group = table->GetTileGroup(current_tile_group_id_);
  if (current_tile_id_ == tile_group->NumTiles()) {
    current_tile_group_id_++;
    current_tile_id_ = 0;
    if (current_tile_group_id_ == table->NumTileGroups()) {
      return false;
    }
    tile_group = table->GetTileGroup(current_tile_group_id_);
    assert(tile_group->NumTiles() > 0);
  }
  storage::Tile *base_tile = tile_group->GetTile(current_tile_id_++);

  // Construct position list by looping through tile group and
  // applying the predicate.
  std::vector<id_t> position_list;
  storage::TileIterator tile_it(base_tile);
  storage::Tuple tuple(&base_tile->GetSchema());
  while (tile_it.Next(tuple)) {
    if (predicate == nullptr
        || predicate->Evaluate(&tuple, nullptr).IsTrue()) {
      // GetLocation() returns the id of the next tuple.
      assert(tile_it.GetLocation() > 0);
      position_list.push_back(tile_it.GetLocation() - 1);
    }
  }

  // Construct logical tile.
  std::unique_ptr<LogicalTile> logical_tile(LogicalTileFactory::GetTile());
  const bool own_base_tile = false;
  const int position_list_idx = 0;
  logical_tile->AddPositionList(std::move(position_list));
  for (id_t origin_column_id : column_ids) {
    logical_tile->AddColumn(
        base_tile,
        own_base_tile,
        origin_column_id,
        position_list_idx);
  }

  SetOutput(logical_tile.release());
  return true;
}

} // namespace executor
} // namespace nstore
<|endoftext|>


<commit_before>#include "MotorHandler.h"
#include <SPI.h>

namespace sentinel {
    namespace handler {
        namespace motor {
            void MotorHandler::setPath(web::Method method, std::shared_ptr<std::string> uri) {
                this->uri = uri;
                this->method = method;
            }

            bool MotorHandler::canHandle() const {
                return uri->compare("/motor") == 0 && method == web::Method::POST;
            }

            MotorHandler::MotorHandler(sentinel::log::Logger& logger) :
                    logger(logger),
                    sender(nullptr),
                    uri(std::shared_ptr<std::string>()),
                    method(web::Method::DELETE) { }

            void MotorHandler::setSender(web::IWebSender& sender) {
                this->sender = &sender;
            }

            bool MotorHandler::handle() {

            }
        }
    }
}<commit_msg>MCP23017 is confirmed working<commit_after>#include "MotorHandler.h"
#include <SPI.h>
#include <Wire.h>
#include "Adafruit_MCP23017.h"

namespace sentinel {
    namespace handler {
        namespace motor {
            void MotorHandler::setPath(web::Method method, std::shared_ptr<std::string> uri) {
                this->uri = uri;
                this->method = method;
            }

            bool MotorHandler::canHandle() const {
                return uri->compare("/motor") == 0 && method == web::Method::POST;
            }

            MotorHandler::MotorHandler(sentinel::log::Logger& logger) :
                    logger(logger),
                    sender(nullptr),
                    uri(std::shared_ptr<std::string>()),
                    method(web::Method::DELETE) { }

            void MotorHandler::setSender(web::IWebSender& sender) {
                this->sender = &sender;
            }

            std::string to_string(int number) {
                char buff[256];
                itoa(number, buff, 10);
                return std::string(buff);
            }

            void testMCP() {
                Adafruit_MCP23017 mcp;
                Wire.begin(5, 4);
                mcp.begin();
                for (int pin = 0; pin < 16; pin++) {
                    mcp.pinMode(pin, OUTPUT);
                    sender->sendContent(to_string(pin) + " ");
                    mcp.digitalWrite(pin, HIGH);
                    delay(1000);
                    mcp.digitalWrite(pin, LOW);
                }
            }

            bool MotorHandler::handle() {

            }
        }
    }
}<|endoftext|>


<commit_before>
/*
 * Copyright 2006 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkImageDecoder.h"
#include "SkColor.h"
#include "SkColorPriv.h"
#include "SkMath.h"
#include "SkStream.h"
#include "SkTemplates.h"
#include "SkUtils.h"

class SkWBMPImageDecoder : public SkImageDecoder {
public:
    virtual Format getFormat() const {
        return kWBMP_Format;
    }

protected:
    virtual bool onDecode(SkStream* stream, SkBitmap* bm, Mode);
};

static bool read_byte(SkStream* stream, uint8_t* data)
{
    return stream->read(data, 1) == 1;
}

static bool read_mbf(SkStream* stream, int* value)
{
    int n = 0;
    uint8_t data;
    do {
        if (!read_byte(stream, &data)) {
            return false;
        }
        n = (n << 7) | (data & 0x7F);
    } while (data & 0x80);

    *value = n;
    return true;
}

struct wbmp_head {
    int fWidth;
    int fHeight;

    bool init(SkStream* stream)
    {
        uint8_t data;

        if (!read_byte(stream, &data) || data != 0) { // unknown type
            return false;
        }
        if (!read_byte(stream, &data) || (data & 0x9F)) { // skip fixed header
            return false;
        }
        if (!read_mbf(stream, &fWidth) || (unsigned)fWidth > 0xFFFF) {
            return false;
        }
        if (!read_mbf(stream, &fHeight) || (unsigned)fHeight > 0xFFFF) {
            return false;
        }
        return fWidth != 0 && fHeight != 0;
    }
};

static void expand_bits_to_bytes(uint8_t dst[], const uint8_t src[], int bits)
{
    int bytes = bits >> 3;

    for (int i = 0; i < bytes; i++) {
        unsigned mask = *src++;
        dst[0] = (mask >> 7) & 1;
        dst[1] = (mask >> 6) & 1;
        dst[2] = (mask >> 5) & 1;
        dst[3] = (mask >> 4) & 1;
        dst[4] = (mask >> 3) & 1;
        dst[5] = (mask >> 2) & 1;
        dst[6] = (mask >> 1) & 1;
        dst[7] = (mask >> 0) & 1;
        dst += 8;
    }

    bits &= 7;
    if (bits > 0) {
        unsigned mask = *src;
        do {
            *dst++ = (mask >> 7) & 1;;
            mask <<= 1;
        } while (--bits != 0);
    }
}

#define SkAlign8(x)     (((x) + 7) & ~7)

bool SkWBMPImageDecoder::onDecode(SkStream* stream, SkBitmap* decodedBitmap,
                                  Mode mode)
{
    wbmp_head   head;

    if (!head.init(stream)) {
        return false;
    }

    int width = head.fWidth;
    int height = head.fHeight;

    // assign these directly, in case we return kDimensions_Result
    decodedBitmap->setConfig(SkBitmap::kIndex8_Config, width, height);
    decodedBitmap->setIsOpaque(true);

    if (SkImageDecoder::kDecodeBounds_Mode == mode)
        return true;

    const SkPMColor colors[] = { SK_ColorBLACK, SK_ColorWHITE };
    SkColorTable* ct = SkNEW_ARGS(SkColorTable, (colors, 2));
    SkAutoUnref   aur(ct);

    if (!this->allocPixelRef(decodedBitmap, ct)) {
        return false;
    }

    SkAutoLockPixels alp(*decodedBitmap);

    uint8_t* dst = decodedBitmap->getAddr8(0, 0);
    // store the 1-bit valuess at the end of our pixels, so we won't stomp
    // on them before we're read them. Just trying to avoid a temp allocation
    size_t srcRB = SkAlign8(width) >> 3;
    size_t srcSize = height * srcRB;
    uint8_t* src = dst + decodedBitmap->getSize() - srcSize;
    if (stream->read(src, srcSize) != srcSize) {
        return false;
    }

    for (int y = 0; y < height; y++)
    {
        expand_bits_to_bytes(dst, src, width);
        dst += decodedBitmap->rowBytes();
        src += srcRB;
    }

    return true;
}

///////////////////////////////////////////////////////////////////////////////
DEFINE_DECODER_CREATOR(WBMPImageDecoder);
///////////////////////////////////////////////////////////////////////////////

#include "SkTRegistry.h"

static SkImageDecoder* sk_wbmp_dfactory(SkStream* stream) {
    wbmp_head   head;

    if (head.init(stream)) {
        return SkNEW(SkWBMPImageDecoder);
    }
    return NULL;
}

static SkTRegistry<SkImageDecoder*, SkStream*> gReg(sk_wbmp_dfactory);

<commit_msg>remove duplicate definition of SkAlign8()<commit_after>
/*
 * Copyright 2006 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkImageDecoder.h"
#include "SkColor.h"
#include "SkColorPriv.h"
#include "SkMath.h"
#include "SkStream.h"
#include "SkTemplates.h"
#include "SkUtils.h"

class SkWBMPImageDecoder : public SkImageDecoder {
public:
    virtual Format getFormat() const {
        return kWBMP_Format;
    }

protected:
    virtual bool onDecode(SkStream* stream, SkBitmap* bm, Mode);
};

static bool read_byte(SkStream* stream, uint8_t* data)
{
    return stream->read(data, 1) == 1;
}

static bool read_mbf(SkStream* stream, int* value)
{
    int n = 0;
    uint8_t data;
    do {
        if (!read_byte(stream, &data)) {
            return false;
        }
        n = (n << 7) | (data & 0x7F);
    } while (data & 0x80);

    *value = n;
    return true;
}

struct wbmp_head {
    int fWidth;
    int fHeight;

    bool init(SkStream* stream)
    {
        uint8_t data;

        if (!read_byte(stream, &data) || data != 0) { // unknown type
            return false;
        }
        if (!read_byte(stream, &data) || (data & 0x9F)) { // skip fixed header
            return false;
        }
        if (!read_mbf(stream, &fWidth) || (unsigned)fWidth > 0xFFFF) {
            return false;
        }
        if (!read_mbf(stream, &fHeight) || (unsigned)fHeight > 0xFFFF) {
            return false;
        }
        return fWidth != 0 && fHeight != 0;
    }
};

static void expand_bits_to_bytes(uint8_t dst[], const uint8_t src[], int bits)
{
    int bytes = bits >> 3;

    for (int i = 0; i < bytes; i++) {
        unsigned mask = *src++;
        dst[0] = (mask >> 7) & 1;
        dst[1] = (mask >> 6) & 1;
        dst[2] = (mask >> 5) & 1;
        dst[3] = (mask >> 4) & 1;
        dst[4] = (mask >> 3) & 1;
        dst[5] = (mask >> 2) & 1;
        dst[6] = (mask >> 1) & 1;
        dst[7] = (mask >> 0) & 1;
        dst += 8;
    }

    bits &= 7;
    if (bits > 0) {
        unsigned mask = *src;
        do {
            *dst++ = (mask >> 7) & 1;;
            mask <<= 1;
        } while (--bits != 0);
    }
}

bool SkWBMPImageDecoder::onDecode(SkStream* stream, SkBitmap* decodedBitmap,
                                  Mode mode)
{
    wbmp_head   head;

    if (!head.init(stream)) {
        return false;
    }

    int width = head.fWidth;
    int height = head.fHeight;

    // assign these directly, in case we return kDimensions_Result
    decodedBitmap->setConfig(SkBitmap::kIndex8_Config, width, height);
    decodedBitmap->setIsOpaque(true);

    if (SkImageDecoder::kDecodeBounds_Mode == mode)
        return true;

    const SkPMColor colors[] = { SK_ColorBLACK, SK_ColorWHITE };
    SkColorTable* ct = SkNEW_ARGS(SkColorTable, (colors, 2));
    SkAutoUnref   aur(ct);

    if (!this->allocPixelRef(decodedBitmap, ct)) {
        return false;
    }

    SkAutoLockPixels alp(*decodedBitmap);

    uint8_t* dst = decodedBitmap->getAddr8(0, 0);
    // store the 1-bit valuess at the end of our pixels, so we won't stomp
    // on them before we're read them. Just trying to avoid a temp allocation
    size_t srcRB = SkAlign8(width) >> 3;
    size_t srcSize = height * srcRB;
    uint8_t* src = dst + decodedBitmap->getSize() - srcSize;
    if (stream->read(src, srcSize) != srcSize) {
        return false;
    }

    for (int y = 0; y < height; y++)
    {
        expand_bits_to_bytes(dst, src, width);
        dst += decodedBitmap->rowBytes();
        src += srcRB;
    }

    return true;
}

///////////////////////////////////////////////////////////////////////////////
DEFINE_DECODER_CREATOR(WBMPImageDecoder);
///////////////////////////////////////////////////////////////////////////////

#include "SkTRegistry.h"

static SkImageDecoder* sk_wbmp_dfactory(SkStream* stream) {
    wbmp_head   head;

    if (head.init(stream)) {
        return SkNEW(SkWBMPImageDecoder);
    }
    return NULL;
}

static SkTRegistry<SkImageDecoder*, SkStream*> gReg(sk_wbmp_dfactory);

<|endoftext|>


<commit_before>
#include "initialization/MainFactory.hpp"

namespace Initialization
{

    MainFactory::MainFactory()
    {
    }

    Simulation::AbstractSimulationSPtr MainFactory::createSimulation(SimulationPlan & in) const
    {
        if(in.kind == "serial")
            return createSimulationWithKnownType<Simulation::SerialSimulation>(in);
        //else if(in.kind == "openmp")
        //    return createSimulationWithKnownType<Simulation::OpenMPSimulation>(in);
        else
            throw std::runtime_error("MainFactoy: There's no simulation type " + in.kind);
    }

} /* namespace Initialization */
<commit_msg>Add author information<commit_after>/*
 * Program.cpp
 *
 *  Created on: 08.03.2016
 *      Author: hartung
 */

#include "initialization/MainFactory.hpp"

namespace Initialization
{

    MainFactory::MainFactory()
    {
    }

    Simulation::AbstractSimulationSPtr MainFactory::createSimulation(SimulationPlan & in) const
    {
        if(in.kind == "serial")
            return createSimulationWithKnownType<Simulation::SerialSimulation>(in);
        //else if(in.kind == "openmp")
        //    return createSimulationWithKnownType<Simulation::OpenMPSimulation>(in);
        else
            throw std::runtime_error("MainFactoy: There's no simulation type " + in.kind);
    }

} /* namespace Initialization */
<|endoftext|>


<commit_before>#include <cstdlib>
#include <cstdio>
#include <exception>
#include <string>
#include "test_server.h"
#include "launcher.h"

int main (int argc, char * argv[])
{
#ifdef WIN32
	ShowWindow( GetConsoleWindow(), SW_MINIMIZE);
#endif
	try
	{
		if (argc < 3)
		{
			printf("launcher: ERROR: Insufficient number of arguments\n");

			printf("\tUsage: trace_server_launcher.exe source_exe running_exe args\n");
			printf("\tExample: trace_server_launcher.exe trace_server.exe trace_server.running.exe\n");
			printf("\tExample: trace_server_launcher.exe trace_server.exe trace_server.running.exe -n -q\n");
			return 1;
		}

		std::string args;
		args += argv[2];
		args += " ";
		for (int i = 3; i < argc; ++i)
		{
			args += argv[i];
			args += " ";
		}

		bool const need_update = trace::tryUpdateTraceServer(argv[1], argv[2]);
		if (need_update)
		{
			int count = 0;
			while (isTraceServerRunning())
			{
				tryTraceServerShutdown();
				Sleep(500);
				if (count >= 4)
				{
					printf("launcher: old version not responding. never give up! never surrender!\n");
					Sleep(1000);
				}
				if (count >= 8)
				{
					printf("launcher: old version not responding. d'oh i give up!\n");
					break;
				}
			}

			bool const copy_ok = trace::tryCopyTraceServer(argv[1], argv[2]);
			if (!copy_ok)
			{
				printf("launcher: old version not responding. d'oh, i surrender!\n");
				printf("launcher: trying to start server anyway\n");
			}
			else
			{
				printf("launcher: server updated. starting...\n");
			}
			trace::runTraceServer(argv[2], args.c_str());
		}
		else
		{
			if (!isTraceServerRunning())
			{
				printf("launcher: server already up-to-date, but not running. starting...\n");
				trace::runTraceServer(argv[2], args.c_str());
			}
			else
			{
				printf("launcher: already up-to-date & started. nothing to do.\n");
			}
		}

	}
	catch (std::exception & e)
	{
		printf("launcher: ERROR - Exception in thread: %s\n", e.what());
		fflush(stdout);
	}
	catch (...)
	{
		printf("launcher: ERROR - General Failure!\n");
		return 10;
	}
	//system("pause");
	return 0;
}

<commit_msg>+ redirect stdout to file<commit_after>#include <cstdlib>
#include <cstdio>
#include <exception>
#include <string>
#include "test_server.h"
#include "launcher.h"

int main (int argc, char * argv[])
{
#ifdef WIN32
	ShowWindow( GetConsoleWindow(), SW_MINIMIZE);
#endif
	try
	{
		if (argc < 3)
		{
			printf("launcher: ERROR: Insufficient number of arguments\n");

			printf("\tUsage: trace_server_launcher.exe source_exe running_exe args\n");
			printf("\tExample: trace_server_launcher.exe trace_server.exe trace_server.running.exe\n");
			printf("\tExample: trace_server_launcher.exe trace_server.exe trace_server.running.exe -n -q\n");
			return 1;
		}

		freopen("trace_server_launcher.log", "w", stdout);

		std::string args;
		args += argv[2];
		args += " ";
		for (int i = 3; i < argc; ++i)
		{
			args += argv[i];
			args += " ";
		}

		bool const need_update = trace::tryUpdateTraceServer(argv[1], argv[2]);
		if (need_update)
		{
			int count = 0;
			while (isTraceServerRunning())
			{
				tryTraceServerShutdown();
				Sleep(500);
				if (count >= 4)
				{
					printf("launcher: old version not responding. never give up! never surrender!\n");
					Sleep(1000);
				}
				if (count >= 8)
				{
					printf("launcher: old version not responding. d'oh i give up!\n");
					break;
				}
			}

			bool const copy_ok = trace::tryCopyTraceServer(argv[1], argv[2]);
			if (!copy_ok)
			{
				printf("launcher: old version not responding. d'oh, i surrender!\n");
				printf("launcher: trying to start server anyway\n");
			}
			else
			{
				printf("launcher: server updated. starting...\n");
			}
			trace::runTraceServer(argv[2], args.c_str());
		}
		else
		{
			if (!isTraceServerRunning())
			{
				printf("launcher: server already up-to-date, but not running. starting...\n");
				trace::runTraceServer(argv[2], args.c_str());
			}
			else
			{
				printf("launcher: already up-to-date & started. nothing to do.\n");
			}
		}

	}
	catch (std::exception & e)
	{
		printf("launcher: ERROR - Exception in thread: %s\n", e.what());
		fflush(stdout);
	}
	catch (...)
	{
		printf("launcher: ERROR - General Failure!\n");
		return 10;
	}
	//system("pause");
	return 0;
}

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmlsecurity.hxx"

#include "seinitializer_mscryptimpl.hxx"

#include "securityenvironment_mscryptimpl.hxx"

#include "xmlsec/strings.h"
#include "xmlsec/mscrypto/app.h"

namespace cssu = com::sun::star::uno;
namespace cssl = com::sun::star::lang;
namespace cssxc = com::sun::star::xml::crypto;

#define SERVICE_NAME "com.sun.star.xml.crypto.SEInitializer"
#define IMPLEMENTATION_NAME "com.sun.star.xml.security.bridge.xmlsec.SEInitializer_MSCryptImpl"
#define SECURITY_ENVIRONMENT "com.sun.star.xml.crypto.SecurityEnvironment"
#define SECURITY_CONTEXT "com.sun.star.xml.crypto.XMLSecurityContext"

SEInitializer_MSCryptImpl::SEInitializer_MSCryptImpl(
    const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > &rxMSF)
    :mxMSF( rxMSF )
{
}

SEInitializer_MSCryptImpl::~SEInitializer_MSCryptImpl()
{
}

/* XSEInitializer */
cssu::Reference< cssxc::XXMLSecurityContext > SAL_CALL
    SEInitializer_MSCryptImpl::createSecurityContext(
    const rtl::OUString& sCertDB )
    throw (cssu::RuntimeException)
{
    const char* n_pCertStore ;
    HCERTSTORE  n_hStoreHandle ;

    //Initialize the crypto engine
    if( sCertDB.getLength() > 0 )
    {
        rtl::OString sCertDir(sCertDB, sCertDB.getLength(), RTL_TEXTENCODING_ASCII_US);
        n_pCertStore = sCertDir.getStr();
        n_hStoreHandle = CertOpenSystemStore( NULL, n_pCertStore ) ;
        if( n_hStoreHandle == NULL )
        {
            return NULL;
        }
    }
    else
    {
        n_pCertStore = NULL ;
        n_hStoreHandle = NULL ;
    }

    xmlSecMSCryptoAppInit( n_pCertStore ) ;

    try {
        /* Build Security Environment */
        const rtl::OUString sSecyrutyEnvironment ( RTL_CONSTASCII_USTRINGPARAM( SECURITY_ENVIRONMENT ) );
        cssu::Reference< cssxc::XSecurityEnvironment > xSecEnv( mxMSF->createInstance ( sSecyrutyEnvironment ), cssu::UNO_QUERY );
        if( !xSecEnv.is() )
        {
            if( n_hStoreHandle != NULL )
            {
                CertCloseStore( n_hStoreHandle, CERT_CLOSE_STORE_FORCE_FLAG ) ;
            }

            xmlSecMSCryptoAppShutdown() ;
            return NULL;
        }

        /* Setup key slot and certDb */
        cssu::Reference< cssl::XUnoTunnel > xEnvTunnel( xSecEnv , cssu::UNO_QUERY ) ;
        if( !xEnvTunnel.is() )
        {
            if( n_hStoreHandle != NULL )
            {
                CertCloseStore( n_hStoreHandle, CERT_CLOSE_STORE_FORCE_FLAG ) ;
            }

            xmlSecMSCryptoAppShutdown() ;
            return NULL;
        }

        SecurityEnvironment_MSCryptImpl* pSecEnv = ( SecurityEnvironment_MSCryptImpl* )xEnvTunnel->getSomething( SecurityEnvironment_MSCryptImpl::getUnoTunnelId() ) ;
        if( pSecEnv == NULL )
        {
            if( n_hStoreHandle != NULL )
            {
                CertCloseStore( n_hStoreHandle, CERT_CLOSE_STORE_FORCE_FLAG ) ;
            }

            xmlSecMSCryptoAppShutdown() ;
            return NULL;
        }

        if( n_hStoreHandle != NULL )
        {
            pSecEnv->setCryptoSlot( n_hStoreHandle ) ;
            pSecEnv->setCertDb( n_hStoreHandle ) ;
        }
        else
        {
            pSecEnv->enableDefaultCrypt( sal_True ) ;
        }

        /* Build XML Security Context */
        const rtl::OUString sSecyrutyContext ( RTL_CONSTASCII_USTRINGPARAM( SECURITY_CONTEXT ) );
        cssu::Reference< cssxc::XXMLSecurityContext > xSecCtx( mxMSF->createInstance ( sSecyrutyContext ), cssu::UNO_QUERY );
        if( !xSecCtx.is() )
        {
            if( n_hStoreHandle != NULL )
            {
                CertCloseStore( n_hStoreHandle, CERT_CLOSE_STORE_FORCE_FLAG ) ;
            }

            xmlSecMSCryptoAppShutdown() ;
            return NULL;
        }

        xSecCtx->setDefaultSecurityEnvironmentIndex(xSecCtx->addSecurityEnvironment( xSecEnv )) ;
        return xSecCtx;
    }
    catch( cssu::Exception& )
    {
        if( n_hStoreHandle != NULL )
        {
            CertCloseStore( n_hStoreHandle, CERT_CLOSE_STORE_FORCE_FLAG ) ;
        }

        xmlSecMSCryptoAppShutdown() ;
        return NULL;
    }
}

void SAL_CALL SEInitializer_MSCryptImpl::freeSecurityContext( const cssu::Reference< cssxc::XXMLSecurityContext >&)
    throw (cssu::RuntimeException)
{
    /*
    cssu::Reference< cssxc::XSecurityEnvironment > xSecEnv
        = securityContext->getSecurityEnvironment();

    if( xSecEnv.is() )
    {
        cssu::Reference< cssl::XUnoTunnel > xEnvTunnel( xSecEnv , cssu::UNO_QUERY ) ;
        if( xEnvTunnel.is() )
        {
            SecurityEnvironment_MSCryptImpl* pSecEnv = ( SecurityEnvironment_MSCryptImpl* )xEnvTunnel->getSomething( SecurityEnvironment_MSCryptImpl::getUnoTunnelId() ) ;
            HCERTSTORE n_hStoreHandle = pSecEnv->getCryptoSlot();

            if( n_hStoreHandle != NULL )
            {
                CertCloseStore( n_hStoreHandle, CERT_CLOSE_STORE_FORCE_FLAG ) ;
                pSecEnv->setCryptoSlot( NULL ) ;
                pSecEnv->setCertDb( NULL ) ;
            }

            xmlSecMSCryptoAppShutdown() ;
        }
    }
    */

    xmlSecMSCryptoAppShutdown() ;
}

rtl::OUString SEInitializer_MSCryptImpl_getImplementationName ()
    throw (cssu::RuntimeException)
{
    return rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( IMPLEMENTATION_NAME ) );
}

sal_Bool SAL_CALL SEInitializer_MSCryptImpl_supportsService( const rtl::OUString& ServiceName )
    throw (cssu::RuntimeException)
{
    return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ));
}

cssu::Sequence< rtl::OUString > SAL_CALL SEInitializer_MSCryptImpl_getSupportedServiceNames(  )
    throw (cssu::RuntimeException)
{
    cssu::Sequence < rtl::OUString > aRet(1);
    rtl::OUString* pArray = aRet.getArray();
    pArray[0] =  rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) );
    return aRet;
}
#undef SERVICE_NAME

cssu::Reference< cssu::XInterface > SAL_CALL SEInitializer_MSCryptImpl_createInstance( const cssu::Reference< cssl::XMultiServiceFactory > & rSMgr)
    throw( cssu::Exception )
{
    return (cppu::OWeakObject*) new SEInitializer_MSCryptImpl(rSMgr);
}

/* XServiceInfo */
rtl::OUString SAL_CALL SEInitializer_MSCryptImpl::getImplementationName(  )
    throw (cssu::RuntimeException)
{
    return SEInitializer_MSCryptImpl_getImplementationName();
}
sal_Bool SAL_CALL SEInitializer_MSCryptImpl::supportsService( const rtl::OUString& rServiceName )
    throw (cssu::RuntimeException)
{
    return SEInitializer_MSCryptImpl_supportsService( rServiceName );
}
cssu::Sequence< rtl::OUString > SAL_CALL SEInitializer_MSCryptImpl::getSupportedServiceNames(  )
    throw (cssu::RuntimeException)
{
    return SEInitializer_MSCryptImpl_getSupportedServiceNames();
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>And yet another .getStr()-style fix<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmlsecurity.hxx"

#include "seinitializer_mscryptimpl.hxx"

#include "securityenvironment_mscryptimpl.hxx"

#include "xmlsec/strings.h"
#include "xmlsec/mscrypto/app.h"

namespace cssu = com::sun::star::uno;
namespace cssl = com::sun::star::lang;
namespace cssxc = com::sun::star::xml::crypto;

#define SERVICE_NAME "com.sun.star.xml.crypto.SEInitializer"
#define IMPLEMENTATION_NAME "com.sun.star.xml.security.bridge.xmlsec.SEInitializer_MSCryptImpl"
#define SECURITY_ENVIRONMENT "com.sun.star.xml.crypto.SecurityEnvironment"
#define SECURITY_CONTEXT "com.sun.star.xml.crypto.XMLSecurityContext"

SEInitializer_MSCryptImpl::SEInitializer_MSCryptImpl(
    const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > &rxMSF)
    :mxMSF( rxMSF )
{
}

SEInitializer_MSCryptImpl::~SEInitializer_MSCryptImpl()
{
}

/* XSEInitializer */
cssu::Reference< cssxc::XXMLSecurityContext > SAL_CALL
    SEInitializer_MSCryptImpl::createSecurityContext(
    const rtl::OUString& sCertDB )
    throw (cssu::RuntimeException)
{
    const char* n_pCertStore ;
    HCERTSTORE  n_hStoreHandle ;

    //Initialize the crypto engine
    if( sCertDB.getLength() > 0 )
    {
        rtl::OString sCertDir(sCertDB.getStr(), sCertDB.getLength(), RTL_TEXTENCODING_ASCII_US);
        n_pCertStore = sCertDir.getStr();
        n_hStoreHandle = CertOpenSystemStore( NULL, n_pCertStore ) ;
        if( n_hStoreHandle == NULL )
        {
            return NULL;
        }
    }
    else
    {
        n_pCertStore = NULL ;
        n_hStoreHandle = NULL ;
    }

    xmlSecMSCryptoAppInit( n_pCertStore ) ;

    try {
        /* Build Security Environment */
        const rtl::OUString sSecyrutyEnvironment ( RTL_CONSTASCII_USTRINGPARAM( SECURITY_ENVIRONMENT ) );
        cssu::Reference< cssxc::XSecurityEnvironment > xSecEnv( mxMSF->createInstance ( sSecyrutyEnvironment ), cssu::UNO_QUERY );
        if( !xSecEnv.is() )
        {
            if( n_hStoreHandle != NULL )
            {
                CertCloseStore( n_hStoreHandle, CERT_CLOSE_STORE_FORCE_FLAG ) ;
            }

            xmlSecMSCryptoAppShutdown() ;
            return NULL;
        }

        /* Setup key slot and certDb */
        cssu::Reference< cssl::XUnoTunnel > xEnvTunnel( xSecEnv , cssu::UNO_QUERY ) ;
        if( !xEnvTunnel.is() )
        {
            if( n_hStoreHandle != NULL )
            {
                CertCloseStore( n_hStoreHandle, CERT_CLOSE_STORE_FORCE_FLAG ) ;
            }

            xmlSecMSCryptoAppShutdown() ;
            return NULL;
        }

        SecurityEnvironment_MSCryptImpl* pSecEnv = ( SecurityEnvironment_MSCryptImpl* )xEnvTunnel->getSomething( SecurityEnvironment_MSCryptImpl::getUnoTunnelId() ) ;
        if( pSecEnv == NULL )
        {
            if( n_hStoreHandle != NULL )
            {
                CertCloseStore( n_hStoreHandle, CERT_CLOSE_STORE_FORCE_FLAG ) ;
            }

            xmlSecMSCryptoAppShutdown() ;
            return NULL;
        }

        if( n_hStoreHandle != NULL )
        {
            pSecEnv->setCryptoSlot( n_hStoreHandle ) ;
            pSecEnv->setCertDb( n_hStoreHandle ) ;
        }
        else
        {
            pSecEnv->enableDefaultCrypt( sal_True ) ;
        }

        /* Build XML Security Context */
        const rtl::OUString sSecyrutyContext ( RTL_CONSTASCII_USTRINGPARAM( SECURITY_CONTEXT ) );
        cssu::Reference< cssxc::XXMLSecurityContext > xSecCtx( mxMSF->createInstance ( sSecyrutyContext ), cssu::UNO_QUERY );
        if( !xSecCtx.is() )
        {
            if( n_hStoreHandle != NULL )
            {
                CertCloseStore( n_hStoreHandle, CERT_CLOSE_STORE_FORCE_FLAG ) ;
            }

            xmlSecMSCryptoAppShutdown() ;
            return NULL;
        }

        xSecCtx->setDefaultSecurityEnvironmentIndex(xSecCtx->addSecurityEnvironment( xSecEnv )) ;
        return xSecCtx;
    }
    catch( cssu::Exception& )
    {
        if( n_hStoreHandle != NULL )
        {
            CertCloseStore( n_hStoreHandle, CERT_CLOSE_STORE_FORCE_FLAG ) ;
        }

        xmlSecMSCryptoAppShutdown() ;
        return NULL;
    }
}

void SAL_CALL SEInitializer_MSCryptImpl::freeSecurityContext( const cssu::Reference< cssxc::XXMLSecurityContext >&)
    throw (cssu::RuntimeException)
{
    /*
    cssu::Reference< cssxc::XSecurityEnvironment > xSecEnv
        = securityContext->getSecurityEnvironment();

    if( xSecEnv.is() )
    {
        cssu::Reference< cssl::XUnoTunnel > xEnvTunnel( xSecEnv , cssu::UNO_QUERY ) ;
        if( xEnvTunnel.is() )
        {
            SecurityEnvironment_MSCryptImpl* pSecEnv = ( SecurityEnvironment_MSCryptImpl* )xEnvTunnel->getSomething( SecurityEnvironment_MSCryptImpl::getUnoTunnelId() ) ;
            HCERTSTORE n_hStoreHandle = pSecEnv->getCryptoSlot();

            if( n_hStoreHandle != NULL )
            {
                CertCloseStore( n_hStoreHandle, CERT_CLOSE_STORE_FORCE_FLAG ) ;
                pSecEnv->setCryptoSlot( NULL ) ;
                pSecEnv->setCertDb( NULL ) ;
            }

            xmlSecMSCryptoAppShutdown() ;
        }
    }
    */

    xmlSecMSCryptoAppShutdown() ;
}

rtl::OUString SEInitializer_MSCryptImpl_getImplementationName ()
    throw (cssu::RuntimeException)
{
    return rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( IMPLEMENTATION_NAME ) );
}

sal_Bool SAL_CALL SEInitializer_MSCryptImpl_supportsService( const rtl::OUString& ServiceName )
    throw (cssu::RuntimeException)
{
    return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ));
}

cssu::Sequence< rtl::OUString > SAL_CALL SEInitializer_MSCryptImpl_getSupportedServiceNames(  )
    throw (cssu::RuntimeException)
{
    cssu::Sequence < rtl::OUString > aRet(1);
    rtl::OUString* pArray = aRet.getArray();
    pArray[0] =  rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) );
    return aRet;
}
#undef SERVICE_NAME

cssu::Reference< cssu::XInterface > SAL_CALL SEInitializer_MSCryptImpl_createInstance( const cssu::Reference< cssl::XMultiServiceFactory > & rSMgr)
    throw( cssu::Exception )
{
    return (cppu::OWeakObject*) new SEInitializer_MSCryptImpl(rSMgr);
}

/* XServiceInfo */
rtl::OUString SAL_CALL SEInitializer_MSCryptImpl::getImplementationName(  )
    throw (cssu::RuntimeException)
{
    return SEInitializer_MSCryptImpl_getImplementationName();
}
sal_Bool SAL_CALL SEInitializer_MSCryptImpl::supportsService( const rtl::OUString& rServiceName )
    throw (cssu::RuntimeException)
{
    return SEInitializer_MSCryptImpl_supportsService( rServiceName );
}
cssu::Sequence< rtl::OUString > SAL_CALL SEInitializer_MSCryptImpl::getSupportedServiceNames(  )
    throw (cssu::RuntimeException)
{
    return SEInitializer_MSCryptImpl_getSupportedServiceNames();
}

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