<commit_before>#include "nevil/parallel/parallel_simulator.hpp"

void nevil::parallel::simulator(nevil::args &cl_args)
{
  using namespace nevil;
  using namespace nevil::parallel;

  srand(time(NULL));

  // Default values
  int num_threads = os::get_num_processors() - 1;
  int num_trials = 30;
  bool seeded_trial = false;

  args::const_iterator it;
  // If the number of threads is provided
  if ((it = cl_args.find("tn")) != cl_args.end())
  {
    num_threads = std::stoi(it->second);
    if (num_threads == 0)
      num_threads = os::get_num_processors();
    else if (num_threads < 0)
      num_threads = std::max(1, os::get_num_processors() + num_threads);
  }

  // If the number of trials is provided
  if ((it = cl_args.find("mt")) != cl_args.end())
    num_trials = std::stoi(it->second);

  // Don't spawn more threads than number of trials
  num_threads = std::min(num_threads, num_trials);

  // If the seed is provided, only run one trial with that seed
  if ((it = cl_args.find("rs")) != cl_args.end())
    seeded_trial = true;

  // Don't spawn threads if the number of threads is 1
  // Or Seed is provided
  if (num_threads == 1 || seeded_trial)
  {
    unsigned seed = rand();
    if (seeded_trial)
      seed = std::stoll(cl_args["rs"]);

    trial_controller controller (1, seed, cl_args);
    controller.run();
    return;
  }

  std::vector<std::thread *> threads(num_threads);
  const size_t load = num_trials / num_threads;
  int remeinder = num_trials % num_threads;
  size_t start_id = 1;
  size_t end_id = 1;

  // Launching threads
  for(int i = 0; i < num_threads; ++i)
  {
    end_id = start_id + load + (remeinder-- > 0);
    threads[i] = new std::thread (_run_trial, cl_args, start_id, end_id, rand());
    start_id = end_id;
  }

  for (auto i : threads)
  {
    i->join();
    delete i;
  }
}

void nevil::parallel::_run_trial(nevil::args cl_args, size_t start_id, size_t end_id, unsigned random_seed)
{
  srand(random_seed);
  for (int i = start_id; i < end_id; ++i)
  {
    nevil::trial_controller controller (i, rand(), cl_args);
    controller.run();
  }
}

<commit_msg>Running x number of experiments when the thread number is set to 1<commit_after>#include "nevil/parallel/parallel_simulator.hpp"

void nevil::parallel::simulator(nevil::args &cl_args)
{
  using namespace nevil;
  using namespace nevil::parallel;

  srand(time(NULL));

  // Default values
  int num_threads = os::get_num_processors() - 1;
  int num_trials = 30;
  bool seeded_trial = false;

  args::const_iterator it;
  // If the number of threads is provided
  if ((it = cl_args.find("tn")) != cl_args.end())
  {
    num_threads = std::stoi(it->second);
    if (num_threads == 0)
      num_threads = os::get_num_processors();
    else if (num_threads < 0)
      num_threads = std::max(1, os::get_num_processors() + num_threads);
  }

  // If the number of trials is provided
  if ((it = cl_args.find("mt")) != cl_args.end())
    num_trials = std::stoi(it->second);

  // Don't spawn more threads than number of trials
  num_threads = std::min(num_threads, num_trials);

  // If the seed is provided, only run one trial with that seed
  if ((it = cl_args.find("rs")) != cl_args.end())
    seeded_trial = true;

  // Run only one experiment if seed is provided
  if (seeded_trial)
  {
    unsigned seed = std::stoll(cl_args["rs"]);
    trial_controller controller (1, seed, cl_args);
    controller.run();
    return;
  }

  // Don't spawn threads if the number of threads is 1
  if (num_threads == 1)
  {
    for (int i = 1; i <= num_trials; ++i)
    {
      trial_controller controller (i, rand(), cl_args);
      controller.run();
    }
    return;
  }

  std::vector<std::thread *> threads(num_threads);
  const size_t load = num_trials / num_threads;
  int remeinder = num_trials % num_threads;
  size_t start_id = 1;
  size_t end_id = 1;

  // Launching threads
  for(int i = 0; i < num_threads; ++i)
  {
    end_id = start_id + load + (remeinder-- > 0);
    threads[i] = new std::thread (_run_trial, cl_args, start_id, end_id, rand());
    start_id = end_id;
  }

  for (auto i : threads)
  {
    i->join();
    delete i;
  }
}

void nevil::parallel::_run_trial(nevil::args cl_args, size_t start_id, size_t end_id, unsigned random_seed)
{
  srand(random_seed);
  for (int i = start_id; i < end_id; ++i)
  {
    nevil::trial_controller controller (i, rand(), cl_args);
    controller.run();
  }
}

<|endoftext|>


<commit_before>/*
 * Elevator.cpp
 *
 *  Created on: Jan 16, 2015
 *      Author: acf
 */

#include "Elevator.hpp"
#include "Solenoid.h"
#include "CANTalon.h"

Elevator::Elevator() {
    m_grabSolenoid = new Solenoid(1);
    m_intakeVertical = new Solenoid(2);
    m_intakeGrabber = new Solenoid(3);
    m_intakeWheels = new CANTalon(6);
    m_settings = new Settings("/home/lvuser/RobotSettings.txt");
    m_intakeState = S_STOPPED;
    m_manual = false;

    m_liftGrbx = new GearBox<CANTalon>(-1, 4, 5);
    /* gear ratio is 48 driver to 26 driven from output of gearbox (where
     * encoder shaft is located), therefore:
     * distance per pulse = 26/48/(number of pulses per revolution)
     *                    = 26/48/360
     *                    = 26/(48*360)
     */
    m_liftGrbx->setDistancePerPulse(26 / (48 * 360));
    reloadPID();
}

Elevator::~Elevator() {
	delete m_grabSolenoid;
	delete m_intakeVertical;
	delete m_intakeGrabber;
	delete m_intakeWheels;
	delete m_settings;
	delete m_liftGrbx;
}

void Elevator::elevatorGrab(bool state) {
    m_grabSolenoid->Set(state);
}

bool Elevator::getElevatorGrab() {
    return m_grabSolenoid->Get();
}

void Elevator::intakeGrab(bool state) {
    m_intakeGrabber->Set(state);
}

bool Elevator::getIntakeGrab() {
    return m_intakeGrabber->Get();
}

void Elevator::stowIntake(bool state) {
    m_intakeVertical->Set(state);
}

bool Elevator::isIntakeStowed() {
    return m_intakeVertical->Get();
}

void Elevator::setIntakeDirection(IntakeMotorState state) {
    m_intakeState = state;

    if (state == S_STOPPED) {
        m_intakeWheels->Set(0);
    }
    else if (state == S_FORWARD) {
        m_intakeWheels->Set(1);
    }
    else if (state == S_REVERSED) {
        m_intakeWheels->Set(-1);
    }
}

Elevator::IntakeMotorState Elevator::getIntakeDirection() {
    return m_intakeState;
}

void Elevator::stop(bool state) {
}

void Elevator::setManualLiftSpeed(float value) {
    if (m_manual == true) {
        m_liftGrbx->setManual(value);
    }
}

void Elevator::setManualMode(bool on) {
    m_manual = on;
}

bool Elevator::getManualMode() {
    return m_manual;
}

void Elevator::setHeight(float height) {
    if (m_manual == false) {
        m_liftGrbx->setSetpoint(height);
    }
}

void Elevator::reloadPID() {
    m_settings->update();

    float p = 0.f;
    float i = 0.f;
    float d = 0.f;

    // Set shooter rotator PID
    p = m_settings->getFloat("PID_ELEVATOR_P");
    i = m_settings->getFloat("PID_ELEVATOR_I");
    d = m_settings->getFloat("PID_ELEVATOR_D");
    m_liftGrbx->setPID(p, i, d);
}

<commit_msg>formatting: ran formatter<commit_after>/*
 * Elevator.cpp
 *
 *  Created on: Jan 16, 2015
 *      Author: acf
 */

#include "Elevator.hpp"
#include "Solenoid.h"
#include "CANTalon.h"

Elevator::Elevator() {
    m_grabSolenoid = new Solenoid(1);
    m_intakeVertical = new Solenoid(2);
    m_intakeGrabber = new Solenoid(3);
    m_intakeWheels = new CANTalon(6);
    m_settings = new Settings("/home/lvuser/RobotSettings.txt");
    m_intakeState = S_STOPPED;
    m_manual = false;

    m_liftGrbx = new GearBox<CANTalon>(-1, 4, 5);
    /* gear ratio is 48 driver to 26 driven from output of gearbox (where
     * encoder shaft is located), therefore:
     * distance per pulse = 26/48/(number of pulses per revolution)
     *                    = 26/48/360
     *                    = 26/(48*360)
     */
    m_liftGrbx->setDistancePerPulse(26 / (48 * 360));
    reloadPID();
}

Elevator::~Elevator() {
    delete m_grabSolenoid;
    delete m_intakeVertical;
    delete m_intakeGrabber;
    delete m_intakeWheels;
    delete m_settings;
    delete m_liftGrbx;
}

void Elevator::elevatorGrab(bool state) {
    m_grabSolenoid->Set(state);
}

bool Elevator::getElevatorGrab() {
    return m_grabSolenoid->Get();
}

void Elevator::intakeGrab(bool state) {
    m_intakeGrabber->Set(state);
}

bool Elevator::getIntakeGrab() {
    return m_intakeGrabber->Get();
}

void Elevator::stowIntake(bool state) {
    m_intakeVertical->Set(state);
}

bool Elevator::isIntakeStowed() {
    return m_intakeVertical->Get();
}

void Elevator::setIntakeDirection(IntakeMotorState state) {
    m_intakeState = state;

    if (state == S_STOPPED) {
        m_intakeWheels->Set(0);
    }
    else if (state == S_FORWARD) {
        m_intakeWheels->Set(1);
    }
    else if (state == S_REVERSED) {
        m_intakeWheels->Set(-1);
    }
}

Elevator::IntakeMotorState Elevator::getIntakeDirection() {
    return m_intakeState;
}

void Elevator::stop(bool state) {
}

void Elevator::setManualLiftSpeed(float value) {
    if (m_manual == true) {
        m_liftGrbx->setManual(value);
    }
}

void Elevator::setManualMode(bool on) {
    m_manual = on;
}

bool Elevator::getManualMode() {
    return m_manual;
}

void Elevator::setHeight(float height) {
    if (m_manual == false) {
        m_liftGrbx->setSetpoint(height);
    }
}

