<commit_before>// From vmdconio.h
#define VMDCON_WARN      2
#define VMDCON_ERROR     3

extern "C" {
    #include <vmdplugin.h>
    #include <molfile_plugin.h>
}

#include <cassert>
#include <array>
#include <string>
#include <vector>
#include <unordered_map>

#include "chemfiles/File.hpp"
#include "chemfiles/Format.hpp"
#include "chemfiles/Atom.hpp"
#include "chemfiles/Frame.hpp"
#include "chemfiles/Residue.hpp"
#include "chemfiles/Topology.hpp"

#include "chemfiles/types.hpp"
#include "chemfiles/warnings.hpp"
#include "chemfiles/error_fmt.hpp"
#include "chemfiles/external/span.hpp"
#include "chemfiles/external/optional.hpp"

#include "chemfiles/formats/Molfile.hpp"

using namespace chemfiles;

/******************************************************************************/
#define PLUGINS_DATA(FORMAT, PLUGIN, READER, VELOCITIES)                       \
    extern "C" int PLUGIN##_register(void*, vmdplugin_register_cb); /*NOLINT*/ \
    extern "C" int PLUGIN##_fini(void); /*NOLINT*/                             \
    extern "C" int PLUGIN##_init(void); /*NOLINT*/                             \
    template <> struct MolfilePluginData<FORMAT> {                             \
        int init() { return PLUGIN##_init(); }                                 \
        int registration(void* data, vmdplugin_register_cb callback) {         \
            return PLUGIN##_register(data, callback);                          \
        }                                                                      \
        int fini() { return PLUGIN##_fini(); }                                 \
        std::string format() const {return #FORMAT;}                           \
        std::string plugin_name() const {return #PLUGIN;}                      \
        std::string reader() const {return #READER;}                           \
        bool have_velocities() const {return VELOCITIES;}                     \
    }

namespace chemfiles {
    PLUGINS_DATA(DCD,               dcdplugin,          dcd,            false);
    PLUGINS_DATA(TRJ,               gromacsplugin,      trj,            false);
    PLUGINS_DATA(LAMMPS,            lammpsplugin,       lammpstrj,      true);
    PLUGINS_DATA(MOLDEN,            moldenplugin,       molden,         false);
}

#undef PLUGINS_FUNCTIONS
/******************************************************************************/

template <MolfileFormat F> static int register_plugin(void* user_data, vmdplugin_t* vmd_plugin) {
    auto user_plugin = static_cast<molfile_plugin_t**>(user_data);
    assert(std::string(MOLFILE_PLUGIN_TYPE) == std::string(vmd_plugin->type));

    auto plugin = reinterpret_cast<molfile_plugin_t*>(vmd_plugin);
    // When this callback is called multiple times with more than one plugin,
    // only register the one whe want
    if (MolfilePluginData<F>().reader() == plugin->name) {
        *user_plugin = plugin;
    }

    return VMDPLUGIN_SUCCESS;
}

static int molfiles_to_chemfiles_warning(int level, const char* message) {
    if (level == VMDCON_ERROR || level == VMDCON_WARN) {
        send_warning(message);
    }
    return 0;
}

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

template <MolfileFormat F>
Molfile<F>::Molfile(std::string path, File::Mode mode, File::Compression compression)
    : path_(std::move(path)), plugin_handle_(nullptr), data_(nullptr), natoms_(0) {
    if (mode != File::READ) {
        throw format_error(
            "molfiles based format {} is only available in read mode", plugin_data_.format()
        );
    }

    if (compression != File::DEFAULT) {
        throw format_error(
            "molfiles based format {} do not support compression", plugin_data_.format()
        );
    }

    if (plugin_data_.init()) {
        throw format_error(
            "could not initialize the {} plugin", plugin_data_.format()
        );
    }

    if (plugin_data_.registration(&plugin_handle_, register_plugin<F>)) {
        throw format_error(
            "could not register the {} plugin", plugin_data_.format()
        );
    }

    // Check the ABI version of the plugin
    assert(plugin_handle_->abiversion == vmdplugin_ABIVERSION);
    // Redirect console output to chemfiles warnings
    plugin_handle_->cons_fputs = molfiles_to_chemfiles_warning;

    // Check that needed functions are here
    if (plugin_handle_->open_file_read == nullptr ||
        (plugin_handle_->read_next_timestep == nullptr && plugin_handle_->read_timestep == nullptr ) ||
        (plugin_handle_->close_file_read == nullptr )) {
        throw format_error(
            "the {} plugin does not have read capacities", plugin_data_.format()
        );
    }

    data_ = plugin_handle_->open_file_read(
        path_.c_str(), plugin_handle_->name, &natoms_
    );

    if (data_ == nullptr) {
        throw format_error(
            "could not open the file at '{}' with {} plugin", path_, plugin_data_.format()
        );
    }

    read_topology();
}

template <MolfileFormat F> Molfile<F>::~Molfile() {
    if (data_) {
        plugin_handle_->close_file_read(data_);
    }
    plugin_data_.fini();
}

template <MolfileFormat F> int Molfile<F>::read_next_timestep(molfile_timestep_t* timestep) {
    if (plugin_handle_->read_next_timestep != nullptr) {
        // This function is provided by classical molecular simulation format.
        return plugin_handle_->read_next_timestep(data_, natoms_, timestep);
    } else if (plugin_handle_->read_timestep != nullptr) {
        // This function is provided by quantum molecular simulation format.
        return plugin_handle_->read_timestep(
            data_, natoms_, timestep, nullptr, nullptr
        );
    } else {
        throw format_error(
            "both read_next_timestep and read_timestep are missing in this "
            "plugin. This is a bug"
        );
    }
}

template <MolfileFormat F> void Molfile<F>::read(Frame& frame) {
    std::vector<float> coords(3 * static_cast<size_t>(natoms_));
    std::vector<float> velocities(0);

    molfile_timestep_t timestep{nullptr, nullptr, 0, 0, 0, 0, 0, 0, 0};
    timestep.coords = coords.data();
    if (plugin_data_.have_velocities()) {
        velocities.resize(3 * static_cast<size_t>(natoms_));
        timestep.velocities = velocities.data();
    }

    int status = read_next_timestep(&timestep);
    if (status != MOLFILE_SUCCESS) {
        throw format_error(
            "error while reading the file at '{}' with {} plugin",
            path_, plugin_data_.format()
        );
    }

    if (topology_) {
        frame.resize(topology_->size());
        frame.set_topology(*topology_);
    }
    molfile_to_frame(timestep, frame);

    frames_.emplace_back(std::move(frame.clone()));
}

template <MolfileFormat F> void Molfile<F>::read_step(size_t step, Frame& frame) {
    while (step >= frames_.size()) {
        Frame new_frame;
        this->read(new_frame);
    }
    frame = frames_.at(step).clone();
}

template <MolfileFormat F> size_t Molfile<F>::nsteps() {
    if (plugin_handle_->read_next_timestep == nullptr) {
        // FIXME: this is hacky, but the molden plugin does not respect a NULL
        // argument for molfile_timestep_t, so for now we are only able to read
        // a sinle step from all the QM format plugins.
        return 1;
    }
    size_t n = 0;
    int status = MOLFILE_SUCCESS;
    while (true) {
        status = read_next_timestep(nullptr);
        if (status == MOLFILE_SUCCESS) {
            n++;
        } else {
            break;
        }
    }
    // We need to close and re-open the file
    plugin_handle_->close_file_read(data_);
    int unused = 0;
    data_ = plugin_handle_->open_file_read(path_.c_str(), plugin_handle_->name, &unused);
    read_topology();

    return n;
}

template <MolfileFormat F>
void Molfile<F>::molfile_to_frame(const molfile_timestep_t& timestep,
                                  Frame& frame) {
    frame.set_cell({
        static_cast<double>(timestep.A),
        static_cast<double>(timestep.B),
        static_cast<double>(timestep.C),
        static_cast<double>(timestep.alpha),
        static_cast<double>(timestep.beta),
        static_cast<double>(timestep.gamma)
    });

    frame.resize(static_cast<size_t>(natoms_));
    auto positions = frame.positions();
    for (size_t i = 0; i < static_cast<size_t>(natoms_); i++) {
        positions[i][0] = static_cast<double>(timestep.coords[3 * i + 0]);
        positions[i][1] = static_cast<double>(timestep.coords[3 * i + 1]);
        positions[i][2] = static_cast<double>(timestep.coords[3 * i + 2]);
    }

    if (plugin_data_.have_velocities()) {
        frame.add_velocities();
        auto velocities = frame.velocities();
        for (size_t i = 0; i < static_cast<size_t>(natoms_); i++) {
            (*velocities)[i][0] = static_cast<double>(timestep.velocities[3 * i + 0]);
            (*velocities)[i][1] = static_cast<double>(timestep.velocities[3 * i + 1]);
            (*velocities)[i][2] = static_cast<double>(timestep.velocities[3 * i + 2]);
        }
    }
}

template <MolfileFormat F> void Molfile<F>::read_topology() {
    if (plugin_handle_->read_structure == nullptr) {
        return;
    }

    std::vector<molfile_atom_t> atoms(static_cast<size_t>(natoms_));
    int optflags = 0;
    int status = plugin_handle_->read_structure(data_, &optflags, atoms.data());
    if (status != MOLFILE_SUCCESS) {
        throw format_error(
            "could not read the molecule structure with {} plugin",
            plugin_data_.format()
        );
    }

    topology_ = Topology();

    auto residues = std::unordered_map<int64_t, Residue>();
    size_t atom_id = 0;
    for (auto& molfile_atom : atoms) {
        Atom atom(molfile_atom.name, molfile_atom.type);
        if ((optflags & MOLFILE_MASS) != 0) {
            atom.set_mass(static_cast<double>(molfile_atom.mass));
        }
        if ((optflags & MOLFILE_CHARGE) != 0) {
            atom.set_charge(static_cast<double>(molfile_atom.charge));
        }

        topology_->add_atom(std::move(atom));

        if (molfile_atom.resname != std::string("")) {
            auto resid = static_cast<int64_t>(molfile_atom.resid);
            auto residue = Residue(molfile_atom.resname, resid);
            auto inserted = residues.insert({resid, std::move(residue)});
            inserted.first->second.add_atom(atom_id);
        }
        atom_id++;
    }

    if (plugin_handle_->read_bonds == nullptr) {
        return;
    }

    int nbonds = 0;
    int* from = nullptr;
    int* to = nullptr;

    int dummy = 0;
    float* _float = nullptr;
    int* _int = nullptr;
    char** _char = nullptr;

    status = plugin_handle_->read_bonds(
        data_, &nbonds, &from, &to, &_float, &_int, &dummy, &_char
    );
    if (status != MOLFILE_SUCCESS) {
        throw format_error(
            "could not read bonds with {} plugin", plugin_data_.format()
        );
    }

    for (size_t i = 0; i < static_cast<size_t>(nbonds); i++) {
        // Indexes are 1-based in Molfile
        topology_->add_bond(static_cast<size_t>(from[i] - 1),
                            static_cast<size_t>(to[i]) - 1);
    }
}

// Instanciate all the templates
template class chemfiles::Molfile<DCD>;
template class chemfiles::Molfile<TRJ>;
template class chemfiles::Molfile<LAMMPS>;
template class chemfiles::Molfile<MOLDEN>;

template<> FormatInfo chemfiles::format_information<Molfile<DCD>>() {
    return FormatInfo("DCD").with_extension(".dcd").description(
        "DCD binary format"
    );
}

template<> FormatInfo chemfiles::format_information<Molfile<TRJ>>() {
    return FormatInfo("TRJ").with_extension(".trj").description(
        "GROMACS .trj binary format"
    );
}

template<> FormatInfo chemfiles::format_information<Molfile<LAMMPS>>() {
    return FormatInfo("LAMMPS").with_extension(".lammpstrj").description(
        "LAMMPS text trajectory format"
    );
}

template<> FormatInfo chemfiles::format_information<Molfile<MOLDEN>>() {
    return FormatInfo("Molden").with_extension(".molden").description(
        "Molden text format"
    );
}
<commit_msg>Do not std::move temporary object<commit_after>// From vmdconio.h
#define VMDCON_WARN      2
#define VMDCON_ERROR     3

extern "C" {
    #include <vmdplugin.h>
    #include <molfile_plugin.h>
}

#include <cassert>
#include <array>
#include <string>
#include <vector>
#include <unordered_map>

#include "chemfiles/File.hpp"
#include "chemfiles/Format.hpp"
#include "chemfiles/Atom.hpp"
#include "chemfiles/Frame.hpp"
#include "chemfiles/Residue.hpp"
#include "chemfiles/Topology.hpp"

#include "chemfiles/types.hpp"
#include "chemfiles/warnings.hpp"
#include "chemfiles/error_fmt.hpp"
#include "chemfiles/external/span.hpp"
#include "chemfiles/external/optional.hpp"

#include "chemfiles/formats/Molfile.hpp"

using namespace chemfiles;

/******************************************************************************/
#define PLUGINS_DATA(FORMAT, PLUGIN, READER, VELOCITIES)                       \
    extern "C" int PLUGIN##_register(void*, vmdplugin_register_cb); /*NOLINT*/ \
    extern "C" int PLUGIN##_fini(void); /*NOLINT*/                             \
    extern "C" int PLUGIN##_init(void); /*NOLINT*/                             \
    template <> struct MolfilePluginData<FORMAT> {                             \
        int init() { return PLUGIN##_init(); }                                 \
        int registration(void* data, vmdplugin_register_cb callback) {         \
            return PLUGIN##_register(data, callback);                          \
        }                                                                      \
        int fini() { return PLUGIN##_fini(); }                                 \
        std::string format() const {return #FORMAT;}                           \
        std::string plugin_name() const {return #PLUGIN;}                      \
        std::string reader() const {return #READER;}                           \
        bool have_velocities() const {return VELOCITIES;}                     \
    }

namespace chemfiles {
    PLUGINS_DATA(DCD,               dcdplugin,          dcd,            false);
    PLUGINS_DATA(TRJ,               gromacsplugin,      trj,            false);
    PLUGINS_DATA(LAMMPS,            lammpsplugin,       lammpstrj,      true);
    PLUGINS_DATA(MOLDEN,            moldenplugin,       molden,         false);
}

#undef PLUGINS_FUNCTIONS
/******************************************************************************/

template <MolfileFormat F> static int register_plugin(void* user_data, vmdplugin_t* vmd_plugin) {
    auto user_plugin = static_cast<molfile_plugin_t**>(user_data);
    assert(std::string(MOLFILE_PLUGIN_TYPE) == std::string(vmd_plugin->type));

    auto plugin = reinterpret_cast<molfile_plugin_t*>(vmd_plugin);
    // When this callback is called multiple times with more than one plugin,
    // only register the one whe want
    if (MolfilePluginData<F>().reader() == plugin->name) {
        *user_plugin = plugin;
    }

    return VMDPLUGIN_SUCCESS;
}

static int molfiles_to_chemfiles_warning(int level, const char* message) {
    if (level == VMDCON_ERROR || level == VMDCON_WARN) {
        send_warning(message);
    }
    return 0;
}

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

template <MolfileFormat F>
Molfile<F>::Molfile(std::string path, File::Mode mode, File::Compression compression)
    : path_(std::move(path)), plugin_handle_(nullptr), data_(nullptr), natoms_(0) {
    if (mode != File::READ) {
        throw format_error(
            "molfiles based format {} is only available in read mode", plugin_data_.format()
        );
    }

    if (compression != File::DEFAULT) {
        throw format_error(
            "molfiles based format {} do not support compression", plugin_data_.format()
        );
    }

    if (plugin_data_.init()) {
        throw format_error(
            "could not initialize the {} plugin", plugin_data_.format()
        );
    }

    if (plugin_data_.registration(&plugin_handle_, register_plugin<F>)) {
        throw format_error(
            "could not register the {} plugin", plugin_data_.format()
        );
    }

    // Check the ABI version of the plugin
    assert(plugin_handle_->abiversion == vmdplugin_ABIVERSION);
    // Redirect console output to chemfiles warnings
    plugin_handle_->cons_fputs = molfiles_to_chemfiles_warning;

    // Check that needed functions are here
    if (plugin_handle_->open_file_read == nullptr ||
        (plugin_handle_->read_next_timestep == nullptr && plugin_handle_->read_timestep == nullptr ) ||
        (plugin_handle_->close_file_read == nullptr )) {
        throw format_error(
            "the {} plugin does not have read capacities", plugin_data_.format()
        );
    }

    data_ = plugin_handle_->open_file_read(
        path_.c_str(), plugin_handle_->name, &natoms_
    );

    if (data_ == nullptr) {
        throw format_error(
            "could not open the file at '{}' with {} plugin", path_, plugin_data_.format()
        );
    }

    read_topology();
}

template <MolfileFormat F> Molfile<F>::~Molfile() {
    if (data_) {
        plugin_handle_->close_file_read(data_);
    }
    plugin_data_.fini();
}

template <MolfileFormat F> int Molfile<F>::read_next_timestep(molfile_timestep_t* timestep) {
    if (plugin_handle_->read_next_timestep != nullptr) {
        // This function is provided by classical molecular simulation format.
        return plugin_handle_->read_next_timestep(data_, natoms_, timestep);
    } else if (plugin_handle_->read_timestep != nullptr) {
        // This function is provided by quantum molecular simulation format.
        return plugin_handle_->read_timestep(
            data_, natoms_, timestep, nullptr, nullptr
        );
    } else {
        throw format_error(
            "both read_next_timestep and read_timestep are missing in this "
            "plugin. This is a bug"
        );
    }
}

template <MolfileFormat F> void Molfile<F>::read(Frame& frame) {
    std::vector<float> coords(3 * static_cast<size_t>(natoms_));
    std::vector<float> velocities(0);

    molfile_timestep_t timestep{nullptr, nullptr, 0, 0, 0, 0, 0, 0, 0};
    timestep.coords = coords.data();
    if (plugin_data_.have_velocities()) {
        velocities.resize(3 * static_cast<size_t>(natoms_));
        timestep.velocities = velocities.data();
    }

    int status = read_next_timestep(&timestep);
    if (status != MOLFILE_SUCCESS) {
        throw format_error(
            "error while reading the file at '{}' with {} plugin",
            path_, plugin_data_.format()
        );
    }

    if (topology_) {
        frame.resize(topology_->size());
        frame.set_topology(*topology_);
    }
    molfile_to_frame(timestep, frame);

    frames_.emplace_back(frame.clone());
}

template <MolfileFormat F> void Molfile<F>::read_step(size_t step, Frame& frame) {
    while (step >= frames_.size()) {
        Frame new_frame;
        this->read(new_frame);
    }
    frame = frames_.at(step).clone();
}

template <MolfileFormat F> size_t Molfile<F>::nsteps() {
    if (plugin_handle_->read_next_timestep == nullptr) {
        // FIXME: this is hacky, but the molden plugin does not respect a NULL
        // argument for molfile_timestep_t, so for now we are only able to read
        // a sinle step from all the QM format plugins.
        return 1;
    }
    size_t n = 0;
    int status = MOLFILE_SUCCESS;
    while (true) {
        status = read_next_timestep(nullptr);
        if (status == MOLFILE_SUCCESS) {
            n++;
        } else {
            break;
        }
    }
    // We need to close and re-open the file
    plugin_handle_->close_file_read(data_);
    int unused = 0;
    data_ = plugin_handle_->open_file_read(path_.c_str(), plugin_handle_->name, &unused);
    read_topology();

    return n;
}

template <MolfileFormat F>
void Molfile<F>::molfile_to_frame(const molfile_timestep_t& timestep,
                                  Frame& frame) {
    frame.set_cell({
        static_cast<double>(timestep.A),
        static_cast<double>(timestep.B),
        static_cast<double>(timestep.C),
        static_cast<double>(timestep.alpha),
        static_cast<double>(timestep.beta),
        static_cast<double>(timestep.gamma)
    });

    frame.resize(static_cast<size_t>(natoms_));
    auto positions = frame.positions();
    for (size_t i = 0; i < static_cast<size_t>(natoms_); i++) {
        positions[i][0] = static_cast<double>(timestep.coords[3 * i + 0]);
        positions[i][1] = static_cast<double>(timestep.coords[3 * i + 1]);
        positions[i][2] = static_cast<double>(timestep.coords[3 * i + 2]);
    }

    if (plugin_data_.have_velocities()) {
        frame.add_velocities();
        auto velocities = frame.velocities();
        for (size_t i = 0; i < static_cast<size_t>(natoms_); i++) {
            (*velocities)[i][0] = static_cast<double>(timestep.velocities[3 * i + 0]);
            (*velocities)[i][1] = static_cast<double>(timestep.velocities[3 * i + 1]);
            (*velocities)[i][2] = static_cast<double>(timestep.velocities[3 * i + 2]);
        }
    }
}

template <MolfileFormat F> void Molfile<F>::read_topology() {
    if (plugin_handle_->read_structure == nullptr) {
        return;
    }

    std::vector<molfile_atom_t> atoms(static_cast<size_t>(natoms_));
    int optflags = 0;
    int status = plugin_handle_->read_structure(data_, &optflags, atoms.data());
    if (status != MOLFILE_SUCCESS) {
        throw format_error(
            "could not read the molecule structure with {} plugin",
            plugin_data_.format()
        );
    }

    topology_ = Topology();

    auto residues = std::unordered_map<int64_t, Residue>();
    size_t atom_id = 0;
    for (auto& molfile_atom : atoms) {
        Atom atom(molfile_atom.name, molfile_atom.type);
        if ((optflags & MOLFILE_MASS) != 0) {
            atom.set_mass(static_cast<double>(molfile_atom.mass));
        }
        if ((optflags & MOLFILE_CHARGE) != 0) {
            atom.set_charge(static_cast<double>(molfile_atom.charge));
        }

        topology_->add_atom(std::move(atom));

        if (molfile_atom.resname != std::string("")) {
            auto resid = static_cast<int64_t>(molfile_atom.resid);
            auto residue = Residue(molfile_atom.resname, resid);
            auto inserted = residues.insert({resid, std::move(residue)});
            inserted.first->second.add_atom(atom_id);
        }
        atom_id++;
    }

    if (plugin_handle_->read_bonds == nullptr) {
        return;
    }

    int nbonds = 0;
    int* from = nullptr;
    int* to = nullptr;

    int dummy = 0;
    float* _float = nullptr;
    int* _int = nullptr;
    char** _char = nullptr;

    status = plugin_handle_->read_bonds(
        data_, &nbonds, &from, &to, &_float, &_int, &dummy, &_char
    );
    if (status != MOLFILE_SUCCESS) {
        throw format_error(
            "could not read bonds with {} plugin", plugin_data_.format()
        );
    }

    for (size_t i = 0; i < static_cast<size_t>(nbonds); i++) {
        // Indexes are 1-based in Molfile
        topology_->add_bond(static_cast<size_t>(from[i] - 1),
                            static_cast<size_t>(to[i]) - 1);
    }
}

// Instanciate all the templates
template class chemfiles::Molfile<DCD>;
template class chemfiles::Molfile<TRJ>;
template class chemfiles::Molfile<LAMMPS>;
template class chemfiles::Molfile<MOLDEN>;

template<> FormatInfo chemfiles::format_information<Molfile<DCD>>() {
    return FormatInfo("DCD").with_extension(".dcd").description(
        "DCD binary format"
    );
}

template<> FormatInfo chemfiles::format_information<Molfile<TRJ>>() {
    return FormatInfo("TRJ").with_extension(".trj").description(
        "GROMACS .trj binary format"
    );
}

template<> FormatInfo chemfiles::format_information<Molfile<LAMMPS>>() {
    return FormatInfo("LAMMPS").with_extension(".lammpstrj").description(
        "LAMMPS text trajectory format"
    );
}

template<> FormatInfo chemfiles::format_information<Molfile<MOLDEN>>() {
    return FormatInfo("Molden").with_extension(".molden").description(
        "Molden text format"
    );
}
<|endoftext|>


<commit_before>/******************************************************************
*
* uHTTP for C++
*
* Copyright (C) Satoshi Konno 2002
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/

#include <stdlib.h>

#include <uhttp/http/HTTP.h>
#include <uhttp/http/HTTPStatus.h>
#include <uhttp/util/StringTokenizer.h>
#include <uhttp/util/StringUtil.h>

using namespace uHTTP;
using namespace uHTTP;

////////////////////////////////////////////////
//  Constructor
////////////////////////////////////////////////

HTTPStatus::HTTPStatus() {
  setVersion("");
  setStatusCode(0);
  setReasonPhrase("");
}

HTTPStatus::HTTPStatus(const std::string &ver, int code, const std::string &reason) {
  setVersion(ver);
  setStatusCode(code);
  setReasonPhrase(reason);
}

HTTPStatus::HTTPStatus(const std::string &lineStr) {
  set(lineStr);
}

////////////////////////////////////////////////
//  set
////////////////////////////////////////////////

void HTTPStatus::set(const std::string &lineStr) {
    if (lineStr.length() <= 0) {
      setVersion(HTTP::VER);
      setStatusCode(HTTP::INTERNAL_SERVER_ERROR);
      setReasonPhrase(HTTP::StatusCode2String(HTTP::INTERNAL_SERVER_ERROR));
      return;
    }

    StringTokenizer st(lineStr, HTTP::STATUS_LINE_DELIM);
    std::string trimBuf;

    if (st.hasMoreTokens() == false)
      return;
    std::string ver = st.nextToken();
    setVersion(StringTrim(ver.c_str(), trimBuf));

    if (st.hasMoreTokens() == false)
      return;
    std::string codeStr = st.nextToken();
    int code = atoi(codeStr.c_str());
    setStatusCode(code);

    std::string reason = "";
    while (st.hasMoreTokens() == true) {
      if (0 < reason.length())
        reason.append(" ");
      reason.append(st.nextToken());
    }
    setReasonPhrase(StringTrim(reason.c_str(), trimBuf));
}

////////////////////////////////////////////////
//  IsStatusCodeSuccess
////////////////////////////////////////////////

bool uHTTP::HTTP::IsStatusCodeSuccess(int statCode) {
  if (200 <= statCode && statCode < 300)
    return true;
  return false;
}

////////////////////////////////////////////////
//  StatusCode2String
////////////////////////////////////////////////

const std::string &uHTTP::HTTP::StatusCode2String(int code) {
  int errType = code - (code % 100);

  if (errType == 100) {
    switch (code) {
      case PROCESSING: return PROCESSING_STRING;
    }
    return CONTINUE_STRING;
  }

  if (errType == 200) {
    switch (code) {
      case ACCEPTED: return ACCEPTED_STRING;
      case NO_CONTENT: return NO_CONTENT_STRING;
      case PARTIAL_CONTENT: return PARTIAL_CONTENT_STRING;
    }
    return OK_REQUEST_STRING;
  }

  if (errType == 400) {
    switch (code) {
      case NOT_FOUND: return NOT_FOUND_STING;
      case PRECONDITION_FAILED: return PRECONDITION_FAILED_STING;
      case INVALID_RANGE: return INVALID_RANGE_STING;
    }
    return BAD_REQUEST_STRING;
  }

  if (errType == 500) {
    return INTERNAL_SERVER_ERROR_STRING;
  }

  if (errType == 600) {
    return INTERNAL_CLIENT_ERROR_STRING;
  }

  return UNKOWN_ERROR_STRING;
}
<commit_msg>* Removed extra namespace.<commit_after>/******************************************************************
*
* uHTTP for C++
*
* Copyright (C) Satoshi Konno 2002
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/

#include <stdlib.h>

#include <uhttp/http/HTTP.h>
#include <uhttp/http/HTTPStatus.h>
#include <uhttp/util/StringTokenizer.h>
#include <uhttp/util/StringUtil.h>

using namespace uHTTP;

////////////////////////////////////////////////
//  Constructor
////////////////////////////////////////////////

HTTPStatus::HTTPStatus() {
  setVersion("");
  setStatusCode(0);
  setReasonPhrase("");
}

HTTPStatus::HTTPStatus(const std::string &ver, int code, const std::string &reason) {
  setVersion(ver);
  setStatusCode(code);
  setReasonPhrase(reason);
}

HTTPStatus::HTTPStatus(const std::string &lineStr) {
  set(lineStr);
}

////////////////////////////////////////////////
//  set
////////////////////////////////////////////////

void HTTPStatus::set(const std::string &lineStr) {
    if (lineStr.length() <= 0) {
      setVersion(HTTP::VER);
      setStatusCode(HTTP::INTERNAL_SERVER_ERROR);
      setReasonPhrase(HTTP::StatusCode2String(HTTP::INTERNAL_SERVER_ERROR));
      return;
    }

    StringTokenizer st(lineStr, HTTP::STATUS_LINE_DELIM);
    std::string trimBuf;

    if (st.hasMoreTokens() == false)
      return;
    std::string ver = st.nextToken();
    setVersion(StringTrim(ver.c_str(), trimBuf));

    if (st.hasMoreTokens() == false)
      return;
    std::string codeStr = st.nextToken();
    int code = atoi(codeStr.c_str());
    setStatusCode(code);

    std::string reason = "";
    while (st.hasMoreTokens() == true) {
      if (0 < reason.length())
        reason.append(" ");
      reason.append(st.nextToken());
    }
    setReasonPhrase(StringTrim(reason.c_str(), trimBuf));
}

////////////////////////////////////////////////
//  IsStatusCodeSuccess
////////////////////////////////////////////////

bool uHTTP::HTTP::IsStatusCodeSuccess(int statCode) {
  if (200 <= statCode && statCode < 300)
    return true;
  return false;
}

////////////////////////////////////////////////
//  StatusCode2String
////////////////////////////////////////////////

const std::string &uHTTP::HTTP::StatusCode2String(int code) {
  int errType = code - (code % 100);

  if (errType == 100) {
    switch (code) {
      case PROCESSING: return PROCESSING_STRING;
    }
    return CONTINUE_STRING;
  }

  if (errType == 200) {
    switch (code) {
      case ACCEPTED: return ACCEPTED_STRING;
      case NO_CONTENT: return NO_CONTENT_STRING;
      case PARTIAL_CONTENT: return PARTIAL_CONTENT_STRING;
    }
    return OK_REQUEST_STRING;
  }

  if (errType == 400) {
    switch (code) {
      case NOT_FOUND: return NOT_FOUND_STING;
      case PRECONDITION_FAILED: return PRECONDITION_FAILED_STING;
      case INVALID_RANGE: return INVALID_RANGE_STING;
    }
    return BAD_REQUEST_STRING;
  }

  if (errType == 500) {
    return INTERNAL_SERVER_ERROR_STRING;
  }

  if (errType == 600) {
    return INTERNAL_CLIENT_ERROR_STRING;
  }

  return UNKOWN_ERROR_STRING;
}
<|endoftext|>


<commit_before>#include <stan/services/util/experimental_message.hpp>
#include <gtest/gtest.h>
#include <stan/callbacks/stream_writer.hpp>
#include <sstream>

TEST(ServicesUtil, experimental_message) {
  std::stringstream ss;
  stan::callbacks::stream_writer writer(ss);

  stan::services::util::experimental_message(writer);

  EXPECT_TRUE(ss.str().find("EXPERIMENTAL ALGORITHM") != std::string::npos);
}
<commit_msg>updating experimental message test<commit_after>#include <stan/services/util/experimental_message.hpp>
#include <gtest/gtest.h>
#include <test/unit/services/instrumented_callbacks.hpp>
#include <sstream>

TEST(ServicesUtil, experimental_message) {
  stan::test::unit::instrumented_logger logger;

  stan::services::util::experimental_message(logger);

  EXPECT_EQ(1, logger.find_info("EXPERIMENTAL ALGORITHM"));
}
<|endoftext|>


<commit_before>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
 *
 * This file is part of WATCHER.
 *
 *     WATCHER is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Affero General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     WATCHER is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Affero General Public License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Watcher.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <iostream>
#include <string>
#include <getopt.h>

#include "server.h"
#include "logger.h"
#include "libconfig.h++"
#include "initConfig.h"
#include "singletonConfig.h"
#include "watcherd.h"

using namespace std;
using namespace watcher;
using namespace libconfig;

option Options[] = {
    { "help", 0, NULL, 'h' },
    { "config", 1, NULL, 'c' },
    { "database", 1, NULL, 'd' },
    { "read-only", 1, NULL, 'r' },
    { 0, 0, NULL, 0 }
};

void usage(const char *progName, bool exitp)
{
    cout << "Usage: " << basename(progName) << " [-c config filename]" << endl;
    cout << "Args: " << endl;
    cout << "   -h, show this messsage and exit." << endl;
    cout << "   -d database, use this event database when running watcherd" << endl;
    cout << "   -c configfile - If not given a filename of the form \""<< basename(progName) << ".cfg\" is assumed." << endl;
    cout << "   -r, --read-only - do not write events to the database." << endl;
    cout << "If a configuration file is not found on startup, a default one will be created, used, and saved on program exit." << endl;

    if (exitp)
        exit(EXIT_FAILURE);
}

DECLARE_GLOBAL_LOGGER("watcherdMain");

int main(int argc, char* argv[])
{
    TRACE_ENTER();

    int i;
    bool readOnly = false;
    std::string dbPath;
    while ((i = getopt_long(argc, argv, "hc:d:r", Options, NULL)) != -1) {
        switch (i) {
            case 'c':
                //handled below
                break;
            case 'r':
                readOnly = true;
                break;
            case 'd':
                dbPath=string(optarg);
                break;
            default:
                usage(argv[0], true);
        }
    }

    string configFilename;
    Config &config=SingletonConfig::instance();
    SingletonConfig::lock();
    if (false==initConfig(config, argc, argv, configFilename))
    {
        cerr << "Error reading configuration file, unable to continue." << endl;
        cerr << "Usage: " << basename(argv[0]) << " [-c|--configFile] configfile" << endl;
        return 1;
    }
    SingletonConfig::unlock();

    string logConf("log.properties");
    if (!config.lookupValue("logPropertiesFile", logConf))
    {
        cout << "Unable to find logPropertiesFile setting in the configuration file, using default: " << logConf
             << " and adding it to the configuration file." << endl;
        config.getRoot().add("logPropertiesFile", libconfig::Setting::TypeString)=logConf;
    }

    LOAD_LOG_PROPS(logConf);

    LOG_INFO("Logger initialized from file \"" << logConf << "\"");

    string address("glory");
    string port("8095");
    size_t numThreads=8;

    if (!config.lookupValue("server", address))
    {
        LOG_INFO("'server' not found in the configuration file, using default: " << address
                << " and adding this to the configuration file.");
        config.getRoot().add("server", libconfig::Setting::TypeString) = address;
    }

    if (!config.lookupValue("port", port))
    {
        LOG_INFO("'port' not found in the configuration file, using default: " << port
                << " and adding this to the configuration file.");
        config.getRoot().add("port", libconfig::Setting::TypeString)=port;
    }

    if (!config.lookupValue("serverThreadNum", numThreads))
    {
        LOG_INFO("'serverThreadNum' not found in the configuration file, using default: " << numThreads
                << " and adding this to the configuration file.");
           config.getRoot().add("serverThreadNum", libconfig::Setting::TypeInt)=static_cast<int>(numThreads);
    }

    std::string tmpDBPath("event.db");
    if (!config.lookupValue("databasePath", tmpDBPath))
    {
        LOG_INFO("'databasePath' not found in the configuration file, using default: " << dbPath
                << " and adding this to the configuration file.");
           config.getRoot().add("databasePath", libconfig::Setting::TypeString)=tmpDBPath;
    }
    if (dbPath.size())
        config.getRoot()["databasePath"]=dbPath;

    WatcherdPtr theWatcherDaemon(new Watcherd(readOnly));
    try
    {
        theWatcherDaemon->run(address, port, (int)numThreads);
    }
    catch (std::exception &e)
    {
        LOG_FATAL("Caught exception in main(): " << e.what());
        std::cerr << "exception: " << e.what() << "\n";
    }

    // Save any configuration changes made during the run.
    LOG_INFO("Saving last known configuration to " << configFilename);
    SingletonConfig::lock();
    config.writeFile(configFilename.c_str());

    return 0;
}
<commit_msg>default hostname is now "localhost" so everyone but me can actually run watcherd by just typing "watcherd".<commit_after>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
 *
 * This file is part of WATCHER.
 *
 *     WATCHER is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Affero General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     WATCHER is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Affero General Public License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Watcher.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <iostream>
#include <string>
#include <getopt.h>

#include "server.h"
#include "logger.h"
#include "libconfig.h++"
#include "initConfig.h"
#include "singletonConfig.h"
#include "watcherd.h"

using namespace std;
using namespace watcher;
using namespace libconfig;

option Options[] = {
    { "help", 0, NULL, 'h' },
    { "config", 1, NULL, 'c' },
    { "database", 1, NULL, 'd' },
    { "read-only", 1, NULL, 'r' },
    { 0, 0, NULL, 0 }
};

void usage(const char *progName, bool exitp)
{
    cout << "Usage: " << basename(progName) << " [-c config filename]" << endl;
    cout << "Args: " << endl;
    cout << "   -h, show this messsage and exit." << endl;
    cout << "   -d database, use this event database when running watcherd" << endl;
    cout << "   -c configfile - If not given a filename of the form \""<< basename(progName) << ".cfg\" is assumed." << endl;
    cout << "   -r, --read-only - do not write events to the database." << endl;
    cout << "If a configuration file is not found on startup, a default one will be created, used, and saved on program exit." << endl;

    if (exitp)
        exit(EXIT_FAILURE);
}

DECLARE_GLOBAL_LOGGER("watcherdMain");

int main(int argc, char* argv[])
{
    TRACE_ENTER();

    int i;
    bool readOnly = false;
    std::string dbPath;
    while ((i = getopt_long(argc, argv, "hc:d:r", Options, NULL)) != -1) {
        switch (i) {
            case 'c':
                //handled below
                break;
            case 'r':
                readOnly = true;
                break;
            case 'd':
                dbPath=string(optarg);
                break;
            default:
                usage(argv[0], true);
        }
    }

    string configFilename;
    Config &config=SingletonConfig::instance();
    SingletonConfig::lock();
    if (false==initConfig(config, argc, argv, configFilename))
    {
        cerr << "Error reading configuration file, unable to continue." << endl;
        cerr << "Usage: " << basename(argv[0]) << " [-c|--configFile] configfile" << endl;
        return 1;
    }
    SingletonConfig::unlock();

    string logConf("log.properties");
    if (!config.lookupValue("logPropertiesFile", logConf))
    {
        cout << "Unable to find logPropertiesFile setting in the configuration file, using default: " << logConf
             << " and adding it to the configuration file." << endl;
        config.getRoot().add("logPropertiesFile", libconfig::Setting::TypeString)=logConf;
    }

    LOAD_LOG_PROPS(logConf);

    LOG_INFO("Logger initialized from file \"" << logConf << "\"");

    string address("localhost");
    string port("8095");
    size_t numThreads=8;

    if (!config.lookupValue("server", address))
    {
        LOG_INFO("'server' not found in the configuration file, using default: " << address
                << " and adding this to the configuration file.");
        config.getRoot().add("server", libconfig::Setting::TypeString) = address;
    }

    if (!config.lookupValue("port", port))
    {
        LOG_INFO("'port' not found in the configuration file, using default: " << port
                << " and adding this to the configuration file.");
        config.getRoot().add("port", libconfig::Setting::TypeString)=port;
    }

    if (!config.lookupValue("serverThreadNum", numThreads))
    {
        LOG_INFO("'serverThreadNum' not found in the configuration file, using default: " << numThreads
                << " and adding this to the configuration file.");
           config.getRoot().add("serverThreadNum", libconfig::Setting::TypeInt)=static_cast<int>(numThreads);
    }

    std::string tmpDBPath("event.db");
    if (!config.lookupValue("databasePath", tmpDBPath))
    {
        LOG_INFO("'databasePath' not found in the configuration file, using default: " << dbPath
                << " and adding this to the configuration file.");
           config.getRoot().add("databasePath", libconfig::Setting::TypeString)=tmpDBPath;
    }
    if (dbPath.size())
        config.getRoot()["databasePath"]=dbPath;

    WatcherdPtr theWatcherDaemon(new Watcherd(readOnly));
    try
    {
        theWatcherDaemon->run(address, port, (int)numThreads);
    }
    catch (std::exception &e)
    {
        LOG_FATAL("Caught exception in main(): " << e.what());
        std::cerr << "exception: " << e.what() << "\n";
    }

    // Save any configuration changes made during the run.
    LOG_INFO("Saving last known configuration to " << configFilename);
    SingletonConfig::lock();
    config.writeFile(configFilename.c_str());

    return 0;
}
<|endoftext|>


<commit_before>#include "apt_source_manager_page.h"
#include "ui_apt_source_manager_page.h"
#include <QDebug>
#include "utilities.h"
#include "Managers/tool_manager.h"

APTSourceManagerPage::~APTSourceManagerPage()
{
    delete ui;
}

APTSourcePtr APTSourceManagerPage::selectedAptSource = nullptr;

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

    init();
}

void APTSourceManagerPage::init()
{
    ui->txtAptSource->setPlaceholderText(tr("example %1")
                                         .arg("'deb http://archive.ubuntu.com/ubuntu xenial main'"));

    loadAptSources();

    on_btnCancel_clicked();

    Utilities::addDropShadow(ui->txtSearchAptSource, 40);
}

void APTSourceManagerPage::loadAptSources()
{
    ui->listWidgetAptSources->clear();

    QList<APTSourcePtr> aptSourceList = ToolManager::ins()->getSourceList();

    for (APTSourcePtr &aptSource: aptSourceList) {

        QListWidgetItem *listItem = new QListWidgetItem(ui->listWidgetAptSources);
        listItem->setData(5, aptSource->source); // for search

        APTSourceRepositoryItem *aptSourceItem = new APTSourceRepositoryItem(aptSource, ui->listWidgetAptSources);

        listItem->setSizeHint(aptSourceItem->sizeHint() + QSize(0, 1));

        ui->listWidgetAptSources->setItemWidget(listItem, aptSourceItem);
    }

    ui->notFoundWidget->setVisible(aptSourceList.isEmpty());

    ui->lblAptSourceTitle->setText(tr("APT Repositories (%1)")
                                   .arg(aptSourceList.count()));
}

void APTSourceManagerPage::on_btnAddAPTSourceRepository_clicked(bool checked)
{
    if (checked) {
        ui->btnAddAPTSourceRepository->setText(tr("Save"));
        changeElementsVisible(checked);
    } else {
        QString aptSourceRepository = ui->txtAptSource->text().trimmed();

        if (! aptSourceRepository.isEmpty()) {
            ToolManager::ins()->addAPTRepository(aptSourceRepository, ui->checkEnableSource->isChecked());

            ui->txtAptSource->clear();
            ui->checkEnableSource->setChecked(false);
            on_btnCancel_clicked();
            loadAptSources();
        }
    }
}

void APTSourceManagerPage::on_btnCancel_clicked()
{
    ui->btnAddAPTSourceRepository->setChecked(false);
    changeElementsVisible(false);
    ui->btnAddAPTSourceRepository->setText(tr("Add Repository"));
}

void APTSourceManagerPage::changeElementsVisible(const bool checked)
{
    ui->txtAptSource->setVisible(checked);
    ui->checkEnableSource->setVisible(checked);
    ui->btnCancel->setVisible(checked);
    ui->btnEditAptSource->setVisible(!checked);
    ui->btnDeleteAptSource->setVisible(!checked);
    ui->bottomSectionHorizontalSpacer->changeSize(0, 0, checked ? QSizePolicy::Minimum : QSizePolicy::Expanding);
}

void APTSourceManagerPage::on_listWidgetAptSources_itemClicked(QListWidgetItem *item)
{
    QWidget *widget = ui->listWidgetAptSources->itemWidget(item);
    if (widget) {
        APTSourceRepositoryItem *aptSourceItem = dynamic_cast<APTSourceRepositoryItem*>(widget);
        if (aptSourceItem) {
            selectedAptSource = aptSourceItem->aptSource();
        }
    } else {
        selectedAptSource.clear();
    }
}

void APTSourceManagerPage::on_listWidgetAptSources_itemDoubleClicked(QListWidgetItem *item)
{
    on_listWidgetAptSources_itemClicked(item);
    on_btnEditAptSource_clicked();
}

void APTSourceManagerPage::on_btnDeleteAptSource_clicked()
{
    if (! selectedAptSource.isNull()) {
        ToolManager::ins()->removeAPTSource(selectedAptSource);
        loadAptSources();
    }
}

void APTSourceManagerPage::on_txtSearchAptSource_textChanged(const QString &val)
{
    for (int i = 0; i < ui->listWidgetAptSources->count(); ++i) {
        QListWidgetItem *item = ui->listWidgetAptSources->item(i);
        if (item) {
            bool isContain = item->data(5).toString().contains(val, Qt::CaseInsensitive);
            ui->listWidgetAptSources->setItemHidden(item, ! isContain);
        }
    }
}

void APTSourceManagerPage::on_btnEditAptSource_clicked()
{
    if (! selectedAptSource.isNull()) {
        if (mAptSourceEditDialog.isNull()) {
            mAptSourceEditDialog = QSharedPointer<APTSourceEdit>(new APTSourceEdit(this));
            connect(mAptSourceEditDialog.data(), &APTSourceEdit::saved, this, &APTSourceManagerPage::loadAptSources);
        }
        APTSourceEdit::selectedAptSource = selectedAptSource;
        mAptSourceEditDialog->show();
    }
}
<commit_msg>added shadow to buttons<commit_after>#include "apt_source_manager_page.h"
#include "ui_apt_source_manager_page.h"
#include <QDebug>
#include "utilities.h"
#include "Managers/tool_manager.h"

APTSourceManagerPage::~APTSourceManagerPage()
{
    delete ui;
}

APTSourcePtr APTSourceManagerPage::selectedAptSource = nullptr;

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

    init();
}

void APTSourceManagerPage::init()
{
    ui->txtAptSource->setPlaceholderText(tr("example %1")
                                         .arg("'deb http://archive.ubuntu.com/ubuntu xenial main'"));

    loadAptSources();

    on_btnCancel_clicked();

    QList<QWidget*> widgets = {
        ui->btnAddAPTSourceRepository, ui->btnCancel, ui->btnDeleteAptSource, ui->btnEditAptSource,
        ui->txtSearchAptSource, ui->txtSearchAptSource
    };
    Utilities::addDropShadow(widgets, 40);
}

void APTSourceManagerPage::loadAptSources()
{
    ui->listWidgetAptSources->clear();

    QList<APTSourcePtr> aptSourceList = ToolManager::ins()->getSourceList();

    for (APTSourcePtr &aptSource: aptSourceList) {

        QListWidgetItem *listItem = new QListWidgetItem(ui->listWidgetAptSources);
        listItem->setData(5, aptSource->source); // for search

        APTSourceRepositoryItem *aptSourceItem = new APTSourceRepositoryItem(aptSource, ui->listWidgetAptSources);

        listItem->setSizeHint(aptSourceItem->sizeHint() + QSize(0, 1));

        ui->listWidgetAptSources->setItemWidget(listItem, aptSourceItem);
    }

    ui->notFoundWidget->setVisible(aptSourceList.isEmpty());

    ui->lblAptSourceTitle->setText(tr("APT Repositories (%1)")
                                   .arg(aptSourceList.count()));
}

void APTSourceManagerPage::on_btnAddAPTSourceRepository_clicked(bool checked)
{
    if (checked) {
        ui->btnAddAPTSourceRepository->setText(tr("Save"));
        changeElementsVisible(checked);
    } else {
        QString aptSourceRepository = ui->txtAptSource->text().trimmed();

        if (! aptSourceRepository.isEmpty()) {
            ToolManager::ins()->addAPTRepository(aptSourceRepository, ui->checkEnableSource->isChecked());

            ui->txtAptSource->clear();
            ui->checkEnableSource->setChecked(false);
            on_btnCancel_clicked();
            loadAptSources();
        }
    }
}

void APTSourceManagerPage::on_btnCancel_clicked()
{
    ui->btnAddAPTSourceRepository->setChecked(false);
    changeElementsVisible(false);
    ui->btnAddAPTSourceRepository->setText(tr("Add Repository"));
}

void APTSourceManagerPage::changeElementsVisible(const bool checked)
{
    ui->txtAptSource->setVisible(checked);
    ui->checkEnableSource->setVisible(checked);
    ui->btnCancel->setVisible(checked);
    ui->btnEditAptSource->setVisible(!checked);
    ui->btnDeleteAptSource->setVisible(!checked);
    ui->bottomSectionHorizontalSpacer->changeSize(0, 0, checked ? QSizePolicy::Minimum : QSizePolicy::Expanding);
}

void APTSourceManagerPage::on_listWidgetAptSources_itemClicked(QListWidgetItem *item)
{
    QWidget *widget = ui->listWidgetAptSources->itemWidget(item);
    if (widget) {
        APTSourceRepositoryItem *aptSourceItem = dynamic_cast<APTSourceRepositoryItem*>(widget);
        if (aptSourceItem) {
            selectedAptSource = aptSourceItem->aptSource();
        }
    } else {
        selectedAptSource.clear();
    }
}

void APTSourceManagerPage::on_listWidgetAptSources_itemDoubleClicked(QListWidgetItem *item)
{
    on_listWidgetAptSources_itemClicked(item);
    on_btnEditAptSource_clicked();
}

void APTSourceManagerPage::on_btnDeleteAptSource_clicked()
{
    if (! selectedAptSource.isNull()) {
        ToolManager::ins()->removeAPTSource(selectedAptSource);
        loadAptSources();
    }
}

void APTSourceManagerPage::on_txtSearchAptSource_textChanged(const QString &val)
{
    for (int i = 0; i < ui->listWidgetAptSources->count(); ++i) {
        QListWidgetItem *item = ui->listWidgetAptSources->item(i);
        if (item) {
            bool isContain = item->data(5).toString().contains(val, Qt::CaseInsensitive);
            ui->listWidgetAptSources->setItemHidden(item, ! isContain);
        }
    }
}

void APTSourceManagerPage::on_btnEditAptSource_clicked()
{
    if (! selectedAptSource.isNull()) {
        if (mAptSourceEditDialog.isNull()) {
            mAptSourceEditDialog = QSharedPointer<APTSourceEdit>(new APTSourceEdit(this));
            connect(mAptSourceEditDialog.data(), &APTSourceEdit::saved, this, &APTSourceManagerPage::loadAptSources);
        }
        APTSourceEdit::selectedAptSource = selectedAptSource;
        mAptSourceEditDialog->show();
    }
}
<|endoftext|>


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

#pragma hdrstop

#include "fuline.hxx"

#include <svx/svxids.hrc>
#ifndef _SVX_TAB_LINE_HXX //autogen
#include <svx/tabline.hxx>
#endif
#ifndef _XENUM_HXX //autogen
#include <svx/xenum.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _XDEF_HXX //autogen
#include <svx/xdef.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif

#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_WINDOW_SHELL_HXX
#include "Window.hxx"
#endif
#include "drawdoc.hxx"
#include "app.hrc"
#include <svx/svxdlg.hxx> //CHINA001
#include <svx/dialogs.hrc> //CHINA001

namespace sd {

TYPEINIT1( FuLine, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuLine::FuLine (
    ViewShell* pViewSh,
    ::sd::Window* pWin,
    ::sd::View* pView,
    SdDrawDocument* pDoc,
    SfxRequest& rReq)
    : FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}

FunctionReference FuLine::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
    FunctionReference xFunc( new FuLine( pViewSh, pWin, pView, pDoc, rReq ) );
    xFunc->DoExecute(rReq);
    return xFunc;
}

void FuLine::DoExecute( SfxRequest& rReq )
{
    BOOL        bHasMarked = pView->AreObjectsMarked();

    const SfxItemSet* pArgs = rReq.GetArgs();

    if( !pArgs )
    {
        // erst einmal alle eingabeparameter fuer den dialog retten
        SfxItemSet aInputAttr( pDoc->GetPool() );
        pView->GetAttributes( aInputAttr );

        const XLineStyleItem &rILineStyleItem = (const XLineStyleItem &) aInputAttr.Get (XATTR_LINESTYLE);
        XLineStyle           eILineStyle      = rILineStyleItem.GetValue ();

        const XLineDashItem  &rILineDashItem  = (const XLineDashItem &) aInputAttr.Get (XATTR_LINEDASH);
        const XDash          &rIDash          = rILineDashItem.GetValue ();

        const XLineWidthItem &rILineWidthItem = (const XLineWidthItem &) aInputAttr.Get (XATTR_LINEWIDTH);
        long                 nILineWidth      = rILineWidthItem.GetValue ();

        const XLineColorItem &rILineColorItem = (const XLineColorItem &) aInputAttr.Get (XATTR_LINECOLOR);
        const Color          &rIColor         = rILineColorItem.GetValue ();

        const SdrObject* pObj = NULL;
        const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
        if( rMarkList.GetMarkCount() == 1 )
            pObj = rMarkList.GetMark(0)->GetObj();

        SfxItemSet* pNewAttr = new SfxItemSet( pDoc->GetPool() );
        pView->GetAttributes( *pNewAttr );

        //CHINA001 SvxLineTabDialog* pDlg = new SvxLineTabDialog( NULL, pNewAttr, pDoc, pObj, bHasMarked );
        SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
        DBG_ASSERT(pFact, "Dialogdiet Factory fail!");//CHINA001
        SfxAbstractTabDialog * pDlg = pFact->CreateSvxLineTabDialog(NULL,
                    pNewAttr,
                    pDoc,
                ResId(RID_SVXDLG_LINE),
                pObj,
                bHasMarked);
        DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
        if ( pDlg->Execute() == RET_OK )
        {
            // die ausgabeparameter des dialogs bestimmen
            SfxItemSet           *pOutputAttr     = (SfxItemSet *) pDlg->GetOutputItemSet();

            const XLineStyleItem &rOLineStyleItem = (const XLineStyleItem &) pOutputAttr->Get (XATTR_LINESTYLE);
            XLineStyle           eOLineStyle      = rOLineStyleItem.GetValue ();

            const XLineDashItem  &rOLineDashItem  = (const XLineDashItem &) pOutputAttr->Get (XATTR_LINEDASH);
            const XDash          &rODash          = rOLineDashItem.GetValue ();

            const XLineWidthItem &rOLineWidthItem = (const XLineWidthItem &) pOutputAttr->Get (XATTR_LINEWIDTH);
            long                 nOLineWidth      = rOLineWidthItem.GetValue ();

            const XLineColorItem &rOLineColorItem = (const XLineColorItem &) pOutputAttr->Get (XATTR_LINECOLOR);
            const Color          &rOColor         = rOLineColorItem.GetValue ();

            pView->SetAttributes (*(pDlg->GetOutputItemSet ()));
        }

        // Attribute wurden geaendert, Listboxes in Objectbars muessen aktualisiert werden
        static USHORT SidArray[] = {
                        SID_ATTR_LINE_STYLE,
                        SID_ATTR_LINE_DASH,
                        SID_ATTR_LINE_WIDTH,
                        SID_ATTR_LINE_COLOR,
                        0 };

        pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );

        delete pDlg;
        delete pNewAttr;
    }

    rReq.Ignore ();
}

void FuLine::Activate()
{
}

void FuLine::Deactivate()
{
}

} // end of namespace sd
<commit_msg>INTEGRATION: CWS warnings01 (1.7.150); FILE MERGED 2006/05/12 16:40:35 sb 1.7.150.1: #i53898# Made code warning-free and/or compile at all after resync to SRC680m162.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fuline.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 12:32:32 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#pragma hdrstop

#include "fuline.hxx"

#include <svx/svxids.hrc>
#ifndef _SVX_TAB_LINE_HXX //autogen
#include <svx/tabline.hxx>
#endif
#ifndef _XENUM_HXX //autogen
#include <svx/xenum.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _XDEF_HXX //autogen
#include <svx/xdef.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif

#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_WINDOW_SHELL_HXX
#include "Window.hxx"
#endif
#include "drawdoc.hxx"
#include "app.hrc"
#include <svx/svxdlg.hxx> //CHINA001
#include <svx/dialogs.hrc> //CHINA001

namespace sd {

TYPEINIT1( FuLine, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuLine::FuLine (
    ViewShell* pViewSh,
    ::sd::Window* pWin,
    ::sd::View* pView,
    SdDrawDocument* pDoc,
    SfxRequest& rReq)
    : FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}

FunctionReference FuLine::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
    FunctionReference xFunc( new FuLine( pViewSh, pWin, pView, pDoc, rReq ) );
    xFunc->DoExecute(rReq);
    return xFunc;
}

void FuLine::DoExecute( SfxRequest& rReq )
{
    BOOL        bHasMarked = pView->AreObjectsMarked();

    const SfxItemSet* pArgs = rReq.GetArgs();

    if( !pArgs )
    {
        // erst einmal alle eingabeparameter fuer den dialog retten
        SfxItemSet aInputAttr( pDoc->GetPool() );
        pView->GetAttributes( aInputAttr );

        const XLineStyleItem &rILineStyleItem = (const XLineStyleItem &) aInputAttr.Get (XATTR_LINESTYLE);
        XLineStyle           eILineStyle      = rILineStyleItem.GetValue ();

        const XLineDashItem  &rILineDashItem  = (const XLineDashItem &) aInputAttr.Get (XATTR_LINEDASH);
        const XDash          &rIDash          = rILineDashItem.GetDashValue ();

        const XLineWidthItem &rILineWidthItem = (const XLineWidthItem &) aInputAttr.Get (XATTR_LINEWIDTH);
        long                 nILineWidth      = rILineWidthItem.GetValue ();

        const XLineColorItem &rILineColorItem = (const XLineColorItem &) aInputAttr.Get (XATTR_LINECOLOR);
        const Color          &rIColor         = rILineColorItem.GetColorValue ();

        const SdrObject* pObj = NULL;
        const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
        if( rMarkList.GetMarkCount() == 1 )
            pObj = rMarkList.GetMark(0)->GetObj();

        SfxItemSet* pNewAttr = new SfxItemSet( pDoc->GetPool() );
        pView->GetAttributes( *pNewAttr );

        //CHINA001 SvxLineTabDialog* pDlg = new SvxLineTabDialog( NULL, pNewAttr, pDoc, pObj, bHasMarked );
        SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
        DBG_ASSERT(pFact, "Dialogdiet Factory fail!");//CHINA001
        SfxAbstractTabDialog * pDlg = pFact->CreateSvxLineTabDialog(NULL,
                    pNewAttr,
                    pDoc,
                ResId(RID_SVXDLG_LINE),
                pObj,
                bHasMarked);
        DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
        if ( pDlg->Execute() == RET_OK )
        {
            // die ausgabeparameter des dialogs bestimmen
            SfxItemSet           *pOutputAttr     = (SfxItemSet *) pDlg->GetOutputItemSet();

            const XLineStyleItem &rOLineStyleItem = (const XLineStyleItem &) pOutputAttr->Get (XATTR_LINESTYLE);
            XLineStyle           eOLineStyle      = rOLineStyleItem.GetValue ();

            const XLineDashItem  &rOLineDashItem  = (const XLineDashItem &) pOutputAttr->Get (XATTR_LINEDASH);
            const XDash          &rODash          = rOLineDashItem.GetDashValue ();

            const XLineWidthItem &rOLineWidthItem = (const XLineWidthItem &) pOutputAttr->Get (XATTR_LINEWIDTH);
            long                 nOLineWidth      = rOLineWidthItem.GetValue ();

            const XLineColorItem &rOLineColorItem = (const XLineColorItem &) pOutputAttr->Get (XATTR_LINECOLOR);
            const Color          &rOColor         = rOLineColorItem.GetColorValue ();

            pView->SetAttributes (*(pDlg->GetOutputItemSet ()));
        }

        // Attribute wurden geaendert, Listboxes in Objectbars muessen aktualisiert werden
        static USHORT SidArray[] = {
                        SID_ATTR_LINE_STYLE,
                        SID_ATTR_LINE_DASH,
                        SID_ATTR_LINE_WIDTH,
                        SID_ATTR_LINE_COLOR,
                        0 };

        pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );

        delete pDlg;
        delete pNewAttr;
    }

    rReq.Ignore ();
}

void FuLine::Activate()
{
}

void FuLine::Deactivate()
{
}

} // end of namespace sd
<|endoftext|>


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

#ifndef SD_FU_SLIDE_HIDE_HXX
#define SD_FU_SLIDE_HIDE_HXX

#ifndef SD_FU_SLIDE_HXX
#include "fuslid.hxx"
#endif

namespace sd {

/*************************************************************************
|*
|* selektierte Dias in der Show zeigen / nicht zeigen
|*
\************************************************************************/

class FuSlideHide
    : public FuSlide
{
public:
    TYPEINFO();

    FuSlideHide (
        ViewShell* pViewSh,
        ::sd::Window* pWin,
        ::sd::View* pView,
        SdDrawDocument* pDoc,
        SfxRequest& rReq);
    virtual ~FuSlideHide (void);
};

} // end of namespace sd

#endif

<commit_msg>INTEGRATION: CWS impressfunctions (1.4.40); FILE MERGED 2005/10/28 10:56:54 cl 1.4.40.1: #125341# reworked FuPoor classes to use refcounting<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fuslhide.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-12-14 17:16:41 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_FU_SLIDE_HIDE_HXX
#define SD_FU_SLIDE_HIDE_HXX

#ifndef SD_FU_SLIDE_HXX
#include "fuslid.hxx"
#endif

namespace sd {

/*************************************************************************
|*
|* selektierte Dias in der Show zeigen / nicht zeigen
|*
\************************************************************************/

class FuSlideHide
    : public FuSlide
{
public:
    TYPEINFO();

    static FunctionReference Create( SlideViewShell* pViewSh, ::sd::Window* pWin, SlideView* pView, SdDrawDocument* pDoc, SfxRequest& rReq );
    virtual void DoExecute( SfxRequest& rReq );

protected:
    FuSlideHide (
        ViewShell* pViewSh,
        ::sd::Window* pWin,
        ::sd::View* pView,
        SdDrawDocument* pDoc,
        SfxRequest& rReq);
    virtual ~FuSlideHide (void);
};

} // end of namespace sd

#endif

<|endoftext|>


<commit_before>/* smoothmove.cpp
 * Smooth motion source file
 */

#include "smoothmove.h"

// Constructor
SmoothMove::SmoothMove(boost::shared_ptr<AL::ALBroker> broker,
			 const std::string &name)
	: AL::ALModule(broker, name)
{
	// Set description, and bind each function
	setModuleDescription("Smooth movement testing module");

	functionName("harryDance", getName(), "Do a little dance");
	BIND_METHOD(SmoothMove::harryDance);

	functionName("moveTest", getName(), "Testing movement");
	BIND_METHOD(SmoothMove::moveTest);

	// Set broker parent IP and port
	pip = broker->getParentIP();
	pport = broker->getParentPort();
}

// Destructor
SmoothMove::~SmoothMove()
{
}

// init() - called as soon as the module is constructed
void SmoothMove::init()
{
}

void SmoothMove::moveTest()
{
	// Get brokers, and go to initial posture
	AL::ALMotionProxy motion(pip, pport);
	AL::ALRobotPostureProxy posture(pip, pport);

	posture.goToPosture("StandInit", 0.5f);

	int space       =  2; // FRAME_ROBOT
	int axisMask    = 63; // control all the effector's axes
	bool isAbsolute = false;

	// Lower the Torso and move to the side
	std::string torso = "Torso";
	std::string lArm  = "LArm";
	std::string rArm  = "RArm";
	std::vector<float> position(6, 0.0f);

	position[0] = 0.0f;
	position[1] = 0.0f;
	position[2] = 0.3f;
	position[3] = 0.0f;
	position[4] = 0.0f;
	position[5] = 0.0f;

	// Amplitude of oscillation
	float amplitude = 0.05f;

	// Oscillation time in seconds
	float freq 	= 8.0f;

	// Update time in milliseconds
	unsigned int update	= 50;

	// Max speed of robot movement
	float speed = 1.0f;

	for (float t = 0; t < freq * 2.0; t += 0.001 * update)
	{
		position[0] = amplitude * sin (2.0 * M_PI * t / freq);
		motion.setPosition(torso, space, position, speed, axisMask);
		qi::os::msleep(update);
	}
}

void SmoothMove::harryDance()
{
  	/** The name of the joint to be moved. */
  	const AL::ALValue jointName = "HeadYaw";

  	try {
    		/** Create a ALMotionProxy to call the methods to move NAO's head.
    		* Arguments for the constructor are:
    		* - IP adress of the robot
    		* - port on which NAOqi is listening, by default 9559
    		*/
    		AL::ALMotionProxy motion(pip, pport);

    		/** Make sure the head is stiff to be able to move it.
    		* To do so, make the stiffness go to the maximum in one second.
    		*/
    		/** Target stiffness. */
    		AL::ALValue stiffness = 1.0f;
    		/** Time (in seconds) to reach the target. */
    		AL::ALValue time = 1.0f;

    		/** Call the stiffness interpolation method. */
    		motion.stiffnessInterpolation(jointName, stiffness, time);

    		/** Remove the stiffness on the head. */
    		stiffness = 0.0f;
    		time = 1.0f;
    		motion.stiffnessInterpolation(jointName, stiffness, time);

    		AL::ALValue result = motion.getWalkArmsEnabled();

   		/*---------Harry's Edits-------*/
   		AL::ALValue names = "RShoulderPitch"; //String is the limb name
    		AL::ALValue names2 = "LShoulderPitch";
    		AL::ALValue angles = 1.0f; //Angle is in robot unit, f
    		AL::ALValue angles2 = 0.0f;
    		AL::ALValue times = 1.0f;
    		bool isAbsolute = true; // Tells robot the angle values are absolute
    		std::cout << "\nShoulder Pitch:\n";

    		for (int i = 0; i < 3; i++)
		{
        		//Function calls robot to move
        		motion.angleInterpolation(names, angles, times, isAbsolute);
        		motion.angleInterpolation(names2, angles2, times, isAbsolute);
        		//angles = 0.0f;
        		motion.angleInterpolation(names, angles2, times, isAbsolute);
        		motion.angleInterpolation(names2, angles, times, isAbsolute);
    		}

  		std::cout << "Shoulder Roll";
    		//Creates arrays of values to send to robot.
    		AL::ALValue angle_list, time_list;
    		angle_list = AL::ALValue::array(1.0f);
    		time_list = AL::ALValue::array(1.0f);

    		angle_list.clear();
    		time_list.clear();

    		angle_list.arraySetSize(2);
    		//Array lists angles to move through
    		angle_list[0] = AL::ALValue::array(-0.5f, 0.5f); //From -0.5 to 0.5
    		angle_list[1] = AL::ALValue::array(0.5f, -0.5f);

    		time_list.arraySetSize(2);
    		//Time arrays - unsure of what this does...
    		time_list[0] = AL::ALValue::array(1.0f, 2.0f);
    		time_list[1] = AL::ALValue::array(1.0f, 2.0f);

    		motion.angleInterpolation(names, angles, times, isAbsolute);
    		//Array tells robot what limbs to move
    		//All array[0] (angle, time) are assigned to the first limb
    		names = AL::ALValue::array("RShoulderRoll", "LShoulderRoll");

    		motion.angleInterpolation(names, angle_list, time_list, isAbsolute);
    		/*-------------------*/
  	}
  	catch (const AL::ALError& e)
	{
    		std::cerr << "Caught exception: " << e.what() << std::endl;
  	}
}

<commit_msg>Small smoothmove update<commit_after>/* smoothmove.cpp
 * Smooth motion source file
 */

#include "smoothmove.h"

// Constructor
SmoothMove::SmoothMove(boost::shared_ptr<AL::ALBroker> broker,
			 const std::string &name)
	: AL::ALModule(broker, name)
{
	// Set description, and bind each function
	setModuleDescription("Smooth movement testing module");

	functionName("harryDance", getName(), "Do a little dance");
	BIND_METHOD(SmoothMove::harryDance);

	functionName("moveTest", getName(), "Testing movement");
	BIND_METHOD(SmoothMove::moveTest);

	// Set broker parent IP and port
	pip = broker->getParentIP();
	pport = broker->getParentPort();
}

// Destructor
SmoothMove::~SmoothMove()
{
}

// init() - called as soon as the module is constructed
void SmoothMove::init()
{
}

void SmoothMove::moveTest()
{
	// Get brokers, and go to initial posture
	AL::ALMotionProxy motion(pip, pport);
	AL::ALRobotPostureProxy posture(pip, pport);

	posture.goToPosture("StandInit", 0.5f);

	int space       =  2; // FRAME_ROBOT
	int axisMask    = 63; // control all the effector's axes
	bool isAbsolute = false;

	// Lower the Torso and move to the side
	std::string torso = "Torso";
	std::string lArm  = "LArm";
	std::string rArm  = "RArm";
	std::vector<float> position(6, 0.0f);

	position[0] = 0.0f;
	position[1] = 0.0f;
	position[2] = 0.3f;
	position[3] = 0.0f;
	position[4] = 0.0f;
	position[5] = 0.0f;

	// Amplitude of oscillation
	float amplitude = 0.05f;

	// Oscillation time in seconds
	float freq 	= 4.0f;

	// Update time in milliseconds
	unsigned int update	= 50;

	// Max speed of robot movement
	float speed = 1.0f;

	// Go to initial position
	motion.setPosition(torso, space, position, speed, axisMask);
	qi::os::sleep(1.0f);

	for (float t = 0; t < freq * 2.0; t += 0.001 * update)
	{
		position[0] = amplitude * sin (2.0 * M_PI * t / freq);
		motion.setPosition(torso, space, position, speed, axisMask);
		qi::os::msleep(update);
	}
}

void SmoothMove::harryDance()
{
  	/** The name of the joint to be moved. */
  	const AL::ALValue jointName = "HeadYaw";

  	try {
    		/** Create a ALMotionProxy to call the methods to move NAO's head.
    		* Arguments for the constructor are:
    		* - IP adress of the robot
    		* - port on which NAOqi is listening, by default 9559
    		*/
    		AL::ALMotionProxy motion(pip, pport);

    		/** Make sure the head is stiff to be able to move it.
    		* To do so, make the stiffness go to the maximum in one second.
    		*/
    		/** Target stiffness. */
    		AL::ALValue stiffness = 1.0f;
    		/** Time (in seconds) to reach the target. */
    		AL::ALValue time = 1.0f;

    		/** Call the stiffness interpolation method. */
    		motion.stiffnessInterpolation(jointName, stiffness, time);

    		/** Remove the stiffness on the head. */
    		stiffness = 0.0f;
    		time = 1.0f;
    		motion.stiffnessInterpolation(jointName, stiffness, time);

    		AL::ALValue result = motion.getWalkArmsEnabled();

   		/*---------Harry's Edits-------*/
   		AL::ALValue names = "RShoulderPitch"; //String is the limb name
    		AL::ALValue names2 = "LShoulderPitch";
    		AL::ALValue angles = 1.0f; //Angle is in robot unit, f
    		AL::ALValue angles2 = 0.0f;
    		AL::ALValue times = 1.0f;
    		bool isAbsolute = true; // Tells robot the angle values are absolute
    		std::cout << "\nShoulder Pitch:\n";

    		for (int i = 0; i < 3; i++)
		{
        		//Function calls robot to move
        		motion.angleInterpolation(names, angles, times, isAbsolute);
        		motion.angleInterpolation(names2, angles2, times, isAbsolute);
        		//angles = 0.0f;
        		motion.angleInterpolation(names, angles2, times, isAbsolute);
        		motion.angleInterpolation(names2, angles, times, isAbsolute);
    		}

  		std::cout << "Shoulder Roll";
    		//Creates arrays of values to send to robot.
    		AL::ALValue angle_list, time_list;
    		angle_list = AL::ALValue::array(1.0f);
    		time_list = AL::ALValue::array(1.0f);

    		angle_list.clear();
    		time_list.clear();

    		angle_list.arraySetSize(2);
    		//Array lists angles to move through
    		angle_list[0] = AL::ALValue::array(-0.5f, 0.5f); //From -0.5 to 0.5
    		angle_list[1] = AL::ALValue::array(0.5f, -0.5f);

    		time_list.arraySetSize(2);
    		//Time arrays - unsure of what this does...
    		time_list[0] = AL::ALValue::array(1.0f, 2.0f);
    		time_list[1] = AL::ALValue::array(1.0f, 2.0f);

    		motion.angleInterpolation(names, angles, times, isAbsolute);
    		//Array tells robot what limbs to move
    		//All array[0] (angle, time) are assigned to the first limb
    		names = AL::ALValue::array("RShoulderRoll", "LShoulderRoll");

    		motion.angleInterpolation(names, angle_list, time_list, isAbsolute);
    		/*-------------------*/
  	}
  	catch (const AL::ALError& e)
	{
    		std::cerr << "Caught exception: " << e.what() << std::endl;
  	}
}

<|endoftext|>