void Elevator::reloadPID() {
    m_settings->update();

    float p = 0.f;
    float i = 0.f;
    float d = 0.f;

    // Set shooter rotator PID
    p = m_settings->getFloat("PID_ELEVATOR_P");
    i = m_settings->getFloat("PID_ELEVATOR_I");
    d = m_settings->getFloat("PID_ELEVATOR_D");
    m_liftGrbx->setPID(p, i, d);
}

<|endoftext|>


<commit_before>#ifdef WITH_HDF5
#include <pybind11/pybind11.h>
#include <iostream>
#include <sstream>
#include <pybind11/numpy.h>

#include "nifty/python/converter.hxx"
#include "nifty/marray/marray_hdf5.hxx"
#include "nifty/hdf5/hdf5_array.hxx"

namespace py = pybind11;

namespace nifty{
namespace hdf5{

    using namespace marray::hdf5;

    void exportHdf5Common(py::module & hdf5Module) {

        py::enum_<FileAccessMode>(hdf5Module, "FileAccessMode")
            .value("READ_ONLY", FileAccessMode::READ_ONLY)
            .value("READ_WRITE", FileAccessMode::READ_WRITE)
            //.export_values();
        ;

        py::enum_<HDF5Version>(hdf5Module, "HDF5Version")
            .value("DEFAULT_HDF5_VERSION", HDF5Version::DEFAULT_HDF5_VERSION)
            .value("LATEST_HDF5_VERSION", HDF5Version::LATEST_HDF5_VERSION)
            //.export_values();
        ;

        py::class_<hid_t>(hdf5Module, "HidT")
        ;

        hdf5Module.def("createFile", &createFile2,
            py::arg("filename"),
            py::arg("hdf5version")=LATEST_HDF5_VERSION,
            py::arg("hashTableSize") = 977,
            py::arg("nBytes") = 36000000,
            py::arg("rddc") = 1.0
        );

        hdf5Module.def("openFile", &openFile2,
            py::arg("filename"),
            py::arg_t<FileAccessMode>("hdf5version",READ_ONLY),
            py::arg_t<HDF5Version>("hdf5version",LATEST_HDF5_VERSION),
            py::arg("hashTableSize") = 977,
            py::arg("nBytes") = 36000000,
            py::arg("rddc") = 1.0
        );

        hdf5Module.def("closeFile", &closeFile,
            py::arg("hidT")
        );

        hdf5Module.def("createGroup", &createGroup,
            py::arg("hidT"),
            py::arg("groupName")
        );

        hdf5Module.def("openGroup", &openGroup,
            py::arg("hidT"),
            py::arg("groupName")
        );

        hdf5Module.def("closeGroup", &closeGroup,
            py::arg("hidT")
        );

    }

}
}

#endif
<commit_msg>hdf5: refactored file chunk settigns<commit_after>#ifdef WITH_HDF5
#include <pybind11/pybind11.h>
#include <iostream>
#include <sstream>
#include <pybind11/numpy.h>

#include "nifty/python/converter.hxx"
#include "nifty/hdf5/hdf5.hxx"

namespace py = pybind11;

namespace nifty{
namespace hdf5{

    using namespace marray::hdf5;

    void exportHdf5Common(py::module & hdf5Module) {

        py::enum_<FileAccessMode>(hdf5Module, "FileAccessMode")
            .value("READ_ONLY", FileAccessMode::READ_ONLY)
            .value("READ_WRITE", FileAccessMode::READ_WRITE)
            //.export_values();
        ;

        py::enum_<HDF5Version>(hdf5Module, "HDF5Version")
            .value("DEFAULT_HDF5_VERSION", HDF5Version::DEFAULT_HDF5_VERSION)
            .value("LATEST_HDF5_VERSION", HDF5Version::LATEST_HDF5_VERSION)
            //.export_values();
        ;

        py::class_<hid_t>(hdf5Module, "HidT")
        ;

        py::class_<CacheSettings>(hdf5Module, "CacheSettings")
            .def(py::init<int,int,float>(),
                py::arg("hashTabelSize") = 977,
                py::arg("nBytes") = 36000000,
                py::arg("rddc") = 1.0
            )
            .def_readwrite("hashTabelSize", &CacheSettings::hashTabelSize)
            .def_readwrite("nBytes", &CacheSettings::nBytes)
            .def_readwrite("rddc", &CacheSettings::rddc)
        ;

        hdf5Module.def("createFile", [](
            const std::string & filename,
            const CacheSettings & cacheSettings,
            const HDF5Version & hdf5version
        ){
            return createFile(filename, cacheSettings, hdf5version);
        },
            py::arg("filename"),
            py::arg("cacheSettings"),
            py::arg("hdf5version") = DEFAULT_HDF5_VERSION
        );

        hdf5Module.def("createFile", [](
            const std::string & filename,
            const HDF5Version & hdf5version
        ){
            return createFile(filename, hdf5version);
        },
            py::arg("filename"),
            py::arg("hdf5version") = DEFAULT_HDF5_VERSION
        );

        hdf5Module.def("openFile", [](
            const std::string & filename,
            const CacheSettings & cacheSettings,
            const FileAccessMode & fileAccessMode,
            const HDF5Version & hdf5version
        ){
            return openFile(filename, cacheSettings,fileAccessMode, hdf5version);
        },
            py::arg("filename"),
            py::arg("cacheSettings"),
            py::arg("fileAccessMode") = READ_ONLY,
            py::arg("hdf5version") = DEFAULT_HDF5_VERSION
        );

        hdf5Module.def("openFile", [](
            const std::string & filename,
            const FileAccessMode & fileAccessMode,
            const HDF5Version & hdf5version
        ){
            return openFile(filename,fileAccessMode, hdf5version);
        },
            py::arg("filename"),
            py::arg("fileAccessMode") = READ_ONLY,
            py::arg("hdf5version") = DEFAULT_HDF5_VERSION
        );

        hdf5Module.def("closeFile", &closeFile,
            py::arg("hidT")
        );

        hdf5Module.def("createGroup", &createGroup,
            py::arg("hidT"),
            py::arg("groupName")
        );

        hdf5Module.def("openGroup", &openGroup,
            py::arg("hidT"),
            py::arg("groupName")
        );

        hdf5Module.def("closeGroup", &closeGroup,
            py::arg("hidT")
        );

    }

}
}

#endif
<|endoftext|>


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

This file is part of the QtMediaHub project on http://www.gitorious.org.

Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).*
All rights reserved.

Contact:  Nokia Corporation (qt-info@nokia.com)**

You may use this file under the terms of the BSD license as follows:

"Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."

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

#include "actionmapper.h"

#include "backend.h"
#include "frontend.h"

#include "qmh-config.h"

class Frontend;

ActionMapper::ActionMapper(Frontend *p)
    : QObject(p),
      pFrontend(p),
      mapPath(Backend::instance()->basePath() + "/devices/keymaps/")
{
    setObjectName("qmhrpc");

    maps = QDir(mapPath).entryList(QDir::Files);
    qWarning() << "Available keyboard maps" << maps;

    mapName = Config::value("keymap", "").toString();
    populateMap();
}

void ActionMapper::takeAction(Action action)
{
    if (!pFrontend || !keyHash.contains(action))
        return;
    QKeyEvent keyPress(QEvent::KeyPress, keyHash[action].at(0), Qt::NoModifier);
    qApp->sendEvent(pFrontend->centralWidget(), &keyPress);
    QKeyEvent keyRelease(QEvent::KeyRelease, keyHash[action].at(0), Qt::NoModifier);
    qApp->sendEvent(pFrontend->centralWidget(), &keyRelease);
}

void ActionMapper::populateMap()
{
    keyHash.clear();

    if (!loadMapFromDisk(mapPath + mapName))
        loadMapFromDisk(mapPath + "stdkeyboard");
}

bool ActionMapper::loadMapFromDisk(const QString &mapFilePath)
{
    const QMetaObject &ActionMO = ActionMapper::staticMetaObject;
    int enumIndex = ActionMO.indexOfEnumerator("Action");
    QMetaEnum actionEnum = ActionMO.enumerator(enumIndex);

    enumIndex = staticQtMetaObject.indexOfEnumerator("Key");
    QMetaEnum keyEnum = staticQtMetaObject.enumerator(enumIndex);

    QFile mapFile(mapFilePath);
    if (mapFile.exists()
        && mapFile.open(QIODevice::ReadOnly))
    {
        qWarning() << "Load keymap" << mapFilePath;

        QTextStream mapStream(&mapFile);
        while(!mapStream.atEnd())
        {
            QStringList mapping = mapStream.readLine().split("=");
            QStringList keyStrings = mapping.at(1).split(",");
            QList<int> keys;
            foreach(const QString &key, keyStrings)
            {
                int keyIndex = keyEnum.keyToValue(QString("Key_").append(key).toAscii().constData());
                if(keyIndex == -1)
                    qWarning() << "\tQt Key does not exist: Key_" << key;
                else
                    keys << keyIndex;
            }
            int index =
                actionEnum.keyToValue(mapping[0].toAscii().constData());
            if (index == -1)
                qWarning() << "\tMapped action is not defined in ActionMapper, skipping: " << mapping[0];
            else
                keyHash[static_cast<Action>(index)] = keys;
        }
        if(actionEnum.keyCount() != keyHash.size())
            qWarning("\tCertain actions have not been mapped");
        else
            qWarning("\tAll keys mapped correctly");
    } else {
        qWarning() << "Could not load keymap: " << mapFilePath;
        return false;
    }

    return true;
}
<commit_msg>Just set default keymap name<commit_after>/****************************************************************************

This file is part of the QtMediaHub project on http://www.gitorious.org.

Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).*
All rights reserved.

Contact:  Nokia Corporation (qt-info@nokia.com)**

You may use this file under the terms of the BSD license as follows:

"Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."

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

#include "actionmapper.h"

#include "backend.h"
#include "frontend.h"

#include "qmh-config.h"

class Frontend;

ActionMapper::ActionMapper(Frontend *p)
    : QObject(p),
      pFrontend(p),
      mapPath(Backend::instance()->basePath() + "/devices/keymaps/")
{
    setObjectName("qmhrpc");

    maps = QDir(mapPath).entryList(QDir::Files);
    qWarning() << "Available keyboard maps" << maps;

    mapName = Config::value("keymap", "stdkeyboard").toString();
    populateMap();
}

void ActionMapper::takeAction(Action action)
{
    if (!pFrontend || !keyHash.contains(action))
        return;
    QKeyEvent keyPress(QEvent::KeyPress, keyHash[action].at(0), Qt::NoModifier);
    qApp->sendEvent(pFrontend->centralWidget(), &keyPress);
    QKeyEvent keyRelease(QEvent::KeyRelease, keyHash[action].at(0), Qt::NoModifier);
    qApp->sendEvent(pFrontend->centralWidget(), &keyRelease);
}

void ActionMapper::populateMap()
{
    keyHash.clear();

    loadMapFromDisk(mapPath + mapName);
}

bool ActionMapper::loadMapFromDisk(const QString &mapFilePath)
{
    const QMetaObject &ActionMO = ActionMapper::staticMetaObject;
    int enumIndex = ActionMO.indexOfEnumerator("Action");
    QMetaEnum actionEnum = ActionMO.enumerator(enumIndex);

    enumIndex = staticQtMetaObject.indexOfEnumerator("Key");
    QMetaEnum keyEnum = staticQtMetaObject.enumerator(enumIndex);

    QFile mapFile(mapFilePath);
    if (mapFile.exists()
        && mapFile.open(QIODevice::ReadOnly))
    {
        qWarning() << "Load keymap" << mapFilePath;

        QTextStream mapStream(&mapFile);
        while(!mapStream.atEnd())
        {
            QStringList mapping = mapStream.readLine().split("=");
            QStringList keyStrings = mapping.at(1).split(",");
            QList<int> keys;
            foreach(const QString &key, keyStrings)
            {
                int keyIndex = keyEnum.keyToValue(QString("Key_").append(key).toAscii().constData());
                if(keyIndex == -1)
                    qWarning() << "\tQt Key does not exist: Key_" << key;
                else
                    keys << keyIndex;
            }
            int index =
                actionEnum.keyToValue(mapping[0].toAscii().constData());
            if (index == -1)
                qWarning() << "\tMapped action is not defined in ActionMapper, skipping: " << mapping[0];
            else
                keyHash[static_cast<Action>(index)] = keys;
        }
        if(actionEnum.keyCount() != keyHash.size())
            qWarning("\tCertain actions have not been mapped");
        else
            qWarning("\tAll keys mapped correctly");
    } else {
        qWarning() << "Could not load keymap: " << mapFilePath;
        return false;
    }

    return true;
}
<|endoftext|>


<commit_before>// Copyright (c) 2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "qt/pivx/sendcustomfeedialog.h"
#include "qt/pivx/forms/ui_sendcustomfeedialog.h"
#include "qt/pivx/qtutils.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include <QListView>
#include <QComboBox>

SendCustomFeeDialog::SendCustomFeeDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SendCustomFeeDialog)
{
    ui->setupUi(this);

    // Stylesheet
    this->setStyleSheet(parent->styleSheet());
    setCssProperty(ui->frame, "container-dialog");

    // Text
    ui->labelTitle->setText(tr("Customize Fee"));
    ui->labelMessage->setText(tr("Customize the transaction fee at your to your liking, depending on the fee value your transaction will be included or not in the blockchain."));
    setCssProperty(ui->labelTitle, "text-title-dialog");
    setCssProperty(ui->labelMessage, "text-main-grey");

    // Recommended
    setCssProperty(ui->labelFee, "text-main-grey-big");
    setCssProperty(ui->comboBoxRecommended, "btn-combo-dialog");
    ui->comboBoxRecommended->setView(new QListView());
    ui->comboBoxRecommended->addItem(tr("Normal"), 5);
    ui->comboBoxRecommended->addItem(tr("Slow"), 20);
    ui->comboBoxRecommended->addItem(tr("Fast"), 1);

    // Custom
    setCssProperty(ui->labelCustomFee, "label-subtitle-dialog");
    ui->lineEditCustomFee->setPlaceholderText("0.000001 PIV");
    initCssEditLine(ui->lineEditCustomFee, true);

    // Buttons
    setCssProperty(ui->btnEsc, "ic-close");
    setCssProperty(ui->btnCancel, "btn-dialog-cancel");
    ui->btnSave->setText(tr("SAVE"));
    setCssBtnPrimary(ui->btnSave);

    connect(ui->btnEsc, SIGNAL(clicked()), this, SLOT(close()));
    connect(ui->btnCancel, SIGNAL(clicked()), this, SLOT(close()));
    connect(ui->btnSave, SIGNAL(clicked()), this, SLOT(accept()));
    connect(ui->checkBoxCustom, SIGNAL(clicked()), this, SLOT(onCustomChecked()));
    connect(ui->checkBoxRecommended, SIGNAL(clicked()), this, SLOT(onRecommendedChecked()));
    connect(ui->comboBoxRecommended, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(updateFee()));
    if(parent) connect(parent, SIGNAL(themeChanged(bool, QString&)), this, SLOT(onChangeTheme(bool, QString&)));
    ui->checkBoxRecommended->setChecked(true);
}

void SendCustomFeeDialog::setWalletModel(WalletModel* walletModel){
    this->walletModel = walletModel;
}

void SendCustomFeeDialog::showEvent(QShowEvent *event){
    updateFee();
}

void SendCustomFeeDialog::onCustomChecked(){
    bool isChecked = ui->checkBoxCustom->checkState() == Qt::Checked;
    ui->lineEditCustomFee->setEnabled(isChecked);
    ui->comboBoxRecommended->setEnabled(!isChecked);
    ui->checkBoxRecommended->setChecked(!isChecked);

    if(walletModel && ui->lineEditCustomFee->text().isEmpty()) {
        feeRate = CWallet::minTxFee;
        ui->lineEditCustomFee->setText(BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), feeRate.GetFeePerK()));
    }
}

void SendCustomFeeDialog::onRecommendedChecked(){
    bool isChecked = ui->checkBoxRecommended->checkState() == Qt::Checked;
    ui->lineEditCustomFee->setEnabled(!isChecked);
    ui->comboBoxRecommended->setEnabled(isChecked);
    ui->checkBoxCustom->setChecked(!isChecked);
}

// Fast = 1.
// Medium = 5
// Slow = 20
void SendCustomFeeDialog::updateFee(){
    if (!walletModel || !walletModel->getOptionsModel()) return;

    QVariant num = ui->comboBoxRecommended->currentData();
    bool res = false;
    int nBlocksToConfirm = num.toInt(&res);
    if (res) {
        feeRate = mempool.estimateFee(nBlocksToConfirm);
        if (feeRate <= CFeeRate(0)) { // not enough data => minfee
            feeRate = CWallet::minTxFee;
            ui->labelFee->setText(BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(),
                                                               feeRate.GetFeePerK()) + "/kB");
        } else {
            ui->labelFee->setText(
                    BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(),
                                                 feeRate.GetFeePerK()) + "/kB");
        }
    }
}

void SendCustomFeeDialog::clear(){
    onRecommendedChecked();
    updateFee();
}

CFeeRate SendCustomFeeDialog::getFeeRate(){
    return ui->checkBoxRecommended->isChecked() ?
           feeRate : CFeeRate(GUIUtil::parseValue(ui->lineEditCustomFee->text(), walletModel->getOptionsModel()->getDisplayUnit()));
}

void SendCustomFeeDialog::onChangeTheme(bool isLightTheme, QString& theme){
    this->setStyleSheet(theme);
    updateStyle(this);
}

SendCustomFeeDialog::~SendCustomFeeDialog(){
    delete ui;
}
<commit_msg>[Trivial] [GUI] Customize Fee Dialog text change<commit_after>// Copyright (c) 2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "qt/pivx/sendcustomfeedialog.h"
#include "qt/pivx/forms/ui_sendcustomfeedialog.h"
#include "qt/pivx/qtutils.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include <QListView>
#include <QComboBox>

SendCustomFeeDialog::SendCustomFeeDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SendCustomFeeDialog)
{
    ui->setupUi(this);

    // Stylesheet
    this->setStyleSheet(parent->styleSheet());
    setCssProperty(ui->frame, "container-dialog");

    // Text
    ui->labelTitle->setText(tr("Customize Fee"));
    ui->labelMessage->setText(tr("Customize the transaction fee, depending on the fee value your transaction will be included or not in the blockchain."));
    setCssProperty(ui->labelTitle, "text-title-dialog");
    setCssProperty(ui->labelMessage, "text-main-grey");

    // Recommended
    setCssProperty(ui->labelFee, "text-main-grey-big");
    setCssProperty(ui->comboBoxRecommended, "btn-combo-dialog");
    ui->comboBoxRecommended->setView(new QListView());
    ui->comboBoxRecommended->addItem(tr("Normal"), 5);
    ui->comboBoxRecommended->addItem(tr("Slow"), 20);
    ui->comboBoxRecommended->addItem(tr("Fast"), 1);

    // Custom
    setCssProperty(ui->labelCustomFee, "label-subtitle-dialog");
    ui->lineEditCustomFee->setPlaceholderText("0.000001 PIV");
    initCssEditLine(ui->lineEditCustomFee, true);

    // Buttons
    setCssProperty(ui->btnEsc, "ic-close");
    setCssProperty(ui->btnCancel, "btn-dialog-cancel");
    ui->btnSave->setText(tr("SAVE"));
    setCssBtnPrimary(ui->btnSave);

    connect(ui->btnEsc, SIGNAL(clicked()), this, SLOT(close()));
    connect(ui->btnCancel, SIGNAL(clicked()), this, SLOT(close()));
    connect(ui->btnSave, SIGNAL(clicked()), this, SLOT(accept()));
    connect(ui->checkBoxCustom, SIGNAL(clicked()), this, SLOT(onCustomChecked()));
    connect(ui->checkBoxRecommended, SIGNAL(clicked()), this, SLOT(onRecommendedChecked()));
    connect(ui->comboBoxRecommended, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(updateFee()));
    if(parent) connect(parent, SIGNAL(themeChanged(bool, QString&)), this, SLOT(onChangeTheme(bool, QString&)));
    ui->checkBoxRecommended->setChecked(true);
}

void SendCustomFeeDialog::setWalletModel(WalletModel* walletModel){
    this->walletModel = walletModel;
}

void SendCustomFeeDialog::showEvent(QShowEvent *event){
    updateFee();
}

void SendCustomFeeDialog::onCustomChecked(){
    bool isChecked = ui->checkBoxCustom->checkState() == Qt::Checked;
    ui->lineEditCustomFee->setEnabled(isChecked);
    ui->comboBoxRecommended->setEnabled(!isChecked);
    ui->checkBoxRecommended->setChecked(!isChecked);

    if(walletModel && ui->lineEditCustomFee->text().isEmpty()) {
        feeRate = CWallet::minTxFee;
        ui->lineEditCustomFee->setText(BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), feeRate.GetFeePerK()));
    }
}

void SendCustomFeeDialog::onRecommendedChecked(){
    bool isChecked = ui->checkBoxRecommended->checkState() == Qt::Checked;
    ui->lineEditCustomFee->setEnabled(!isChecked);
    ui->comboBoxRecommended->setEnabled(isChecked);
    ui->checkBoxCustom->setChecked(!isChecked);
}

// Fast = 1.
// Medium = 5
// Slow = 20
void SendCustomFeeDialog::updateFee(){
    if (!walletModel || !walletModel->getOptionsModel()) return;

    QVariant num = ui->comboBoxRecommended->currentData();
    bool res = false;
    int nBlocksToConfirm = num.toInt(&res);
    if (res) {
        feeRate = mempool.estimateFee(nBlocksToConfirm);
        if (feeRate <= CFeeRate(0)) { // not enough data => minfee
            feeRate = CWallet::minTxFee;
            ui->labelFee->setText(BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(),
                                                               feeRate.GetFeePerK()) + "/kB");
        } else {
            ui->labelFee->setText(
                    BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(),
                                                 feeRate.GetFeePerK()) + "/kB");
        }
    }
}

void SendCustomFeeDialog::clear(){
    onRecommendedChecked();
    updateFee();
}

CFeeRate SendCustomFeeDialog::getFeeRate(){
    return ui->checkBoxRecommended->isChecked() ?
           feeRate : CFeeRate(GUIUtil::parseValue(ui->lineEditCustomFee->text(), walletModel->getOptionsModel()->getDisplayUnit()));
}

void SendCustomFeeDialog::onChangeTheme(bool isLightTheme, QString& theme){
    this->setStyleSheet(theme);
    updateStyle(this);
}

SendCustomFeeDialog::~SendCustomFeeDialog(){
    delete ui;
}
<|endoftext|>


<commit_before>#include "scenemanager.hpp"

#include <chrono>
#include <thread>
#include <mutex>
#include <typeinfo>

#include "glload/gl_3_2.h"
#include <GL/glfw.h>

#include "scenegroup.hpp"
#include "perspectivecamera.hpp"

#include "render/lightmanager.hpp"

#include "collisiondetection/collidable.hpp"
#include "collisiondetection/objectorientedboundingbox.hpp"

#include "config/globals.hpp"

using namespace scene;

SceneManager::SceneManager()
: world(3, collisiondetection::AABB(std::make_tuple(glm::vec3(-10.0f, -10.0f, 10.0f), glm::vec3(10.0f, 10.0f, -50.0f)))),
running(false){
}

void SceneManager::startSceneLoop() {
	scene::PerspectiveCamera& camera = scene::PerspectiveCamera::getInstance();

	running = true;

	std::thread updateThread([this, &camera]() {
		while(running) {
			universalGravity.update();

			world.visitScene([](std::shared_ptr<SceneItem> child) {
				child->update();

				child->buildModelMatrix();
			});

			world.visitGroups([](SceneGroup& group) {
				for (std::shared_ptr<SceneItem>& child : group.childItems) {
					auto collidable = std::dynamic_pointer_cast<collisiondetection::Collidable>(child);

					if(collidable.get() != nullptr) {
						std::function<void(const SceneGroup&)> collisionCheck = [collidable, child](const SceneGroup& otherGroup) {
							for(const std::shared_ptr<SceneItem>& other : otherGroup.childItems) {
								if(child.get() != other.get()) {
									const collisiondetection::ObjectOrientedBoundingBox collidableBounds = child->getBounds();
									collidableBounds.attachToItem(child.get());

									const collisiondetection::ObjectOrientedBoundingBox otherBounds = other->getBounds();
									otherBounds.attachToItem(other.get());

									if(collidableBounds.intersects(otherBounds)) {
										collidable->handleCollision(*other);
									}
								}
							}
						};

						collisionCheck(group);

						if(group.childGroups != nullptr) {
							//Check underlying groups for lower edge cases
							for(SceneGroup& childGroup : *group.childGroups) {
								collisionCheck(childGroup);
							}
						}

						//Check with parents for upper edge cases
						group.visitParentGroups(collisionCheck);
					}
				}
			});

			world.visitGroups([](SceneGroup& group) {
				if(group.constraints != nullptr) {
					std::vector<std::shared_ptr<SceneItem>> bubbleCandidates;

					auto it = group.childItems.begin();
					while(it != group.childItems.end()) {
						const collisiondetection::BoundingVolume& otherBounds = (*it)->getBounds();
						otherBounds.attachToItem((*it).get());

						if(!otherBounds.intersects(*(group.constraints))) {
							std::lock_guard<std::recursive_mutex> guard(group.rootNode->sceneMutex);

							bubbleCandidates.push_back(*it);
							it = group.childItems.erase(it);
						} else {
							++it;
						}
					}

					for(std::shared_ptr<SceneItem>& candidate : bubbleCandidates) {
						group.rootNode->bubbleItem(candidate);
					}
				}
			});

			std::this_thread::sleep_for(std::chrono::milliseconds((unsigned int)(1.0f/config::globals::updateRate)*1000));
		}
	});

	while(running) {
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

		render::LightManager::getInstance().upload();
		camera.render(&world);

		glfwSwapBuffers();

		std::this_thread::sleep_for(std::chrono::milliseconds((unsigned int)(1.0f/config::globals::frameRate)*1000));
	}

	updateThread.join();
}

void SceneManager::stopSceneLoop() {
	running = false;
}

void SceneManager::addItem(std::shared_ptr<SceneItem> item) {
	GravitationalObject* gravObject = dynamic_cast<GravitationalObject*>(item.get());
	if(gravObject != nullptr) {
		universalGravity.addObject(gravObject);
	}

	std::lock_guard<std::recursive_mutex> guard(world.rootNode->sceneMutex);
	world.bubbleItem(item);
}
<commit_msg>Collision detection: Check all underlying groups<commit_after>#include "scenemanager.hpp"

#include <chrono>
#include <thread>
#include <mutex>
#include <typeinfo>

#include "glload/gl_3_2.h"
#include <GL/glfw.h>

#include "scenegroup.hpp"
#include "perspectivecamera.hpp"

#include "render/lightmanager.hpp"

#include "collisiondetection/collidable.hpp"
#include "collisiondetection/objectorientedboundingbox.hpp"

#include "config/globals.hpp"

using namespace scene;

SceneManager::SceneManager()
: world(3, collisiondetection::AABB(std::make_tuple(glm::vec3(-10.0f, -10.0f, 10.0f), glm::vec3(10.0f, 10.0f, -50.0f)))),
running(false){
}

void SceneManager::startSceneLoop() {
	scene::PerspectiveCamera& camera = scene::PerspectiveCamera::getInstance();

	running = true;

	std::thread updateThread([this, &camera]() {
		while(running) {
			universalGravity.update();

			world.visitScene([](std::shared_ptr<SceneItem> child) {
				child->update();

				child->buildModelMatrix();
			});

			world.visitGroups([](SceneGroup& group) {
				for (std::shared_ptr<SceneItem>& child : group.childItems) {
					auto collidable = std::dynamic_pointer_cast<collisiondetection::Collidable>(child);

					if(collidable.get() != nullptr) {
						std::function<void(const SceneGroup&)> collisionCheck = [collidable, child](const SceneGroup& otherGroup) {
							for(const std::shared_ptr<SceneItem>& other : otherGroup.childItems) {
								if(child.get() != other.get()) {
									const collisiondetection::ObjectOrientedBoundingBox collidableBounds = child->getBounds();
									collidableBounds.attachToItem(child.get());

									const collisiondetection::ObjectOrientedBoundingBox otherBounds = other->getBounds();
									otherBounds.attachToItem(other.get());

									if(collidableBounds.intersects(otherBounds)) {
										collidable->handleCollision(*other);
									}
								}
							}
						};

						collisionCheck(group);

						if(group.childGroups != nullptr) {
							//Check underlying groups for lower edge cases
							group.visitGroups(collisionCheck);
						}

						//Check with parents for upper edge cases
						group.visitParentGroups(collisionCheck);
					}
				}
			});

			world.visitGroups([](SceneGroup& group) {
				if(group.constraints != nullptr) {
					std::vector<std::shared_ptr<SceneItem>> bubbleCandidates;

					auto it = group.childItems.begin();
					while(it != group.childItems.end()) {
						const collisiondetection::BoundingVolume& otherBounds = (*it)->getBounds();
						otherBounds.attachToItem((*it).get());

						if(!otherBounds.intersects(*(group.constraints))) {
							std::lock_guard<std::recursive_mutex> guard(group.rootNode->sceneMutex);

							bubbleCandidates.push_back(*it);
							it = group.childItems.erase(it);
						} else {
							++it;
						}
					}

					for(std::shared_ptr<SceneItem>& candidate : bubbleCandidates) {
						group.rootNode->bubbleItem(candidate);
					}
				}
			});

			std::this_thread::sleep_for(std::chrono::milliseconds((unsigned int)(1.0f/config::globals::updateRate)*1000));
		}
	});

	while(running) {
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

		render::LightManager::getInstance().upload();
		camera.render(&world);

		glfwSwapBuffers();

		std::this_thread::sleep_for(std::chrono::milliseconds((unsigned int)(1.0f/config::globals::frameRate)*1000));
	}

	updateThread.join();
}

void SceneManager::stopSceneLoop() {
	running = false;
}

void SceneManager::addItem(std::shared_ptr<SceneItem> item) {
	GravitationalObject* gravObject = dynamic_cast<GravitationalObject*>(item.get());
	if(gravObject != nullptr) {
		universalGravity.addObject(gravObject);
	}

	std::lock_guard<std::recursive_mutex> guard(world.rootNode->sceneMutex);
	world.bubbleItem(item);
}
<|endoftext|>


<commit_before>/*
 * Copyright 2016 <Lennart Nachtigall> <firesurfer65@yahoo.de>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "ManagedNode.h"
namespace ros2_components {

ManagedNode::ManagedNode(std::string _nodeName, int argc, char *argv[], bool parseCli):cliParser{argv,argc,nodeName}
{

    //Initialise ros2
    rclcpp::init(argc, argv);
    executor = std::make_shared<rclcpp::executors::SingleThreadedExecutor>();

    nodeName = _nodeName;

    //TODO put additional help information into parser

    CLIArgument idArg = {"id","Specify id used for the node", &id_str};
    CLIArgument logArg = {"logpath","Path to the logfile - also enables the logging to a file", &this->LogfilePath};
    CLIArgument configArg = {"configpath","Path to a configfile", &this->ConfigfilePath};
    cliParser.addArgument(idArg);
    cliParser.addArgument(logArg);
    cliParser.addArgument(configArg);

    //This defaults to true. You could pass parseCli = false to the constructor in case you want to add your own arguments in an inherited node.
    if(parseCli)
    {
        cliParser.parse();
    }

}
ManagedNode::~ManagedNode()
{
    Exit();
}

void ManagedNode::Spin()
{
    if(!isSetup)
        throw std::runtime_error("Node wasn't setup yet");

    rclcpp::WallRate loop_rate(this->loopRate);
    while(rclcpp::ok() && !Abort)
    {
        SpinOnce();
        loop_rate.sleep();
    }
}

void ManagedNode::SpinOnce(std::chrono::nanoseconds timeout )
{
    if(!isSetup)
        throw std::runtime_error("Node wasn't setup yet");
    if(rclcpp::ok() && !Abort)
        executor->spin_once(timeout);
}

bool ManagedNode::Ok() const
{
    //TODO add &&abort ?
    return rclcpp::ok();
}

ComponentManager::SharedPtr ManagedNode::GetComponentManager()
{
    return this->CompManager;
}

rclcpp::node::Node::SharedPtr ManagedNode::GetRosNode()
{
    return this->RosNode;
}

int64_t ManagedNode::GetNodeId()
{
    return this->NodeId;
}

bool ManagedNode::NodeSetupSuccessfull()
{
    return this->isSetup;
}

int ManagedNode::GetLoopRate() const
{
    return loopRate;
}

void ManagedNode::SetLoopRate(int value)
{
    loopRate = value;
}

CLIParser ManagedNode::GetCliParser() const
{
    return cliParser;
}

void ManagedNode::AsyncWorker()
{
    //TODO make loop_rate configurable
    rclcpp::WallRate loop_rate(80);
    while(!Abort)
    {
        DoWork();
        loop_rate.sleep();
    }
}

void ManagedNode::DoWork()
{

}

void ManagedNode::Exit()
{
    //std::cout << "Calling exit" << std::endl;
    Abort = true;
    if(WorkThread)
        WorkThread->join();
    if(SpinThread)
        SpinThread->join();
    //std::cout << "Thread successfully ended" << std::endl;
    rclcpp::shutdown();
    //std::cout << "Exit successfull" << std::endl;
}

void ManagedNode::Start(bool multithreaded)
{
    SpinThread = std::make_shared<std::thread>(std::bind(&ManagedNode::Spin,this));
    if(multithreaded)
        WorkThread = std::make_shared<std::thread>(std::bind(&ManagedNode::AsyncWorker,this));
    this->isSpinningAsync = true;
}
void ManagedNode::Setup()
{
    Setup(LogLevel::Info);

}
void ManagedNode::Setup(LogLevel logLevel, bool no_executor)
{
    uint64_t id = 100;
    if(id_str != "")
    {
        std::cout << id_str << std::endl;
        id = std::stoi(id_str);
    }

    //Create the ros node base on the given node name and the specified id
    RosNode = rclcpp::node::Node::make_shared(nodeName+ std::to_string(id));
    NodeId = id;
    std::cout << "Started node: " << RosNode->get_name() << std::endl;

    this->nodeEntity = std::make_shared<NodeEntity>(NodeId, this->nodeName, RosNode);
    //If you want to implement a hardware node create base entity in derived class
    //Check if rosnode is valid -> should be always the case
    if( !this->RosNode)
        throw std::runtime_error("RosNode may not be null - cant proceed with setup");
    //Add the node to our singlethread executor
    if(!no_executor)
        executor->add_node(RosNode);
    //Init logger
    INIT_LOGGER(RosNode);
    //Set loglevel to given loglevel
    LOGLEVEL(logLevel);
    //If the --logfile argument was successfully parsed, set logfilepath (this will enable logging to a file)
    if(this->LogfilePath != "")
        simpleLogger::getInstance()->setLogFilePath(this->LogfilePath);
    LOG(Info) <<"Build at: "<< BuildInfo::get_build_date() << std::endl;

    //Create Componentmanager with nodeEntity as base
    this->CompManager = std::make_shared<ComponentManager>(this->RosNode,this->nodeEntity);

    //Component manager for a algorithm node: Doesnt need a baseentity
    this->isSetup = true; //Set setup to true
}

}

<commit_msg>passing timeout to spin once<commit_after>/*
 * Copyright 2016 <Lennart Nachtigall> <firesurfer65@yahoo.de>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "ManagedNode.h"
//using namespace std::chrono_literals;
namespace ros2_components {

ManagedNode::ManagedNode(std::string _nodeName, int argc, char *argv[], bool parseCli):cliParser{argv,argc,nodeName}
{

    //Initialise ros2
    rclcpp::init(argc, argv);
    executor = std::make_shared<rclcpp::executors::SingleThreadedExecutor>();

    nodeName = _nodeName;

    //TODO put additional help information into parser

    CLIArgument idArg = {"id","Specify id used for the node", &id_str};
    CLIArgument logArg = {"logpath","Path to the logfile - also enables the logging to a file", &this->LogfilePath};
    CLIArgument configArg = {"configpath","Path to a configfile", &this->ConfigfilePath};
    cliParser.addArgument(idArg);
    cliParser.addArgument(logArg);
    cliParser.addArgument(configArg);

    //This defaults to true. You could pass parseCli = false to the constructor in case you want to add your own arguments in an inherited node.
    if(parseCli)
    {
        cliParser.parse();
    }

}
ManagedNode::~ManagedNode()
{
    Exit();
}

void ManagedNode::Spin()
{
    if(!isSetup)
        throw std::runtime_error("Node wasn't setup yet");

    rclcpp::WallRate loop_rate(this->loopRate);
    while(rclcpp::ok() && !Abort)
    {
        SpinOnce(std::chrono::nanoseconds(100));
        loop_rate.sleep();
    }
}

void ManagedNode::SpinOnce(std::chrono::nanoseconds timeout )
{
    if(!isSetup)
        throw std::runtime_error("Node wasn't setup yet");
    if(rclcpp::ok() && !Abort)
        executor->spin_once(timeout);
}

bool ManagedNode::Ok() const
{
    //TODO add &&abort ?
    return rclcpp::ok();
}

ComponentManager::SharedPtr ManagedNode::GetComponentManager()
{
    return this->CompManager;
}

rclcpp::node::Node::SharedPtr ManagedNode::GetRosNode()
{
    return this->RosNode;
}

int64_t ManagedNode::GetNodeId()
{
    return this->NodeId;
}

bool ManagedNode::NodeSetupSuccessfull()
{
    return this->isSetup;
}

int ManagedNode::GetLoopRate() const
{
    return loopRate;
}

void ManagedNode::SetLoopRate(int value)
{
    loopRate = value;
}

CLIParser ManagedNode::GetCliParser() const
{
    return cliParser;
}

void ManagedNode::AsyncWorker()
{
    //TODO make loop_rate configurable
    rclcpp::WallRate loop_rate(80);
    while(!Abort)
    {
        DoWork();
        loop_rate.sleep();
    }
}

void ManagedNode::DoWork()
{

}

void ManagedNode::Exit()
{
    //std::cout << "Calling exit" << std::endl;
    Abort = true;
    if(WorkThread)
        WorkThread->join();
    if(SpinThread)
        SpinThread->join();
    //std::cout << "Thread successfully ended" << std::endl;
    rclcpp::shutdown();
    //std::cout << "Exit successfull" << std::endl;
}

void ManagedNode::Start(bool multithreaded)
{
    SpinThread = std::make_shared<std::thread>(std::bind(&ManagedNode::Spin,this));
    if(multithreaded)
        WorkThread = std::make_shared<std::thread>(std::bind(&ManagedNode::AsyncWorker,this));
    this->isSpinningAsync = true;
}
void ManagedNode::Setup()
{
    Setup(LogLevel::Info);

}
void ManagedNode::Setup(LogLevel logLevel, bool no_executor)
{
    uint64_t id = 100;
    if(id_str != "")
    {
        std::cout << id_str << std::endl;
        id = std::stoi(id_str);
    }

    //Create the ros node base on the given node name and the specified id
    RosNode = rclcpp::node::Node::make_shared(nodeName+ std::to_string(id));
    NodeId = id;
    std::cout << "Started node: " << RosNode->get_name() << std::endl;

    this->nodeEntity = std::make_shared<NodeEntity>(NodeId, this->nodeName, RosNode);
    //If you want to implement a hardware node create base entity in derived class
    //Check if rosnode is valid -> should be always the case
    if( !this->RosNode)
        throw std::runtime_error("RosNode may not be null - cant proceed with setup");
    //Add the node to our singlethread executor
    if(!no_executor)
        executor->add_node(RosNode);
    //Init logger
    INIT_LOGGER(RosNode);
    //Set loglevel to given loglevel
    LOGLEVEL(logLevel);
    //If the --logfile argument was successfully parsed, set logfilepath (this will enable logging to a file)
    if(this->LogfilePath != "")
        simpleLogger::getInstance()->setLogFilePath(this->LogfilePath);
    LOG(Info) <<"Build at: "<< BuildInfo::get_build_date() << std::endl;

    //Create Componentmanager with nodeEntity as base
    this->CompManager = std::make_shared<ComponentManager>(this->RosNode,this->nodeEntity);

    //Component manager for a algorithm node: Doesnt need a baseentity
    this->isSetup = true; //Set setup to true
}

}

<|endoftext|>


<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "serializer/log/static_header.hpp"

#include "utils.hpp"
#include <boost/bind.hpp>

#include "arch/arch.hpp"
#include "arch/runtime/coroutines.hpp"
#include "config/args.hpp"

bool static_header_check(file_t *file) {
    if (file->get_size() < DEVICE_BLOCK_SIZE) {
        return false;
    } else {
        static_header_t *buffer = reinterpret_cast<static_header_t *>(malloc_aligned(DEVICE_BLOCK_SIZE, DEVICE_BLOCK_SIZE));
        co_read(file, 0, DEVICE_BLOCK_SIZE, buffer, DEFAULT_DISK_ACCOUNT);
        bool equals = memcmp(buffer, SOFTWARE_NAME_STRING, sizeof(SOFTWARE_NAME_STRING)) == 0;
        free(buffer);
        return equals;
    }
}

void co_static_header_write(file_t *file, void *data, size_t data_size) {
    static_header_t *buffer = reinterpret_cast<static_header_t *>(malloc_aligned(DEVICE_BLOCK_SIZE, DEVICE_BLOCK_SIZE));
    rassert(sizeof(static_header_t) + data_size < DEVICE_BLOCK_SIZE);

    file->set_size_at_least(DEVICE_BLOCK_SIZE);

    bzero(buffer, DEVICE_BLOCK_SIZE);

    rassert(sizeof(SOFTWARE_NAME_STRING) < 16);
    memcpy(buffer->software_name, SOFTWARE_NAME_STRING, sizeof(SOFTWARE_NAME_STRING));

    rassert(sizeof(SERIALIZER_VERSION_STRING) < 16);
    memcpy(buffer->version, SERIALIZER_VERSION_STRING, sizeof(SERIALIZER_VERSION_STRING));

    memcpy(buffer->data, data, data_size);

    // We want to follow up the static header write with a datasync, because... it's the
    // most important block in the file!
    co_write(file, 0, DEVICE_BLOCK_SIZE, buffer, DEFAULT_DISK_ACCOUNT, file_t::WRAP_IN_DATASYNCS);

    free(buffer);
}

void co_static_header_write_helper(file_t *file, static_header_write_callback_t *cb, void *data, size_t data_size) {
    co_static_header_write(file, data, data_size);
    cb->on_static_header_write();
}

bool static_header_write(file_t *file, void *data, size_t data_size, static_header_write_callback_t *cb) {
    coro_t::spawn(boost::bind(co_static_header_write_helper, file, cb, data, data_size));
    return false;
}

void co_static_header_read(file_t *file, static_header_read_callback_t *callback, void *data_out, size_t data_size) {
    rassert(sizeof(static_header_t) + data_size < DEVICE_BLOCK_SIZE);
    static_header_t *buffer = reinterpret_cast<static_header_t *>(malloc_aligned(DEVICE_BLOCK_SIZE, DEVICE_BLOCK_SIZE));
    co_read(file, 0, DEVICE_BLOCK_SIZE, buffer, DEFAULT_DISK_ACCOUNT);
    if (memcmp(buffer->software_name, SOFTWARE_NAME_STRING, sizeof(SOFTWARE_NAME_STRING)) != 0) {
        fail_due_to_user_error("This doesn't appear to be a RethinkDB data file.");
    }

    if (memcmp(buffer->version, SERIALIZER_VERSION_STRING, sizeof(SERIALIZER_VERSION_STRING)) != 0) {
        fail_due_to_user_error("File version is incorrect. This file was created with "
                               "RethinkDB's serializer version %s, but you are trying "
                               "to read it with version %s.  See "
                               "http://rethinkdb.com/docs/backup/ for information on "
                               "backing up and restoring data.",
                               buffer->version, SERIALIZER_VERSION_STRING);
    }
    memcpy(data_out, buffer->data, data_size);
    callback->on_static_header_read();
    // TODO: free buffer before you call the callback.
    free(buffer);
}

bool static_header_read(file_t *file, void *data_out, size_t data_size, static_header_read_callback_t *cb) {
    coro_t::spawn(boost::bind(co_static_header_read, file, cb, data_out, data_size));
    return false;
}
<commit_msg>changing wrong serializer version message to be more helpful<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "serializer/log/static_header.hpp"

#include "utils.hpp"
#include <boost/bind.hpp>

#include "arch/arch.hpp"
#include "arch/runtime/coroutines.hpp"
#include "config/args.hpp"

bool static_header_check(file_t *file) {
    if (file->get_size() < DEVICE_BLOCK_SIZE) {
        return false;
    } else {
        static_header_t *buffer = reinterpret_cast<static_header_t *>(malloc_aligned(DEVICE_BLOCK_SIZE, DEVICE_BLOCK_SIZE));
        co_read(file, 0, DEVICE_BLOCK_SIZE, buffer, DEFAULT_DISK_ACCOUNT);
        bool equals = memcmp(buffer, SOFTWARE_NAME_STRING, sizeof(SOFTWARE_NAME_STRING)) == 0;
        free(buffer);
        return equals;
    }
}

void co_static_header_write(file_t *file, void *data, size_t data_size) {
    static_header_t *buffer = reinterpret_cast<static_header_t *>(malloc_aligned(DEVICE_BLOCK_SIZE, DEVICE_BLOCK_SIZE));
    rassert(sizeof(static_header_t) + data_size < DEVICE_BLOCK_SIZE);

    file->set_size_at_least(DEVICE_BLOCK_SIZE);

    bzero(buffer, DEVICE_BLOCK_SIZE);

    rassert(sizeof(SOFTWARE_NAME_STRING) < 16);
    memcpy(buffer->software_name, SOFTWARE_NAME_STRING, sizeof(SOFTWARE_NAME_STRING));

    rassert(sizeof(SERIALIZER_VERSION_STRING) < 16);
    memcpy(buffer->version, SERIALIZER_VERSION_STRING, sizeof(SERIALIZER_VERSION_STRING));

    memcpy(buffer->data, data, data_size);

    // We want to follow up the static header write with a datasync, because... it's the
    // most important block in the file!
    co_write(file, 0, DEVICE_BLOCK_SIZE, buffer, DEFAULT_DISK_ACCOUNT, file_t::WRAP_IN_DATASYNCS);

    free(buffer);
}

void co_static_header_write_helper(file_t *file, static_header_write_callback_t *cb, void *data, size_t data_size) {
    co_static_header_write(file, data, data_size);
    cb->on_static_header_write();
}

bool static_header_write(file_t *file, void *data, size_t data_size, static_header_write_callback_t *cb) {
    coro_t::spawn(boost::bind(co_static_header_write_helper, file, cb, data, data_size));
    return false;
}

void co_static_header_read(file_t *file, static_header_read_callback_t *callback, void *data_out, size_t data_size) {
    rassert(sizeof(static_header_t) + data_size < DEVICE_BLOCK_SIZE);
    static_header_t *buffer = reinterpret_cast<static_header_t *>(malloc_aligned(DEVICE_BLOCK_SIZE, DEVICE_BLOCK_SIZE));
    co_read(file, 0, DEVICE_BLOCK_SIZE, buffer, DEFAULT_DISK_ACCOUNT);
    if (memcmp(buffer->software_name, SOFTWARE_NAME_STRING, sizeof(SOFTWARE_NAME_STRING)) != 0) {
        fail_due_to_user_error("This doesn't appear to be a RethinkDB data file.");
    }

    if (memcmp(buffer->version, SERIALIZER_VERSION_STRING, sizeof(SERIALIZER_VERSION_STRING)) != 0) {
        fail_due_to_user_error("File version is incorrect. This file was created with "
                               "RethinkDB's serializer version %s, but you are trying "
                               "to read it with version %s.  See "
                               "http://rethinkdb.com/docs/migration/ for information on "
                               "migrating data from a previous version.",
                               buffer->version, SERIALIZER_VERSION_STRING);
    }
    memcpy(data_out, buffer->data, data_size);
    callback->on_static_header_read();
    // TODO: free buffer before you call the callback.
    free(buffer);
}

bool static_header_read(file_t *file, void *data_out, size_t data_size, static_header_read_callback_t *cb) {
    coro_t::spawn(boost::bind(co_static_header_read, file, cb, data_out, data_size));
    return false;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Ali Saidi
 */

#ifndef __ARCH_MIPS_STACKTRACE_HH__
#define __ARCH_MIPS_STACKTRACE_HH__

#include "base/trace.hh"
#include "cpu/static_inst.hh"

class ThreadContext;
class StackTrace;

class ProcessInfo
{
  private:
    ThreadContext *tc;

    int thread_info_size;
    int task_struct_size;
    int task_off;
    int pid_off;
    int name_off;

  public:
    ProcessInfo(ThreadContext *_tc);

    Addr task(Addr ksp) const;
    int pid(Addr ksp) const;
    std::string name(Addr ksp) const;
};

class StackTrace
{
  protected:
    typedef TheISA::MachInst MachInst;
  private:
    ThreadContext *tc;
    std::vector<Addr> stack;

  private:
    bool isEntry(Addr addr);
    bool decodePrologue(Addr sp, Addr callpc, Addr func, int &size, Addr &ra);
    bool decodeSave(MachInst inst, int &reg, int &disp);
    bool decodeStack(MachInst inst, int &disp);

    void trace(ThreadContext *tc, bool is_call);

  public:
    StackTrace();
    StackTrace(ThreadContext *tc, StaticInstPtr inst);
    ~StackTrace();

    void clear()
    {
        tc = 0;
        stack.clear();
    }

    bool valid() const { return tc != NULL; }
    bool trace(ThreadContext *tc, StaticInstPtr inst);

  public:
    const std::vector<Addr> &getstack() const { return stack; }

    static const int user = 1;
    static const int console = 2;
    static const int unknown = 3;

#if TRACING_ON
  private:
    void dump();

  public:
    void dprintf() { if (DTRACE(Stack)) dump(); }
#else
  public:
    void dprintf() {}
#endif
};

inline bool
StackTrace::trace(ThreadContext *tc, StaticInstPtr inst)
{
    if (!inst->isCall() && !inst->isReturn())
        return false;

    if (valid())
        clear();

    trace(tc, !inst->isReturn());
    return true;
}

#endif // __ARCH_MIPS_STACKTRACE_HH__
<commit_msg>Put the MIPS stacktrace into the MipsISA namespace to fit with Alpha and SPARC.<commit_after>/*
 * Copyright (c) 2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Ali Saidi
 */

#ifndef __ARCH_MIPS_STACKTRACE_HH__
#define __ARCH_MIPS_STACKTRACE_HH__

#include "base/trace.hh"
#include "cpu/static_inst.hh"

class ThreadContext;
class StackTrace;

namespace MipsISA
{

class ProcessInfo
{
  private:
    ThreadContext *tc;

    int thread_info_size;
    int task_struct_size;
    int task_off;
    int pid_off;
    int name_off;

  public:
    ProcessInfo(ThreadContext *_tc);

    Addr task(Addr ksp) const;
    int pid(Addr ksp) const;
    std::string name(Addr ksp) const;
};

class StackTrace
{
  protected:
    typedef TheISA::MachInst MachInst;
  private:
    ThreadContext *tc;
    std::vector<Addr> stack;

  private:
    bool isEntry(Addr addr);
    bool decodePrologue(Addr sp, Addr callpc, Addr func, int &size, Addr &ra);
    bool decodeSave(MachInst inst, int &reg, int &disp);
    bool decodeStack(MachInst inst, int &disp);

    void trace(ThreadContext *tc, bool is_call);

  public:
    StackTrace();
    StackTrace(ThreadContext *tc, StaticInstPtr inst);
    ~StackTrace();

    void clear()
    {
        tc = 0;
        stack.clear();
    }

    bool valid() const { return tc != NULL; }
    bool trace(ThreadContext *tc, StaticInstPtr inst);

  public:
    const std::vector<Addr> &getstack() const { return stack; }

    static const int user = 1;
    static const int console = 2;
    static const int unknown = 3;

#if TRACING_ON
  private:
    void dump();

  public:
    void dprintf() { if (DTRACE(Stack)) dump(); }
#else
  public:
    void dprintf() {}
#endif
};

inline bool
StackTrace::trace(ThreadContext *tc, StaticInstPtr inst)
{
    if (!inst->isCall() && !inst->isReturn())
        return false;

    if (valid())
        clear();

    trace(tc, !inst->isReturn());
    return true;
}

}

#endif // __ARCH_MIPS_STACKTRACE_HH__
<|endoftext|>


<commit_before>// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// 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 co
// pies 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 al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER 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 "content/nw/src/shell_content_browser_client.h"

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/threading/thread_restrictions.h"
#include "content/public/browser/browser_url_handler.h"
#include "content/public/browser/resource_dispatcher_host.h"
#include "content/nw/src/api/dispatcher_host.h"
#include "content/nw/src/common/shell_switches.h"
#include "content/nw/src/browser/shell_devtools_delegate.h"
#include "content/nw/src/browser/shell_resource_dispatcher_host_delegate.h"
#include "content/nw/src/media/media_internals.h"
#include "content/nw/src/nw_package.h"
#include "content/nw/src/nw_shell.h"
#include "content/nw/src/shell_browser_context.h"
#include "content/nw/src/shell_browser_main_parts.h"
#include "geolocation/shell_access_token_store.h"
#include "googleurl/src/gurl.h"
#include "webkit/glue/webpreferences.h"
#include "ui/base/l10n/l10n_util.h"

namespace content {

ShellContentBrowserClient::ShellContentBrowserClient()
    : shell_browser_main_parts_(NULL) {
}

ShellContentBrowserClient::~ShellContentBrowserClient() {
}

BrowserMainParts* ShellContentBrowserClient::CreateBrowserMainParts(
    const MainFunctionParams& parameters) {
  shell_browser_main_parts_ = new ShellBrowserMainParts(parameters);
  return shell_browser_main_parts_;
}

void ShellContentBrowserClient::RenderViewHostCreated(
    RenderViewHost* render_view_host) {
  new api::DispatcherHost(render_view_host);
}

std::string ShellContentBrowserClient::GetApplicationLocale() {
  return l10n_util::GetApplicationLocale("en-US");
}

void ShellContentBrowserClient::AppendExtraCommandLineSwitches(
    CommandLine* command_line,
    int child_process_id) {
  nw::Package* package = shell_browser_main_parts()->package();
  if (package && package->GetUseNode()) {
    // Allow node.js
    command_line->AppendSwitch(switches::kmNodejs);

    // Set cwd
    command_line->AppendSwitchPath(switches::kWorkingDirectory,
                                   package->path());
  }
}

void ShellContentBrowserClient::ResourceDispatcherHostCreated() {
  resource_dispatcher_host_delegate_.reset(
      new ShellResourceDispatcherHostDelegate());
  ResourceDispatcherHost::Get()->SetDelegate(
      resource_dispatcher_host_delegate_.get());
}

std::string ShellContentBrowserClient::GetDefaultDownloadName() {
  return "download";
}

MediaObserver* ShellContentBrowserClient::GetMediaObserver() {
  return MediaInternals::GetInstance();
}

void ShellContentBrowserClient::BrowserURLHandlerCreated(
    BrowserURLHandler* handler) {
}

ShellBrowserContext* ShellContentBrowserClient::browser_context() {
  return shell_browser_main_parts_->browser_context();
}

ShellBrowserContext*
    ShellContentBrowserClient::off_the_record_browser_context() {
  return shell_browser_main_parts_->off_the_record_browser_context();
}

AccessTokenStore* ShellContentBrowserClient::CreateAccessTokenStore() {
  return new ShellAccessTokenStore(browser_context()->GetRequestContext());
}

void ShellContentBrowserClient::OverrideWebkitPrefs(
      RenderViewHost* render_view_host,
      const GURL& url,
      webkit_glue::WebPreferences* prefs) {
  nw::Package* package = shell_browser_main_parts()->package();

  // Disable web security.
  prefs->dom_paste_enabled = true;
  prefs->javascript_can_access_clipboard = true;
  prefs->web_security_enabled = false;
  prefs->allow_file_access_from_file_urls = true;

  // Disable plugins and cache by default.
  prefs->plugins_enabled = false;
  prefs->java_enabled = false;
  prefs->uses_page_cache = false;

  base::DictionaryValue* webkit;
  if (package->root()->GetDictionary(switches::kmWebkit, &webkit)) {
    webkit->GetBoolean(switches::kmJava, &prefs->java_enabled);
    webkit->GetBoolean(switches::kmPlugin, &prefs->plugins_enabled);
    webkit->GetBoolean(switches::kmPageCache, &prefs->uses_page_cache);
  }
}

}  // namespace content
<commit_msg>Enable experimental WebKit features. Fix #105.<commit_after>// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// 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 co
// pies 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 al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER 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 "content/nw/src/shell_content_browser_client.h"

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/threading/thread_restrictions.h"
#include "content/public/browser/browser_url_handler.h"
#include "content/public/browser/resource_dispatcher_host.h"
#include "content/nw/src/api/dispatcher_host.h"
#include "content/nw/src/common/shell_switches.h"
#include "content/nw/src/browser/shell_devtools_delegate.h"
#include "content/nw/src/browser/shell_resource_dispatcher_host_delegate.h"
#include "content/nw/src/media/media_internals.h"
#include "content/nw/src/nw_package.h"
#include "content/nw/src/nw_shell.h"
#include "content/nw/src/shell_browser_context.h"
#include "content/nw/src/shell_browser_main_parts.h"
#include "geolocation/shell_access_token_store.h"
#include "googleurl/src/gurl.h"
#include "webkit/glue/webpreferences.h"
#include "ui/base/l10n/l10n_util.h"

namespace content {

ShellContentBrowserClient::ShellContentBrowserClient()
    : shell_browser_main_parts_(NULL) {
}

ShellContentBrowserClient::~ShellContentBrowserClient() {
}

BrowserMainParts* ShellContentBrowserClient::CreateBrowserMainParts(
    const MainFunctionParams& parameters) {
  shell_browser_main_parts_ = new ShellBrowserMainParts(parameters);
  return shell_browser_main_parts_;
}

void ShellContentBrowserClient::RenderViewHostCreated(
    RenderViewHost* render_view_host) {
  new api::DispatcherHost(render_view_host);
}

std::string ShellContentBrowserClient::GetApplicationLocale() {
  return l10n_util::GetApplicationLocale("en-US");
}

void ShellContentBrowserClient::AppendExtraCommandLineSwitches(
    CommandLine* command_line,
    int child_process_id) {
  nw::Package* package = shell_browser_main_parts()->package();
  if (package && package->GetUseNode()) {
    // Allow node.js
    command_line->AppendSwitch(switches::kmNodejs);

    // Set cwd
    command_line->AppendSwitchPath(switches::kWorkingDirectory,
                                   package->path());
  }
}

void ShellContentBrowserClient::ResourceDispatcherHostCreated() {
  resource_dispatcher_host_delegate_.reset(
      new ShellResourceDispatcherHostDelegate());
  ResourceDispatcherHost::Get()->SetDelegate(
      resource_dispatcher_host_delegate_.get());
}

std::string ShellContentBrowserClient::GetDefaultDownloadName() {
  return "download";
}

MediaObserver* ShellContentBrowserClient::GetMediaObserver() {
  return MediaInternals::GetInstance();
}

void ShellContentBrowserClient::BrowserURLHandlerCreated(
    BrowserURLHandler* handler) {
}

ShellBrowserContext* ShellContentBrowserClient::browser_context() {
  return shell_browser_main_parts_->browser_context();
}

ShellBrowserContext*
    ShellContentBrowserClient::off_the_record_browser_context() {
  return shell_browser_main_parts_->off_the_record_browser_context();
}

AccessTokenStore* ShellContentBrowserClient::CreateAccessTokenStore() {
  return new ShellAccessTokenStore(browser_context()->GetRequestContext());
}

void ShellContentBrowserClient::OverrideWebkitPrefs(
      RenderViewHost* render_view_host,
      const GURL& url,
      webkit_glue::WebPreferences* prefs) {
  nw::Package* package = shell_browser_main_parts()->package();

  // Disable web security.
  prefs->dom_paste_enabled = true;
  prefs->javascript_can_access_clipboard = true;
  prefs->web_security_enabled = false;
  prefs->allow_file_access_from_file_urls = true;

  // Open experimental features.
  prefs->css_sticky_position_enabled = true;
  prefs->css_regions_enabled = true;
  prefs->css_shaders_enabled = true;
  prefs->css_variables_enabled = true;

  // Disable plugins and cache by default.
  prefs->plugins_enabled = false;
  prefs->java_enabled = false;
  prefs->uses_page_cache = false;

  base::DictionaryValue* webkit;
  if (package->root()->GetDictionary(switches::kmWebkit, &webkit)) {
    webkit->GetBoolean(switches::kmJava, &prefs->java_enabled);
    webkit->GetBoolean(switches::kmPlugin, &prefs->plugins_enabled);
    webkit->GetBoolean(switches::kmPageCache, &prefs->uses_page_cache);
  }
}

}  // namespace content
<|endoftext|>


<commit_before>#include <QDebug>
#include <QTimer>
#include <DuiApplicationWindow>

#include "shutdowndialogbusinesslogic.h"
#include <qmsystem/qmsystemstate.h>
#include <qmsystem/qmled.h>

const int SHUTDOWN_TIME = 8000/*ms*/;
const int UPDATE_INTERVAL = 50;/*ms*/
const int IDLE_TIME = 10000/*ms*/;
const int SLIDER_RANGE = 1000;

using namespace Maemo;

ShutdownDialogBusinessLogic::ShutdownDialogBusinessLogic(DuiApplicationWindow& window) : QObject(), win(window)
{
    shutdownDlg = NULL;
    shuttingDown = false;
    powerKeyPressTimer = NULL;
    idleTimer = NULL;
    currentPosInTime = 0;
    currentPos = 0;
}
ShutdownDialogBusinessLogic::~ShutdownDialogBusinessLogic()
{
    if (shutdownDlg)
        shutdownDlg->deleteLater();
    shutdownDlg = NULL;
}

void ShutdownDialogBusinessLogic::openDialog(bool btnDown)
{
    qDebug() << "openDialog";
    if (shutdownDlg != NULL || shuttingDown) {
        qDebug() << "won't open";
        return;
    }
    emit dialogOpen(true);

    win.show();

    shutdownDlg = new ShutdownDialog(QString("Shutdown dialog"), QString("next alarm event"), DuiDialog::NoButton, SLIDER_RANGE);
    connect(shutdownDlg->slider(), SIGNAL(unlocked()), this, SLOT(shutdown()));
    connect(shutdownDlg->slider(), SIGNAL(valueChanged()), this, SLOT(resetIdleTimer()));

    if(btnDown)
        startPowerKeyPressTimer();

    resetIdleTimer();

    /* shutdownDlg->setSystemModal(); NOT YET IMPLEMENTED */
    shutdownDlg->exec();

}

void ShutdownDialogBusinessLogic::closeDialog()
{
    /* Here we should turn off the device instead of just deleting the dialog */
    qDebug() << "closeDialog()";
    stopPowerKeyPressTimer();
    stopIdleTimer();
    shutdownDlg->reject();
    shutdownDlg->deleteLater();
    shutdownDlg = NULL;
    win.hide();
    emit dialogOpen(false);
}

void ShutdownDialogBusinessLogic::powerKeyDown()
{
    qDebug() << "powerKeyDown()";
    if(shuttingDown)
        return;

    if(powerKeyPressTimer == NULL)
        startPowerKeyPressTimer();
    if(shutdownDlg != NULL)
        if(shutdownDlg->slider() != NULL)
            shutdownDlg->slider()->hwKeyDown(true);
}

void ShutdownDialogBusinessLogic::powerKeyUp()
{
    qDebug() << "powerKeyUp()";
    if(shuttingDown)
        return;

    stopPowerKeyPressTimer();
    if(shutdownDlg != NULL)
        if(shutdownDlg->slider() != NULL)
            shutdownDlg->slider()->hwKeyDown(false);
}

void ShutdownDialogBusinessLogic::startPowerKeyPressTimer()
{
    qDebug() << "startPowerKeyPressTimer()";
    t.start();

    if(shutdownDlg != NULL) {
        if(shutdownDlg->slider() != NULL) {
            currentPosInTime = (int)(SHUTDOWN_TIME * (double)(shutdownDlg->slider()->value()/(double)SLIDER_RANGE));
            currentPos = shutdownDlg->slider()->value();
        }
    }

    if(powerKeyPressTimer == NULL) {
        powerKeyPressTimer = new QTimer(this);
        powerKeyPressTimer->setInterval(UPDATE_INTERVAL);
        connect(powerKeyPressTimer, SIGNAL(timeout()), this, SLOT(updateSlider()));
        powerKeyPressTimer->start();
    }
}

void ShutdownDialogBusinessLogic::stopPowerKeyPressTimer()
{
    if(powerKeyPressTimer != NULL) {
        powerKeyPressTimer->stop();
        powerKeyPressTimer->deleteLater();
        powerKeyPressTimer = NULL;
    }
}

void ShutdownDialogBusinessLogic::stopIdleTimer()
{
    qDebug() << "stopIdleTimer()";
    if(idleTimer != NULL) {
        idleTimer->stop();
        idleTimer->deleteLater();
        idleTimer = NULL;
    }
}

void ShutdownDialogBusinessLogic::resetIdleTimer()
{
    if(shuttingDown)
        return;

    if(idleTimer == NULL) {
        idleTimer = new QTimer(this);
        connect(idleTimer, SIGNAL(timeout()), this, SLOT(closeDialog()));
    }
    idleTimer->start(IDLE_TIME);
}

void ShutdownDialogBusinessLogic::updateSlider()
{
    qDebug() << "updateSlider";
    if(shutdownDlg != NULL) {
        if(shutdownDlg->slider() != NULL) {
            shutdownDlg->slider()->updateValue(
                    (double)(t.elapsed()/(double)(SHUTDOWN_TIME-currentPosInTime)) * (SLIDER_RANGE - currentPos) + currentPos
                    );
        }
    }

    /* Note: We cannot just use the powerKeyPressTimer and check when it reaches the SHUTDOWN_TIME.
       Updating the slider takes time so that the powerKeyPressTimer reaches the SHUTDOWN_TIME way too
       late. Instead we use separate QTime t to define the actual SHUTDOWN_TIME. */
}

void ShutdownDialogBusinessLogic::shutdown()
{
    qDebug() << "shutdown()";
    stopPowerKeyPressTimer();
    stopIdleTimer();
    shuttingDown = true;
    if(shutdownDlg != NULL)
        if(shutdownDlg->slider() != NULL)
            shutdownDlg->slider()->setEnabled(false);

    QmLED led;
    led.activate(QString("PatternShutDown"));

    QmSystemState state;
    state.set(QmSystemState::Shutdown);
}
<commit_msg>minor fix<commit_after>#include <QDebug>
#include <QTimer>
#include <DuiApplicationWindow>

#include "shutdowndialogbusinesslogic.h"
#include <qmsystem/qmsystemstate.h>
#include <qmsystem/qmled.h>

const int SHUTDOWN_TIME = 8000/*ms*/;
const int UPDATE_INTERVAL = 50;/*ms*/
const int IDLE_TIME = 10000/*ms*/;
const int SLIDER_RANGE = 1000;

using namespace Maemo;

ShutdownDialogBusinessLogic::ShutdownDialogBusinessLogic(DuiApplicationWindow& window) : QObject(), win(window)
{
    shutdownDlg = NULL;
    shuttingDown = false;
    powerKeyPressTimer = NULL;
    idleTimer = NULL;
    currentPosInTime = 0;
    currentPos = 0;
}
ShutdownDialogBusinessLogic::~ShutdownDialogBusinessLogic()
{
    if (shutdownDlg)
        shutdownDlg->deleteLater();
    shutdownDlg = NULL;
}

void ShutdownDialogBusinessLogic::openDialog(bool btnDown)
{
    qDebug() << "openDialog";
    if (shutdownDlg != NULL || shuttingDown) {
        qDebug() << "won't open";
        return;
    }
    emit dialogOpen(true);

    win.show();

    shutdownDlg = new ShutdownDialog(QString("Shutdown dialog"), QString("next alarm event"), DuiDialog::NoButton, SLIDER_RANGE);
    connect(shutdownDlg->slider(), SIGNAL(unlocked()), this, SLOT(shutdown()));
    connect(shutdownDlg->slider(), SIGNAL(valueChanged()), this, SLOT(resetIdleTimer()));

    if(btnDown)
        startPowerKeyPressTimer();

    resetIdleTimer();

    /* shutdownDlg->setSystemModal(); NOT YET IMPLEMENTED */
    shutdownDlg->exec();

}

void ShutdownDialogBusinessLogic::closeDialog()
{
    /* Here we should turn off the device instead of just deleting the dialog */
    qDebug() << "closeDialog()";
    stopPowerKeyPressTimer();
    stopIdleTimer();
    shutdownDlg->reject();
    shutdownDlg->deleteLater();
    shutdownDlg = NULL;
    win.hide();
    emit dialogOpen(false);
}

void ShutdownDialogBusinessLogic::powerKeyDown()
{
    qDebug() << "powerKeyDown()";
    if(shuttingDown)
        return;

    if(powerKeyPressTimer == NULL)
        startPowerKeyPressTimer();
    if(shutdownDlg != NULL)
        if(shutdownDlg->slider() != NULL)
            shutdownDlg->slider()->hwKeyDown(true);
}

void ShutdownDialogBusinessLogic::powerKeyUp()
{
    qDebug() << "powerKeyUp()";
    if(shuttingDown)
        return;

    stopPowerKeyPressTimer();
    if(shutdownDlg != NULL)
        if(shutdownDlg->slider() != NULL)
            shutdownDlg->slider()->hwKeyDown(false);
}

void ShutdownDialogBusinessLogic::startPowerKeyPressTimer()
{
    qDebug() << "startPowerKeyPressTimer()";
    t.start();

    if(shutdownDlg != NULL) {
        if(shutdownDlg->slider() != NULL) {
            currentPosInTime = (int)(SHUTDOWN_TIME * (double)(shutdownDlg->slider()->value()/(double)SLIDER_RANGE));
            currentPos = shutdownDlg->slider()->value();
        }
    }

    if(powerKeyPressTimer == NULL) {
        powerKeyPressTimer = new QTimer(this);
        powerKeyPressTimer->setInterval(UPDATE_INTERVAL);
        connect(powerKeyPressTimer, SIGNAL(timeout()), this, SLOT(updateSlider()));
        powerKeyPressTimer->start();
    }
}

void ShutdownDialogBusinessLogic::stopPowerKeyPressTimer()
{
    if(powerKeyPressTimer != NULL) {
        powerKeyPressTimer->stop();
        powerKeyPressTimer->deleteLater();
        powerKeyPressTimer = NULL;
    }
}

void ShutdownDialogBusinessLogic::stopIdleTimer()
{
    qDebug() << "stopIdleTimer()";
    if(idleTimer != NULL) {
        idleTimer->stop();
        idleTimer->deleteLater();
        idleTimer = NULL;
    }
}

void ShutdownDialogBusinessLogic::resetIdleTimer()
{
    if(shuttingDown)
        return;

    if(idleTimer == NULL) {
        idleTimer = new QTimer(this);
        connect(idleTimer, SIGNAL(timeout()), this, SLOT(closeDialog()));
    }
    idleTimer->start(IDLE_TIME);
}

void ShutdownDialogBusinessLogic::updateSlider()
{
    qDebug() << "updateSlider";
    if(shutdownDlg != NULL) {
        if(shutdownDlg->slider() != NULL) {
            shutdownDlg->slider()->updateValue(
                    (double)(t.elapsed()/(double)(SHUTDOWN_TIME-currentPosInTime)) * (SLIDER_RANGE - currentPos) + currentPos
                    );
        }
    }

    /* Note: We cannot just use the powerKeyPressTimer and check when it reaches the SHUTDOWN_TIME.
       Updating the slider takes time so that the powerKeyPressTimer reaches the SHUTDOWN_TIME way too
       late. Instead we use separate QTime t to define the actual SHUTDOWN_TIME. */
}

void ShutdownDialogBusinessLogic::shutdown()
{
    qDebug() << "shutdown()";
    stopPowerKeyPressTimer();
    stopIdleTimer();
    shuttingDown = true;
    if(shutdownDlg != NULL) {
        if(shutdownDlg->slider() != NULL) {
            shutdownDlg->slider()->setEnabled(false);
            shutdownDlg->slider()->pressed();
        }
    }

    QmLED led;
    led.activate(QString("PatternShutDown"));

    QmSystemState state;
    state.set(QmSystemState::Shutdown);
}
<|endoftext|>