<commit_before>/******************************
 * Qt player using libVLC     *
 * By protonux                *
 *                            *
 * Under WTFPL                *
 ******************************/
#include "player.h"
#include <vlc/vlc.h>

#define qtu( i ) ((i).toUtf8().constData())

#include <QtGui>

Mwindow::Mwindow() {
    vlcPlayer = NULL;

    /* Init libVLC */
    if((vlcObject = libvlc_new(0,NULL)) == NULL) {
        printf("Could not init libVLC");
        exit(1);
    }

    /* Display libVLC version */
    printf("libVLC version: %s\n",libvlc_get_version());

    /* Interface initialisation */
    initMenus();
    initComponents();
}

Mwindow::~Mwindow() {
    if(vlcObject)
        libvlc_release(vlcObject);
}

void Mwindow::initMenus() {

    centralWidget = new QWidget;

    videoWidget = new QWidget;
    videoWidget->setAutoFillBackground( true );
    QPalette plt = palette();
    plt.setColor( QPalette::Window, Qt::black );
    videoWidget->setPalette( plt );

    QMenu *fileMenu = menuBar()->addMenu("&File");
    QMenu *editMenu = menuBar()->addMenu("&Edit");

    QAction *Open = new QAction("&Open", this);
    QAction *Quit = new QAction("&Quit", this);
    QAction *playAc = new QAction("&Play/Pause", this);

    Open->setShortcut(QKeySequence("Ctrl+O"));
    Quit->setShortcut(QKeySequence("Ctrl+Q"));

    fileMenu->addAction(Open);
    fileMenu->addAction(Quit);
    editMenu->addAction(playAc);

    connect(Open, SIGNAL(triggered()), this, SLOT(openFile()));
    connect(playAc, SIGNAL(triggered()), this, SLOT(play()));
    connect(Quit, SIGNAL(triggered()), qApp, SLOT(quit()));
}

void Mwindow::initComponents() {

    playBut = new QPushButton("Play");
    QObject::connect(playBut, SIGNAL(clicked()), this, SLOT(play()));

    stopBut = new QPushButton("Stop");
    QObject::connect(stopBut, SIGNAL(clicked()), this, SLOT(stop()));

    muteBut = new QPushButton("Mute");
    QObject::connect(muteBut, SIGNAL(clicked()), this, SLOT(mute()));

    volumeSlider = new QSlider(Qt::Horizontal);
    QObject::connect(volumeSlider, SIGNAL(sliderMoved(int)), this, SLOT(changeVolume(int)));
    volumeSlider->setValue(80);

    slider = new QSlider(Qt::Horizontal);
    slider->setMaximum(1000);
    QObject::connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(changePosition(int)));

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(updateInterface()));
    timer->start(100);

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(playBut);
    layout->addWidget(stopBut);
    layout->addWidget(muteBut);
    layout->addWidget(volumeSlider);

    QVBoxLayout *layout2 = new QVBoxLayout;
    layout2->addWidget(videoWidget);
    layout2->addWidget(slider);
    layout2->addLayout(layout);

    centralWidget->setLayout(layout2);
    setCentralWidget(centralWidget);
    resize( 600, 400);
}

void Mwindow::openFile() {
    /* Just the basic file-select box */
    QString fileOpen = QFileDialog::getOpenFileName(this,tr("Load a file"), "~");

    /* Stop if something is playing */
    if( vlcPlayer && libvlc_media_player_is_playing(vlcPlayer) )
        stop();

    /* New Media */
    libvlc_media_t *vlcMedia = libvlc_media_new_path(vlcObject,qtu(fileOpen));
    if( !vlcMedia )
        return;

    vlcPlayer = libvlc_media_player_new_from_media (vlcMedia);
    libvlc_media_release(vlcMedia);

    /* Integrate the video in the interface */
#if defined(Q_OS_MAC)
    libvlc_media_player_set_nsobject(vlcPlayer, videoWidget->winId());
#elif defined(Q_OS_UNIX)
    libvlc_media_player_set_xwindow(vlcPlayer, videoWidget->winId());
#elif defined(Q_OS_WIN)
    libvlc_media_player_set_hwnd(vlcPlayer, videoWidget->winId());
#endif

    /* And play */
    libvlc_media_player_play (vlcPlayer);

    //Set vars and text correctly
    playBut->setText("Pause");
}

void Mwindow::play() {

    if(vlcPlayer)
    {
        if (libvlc_media_player_is_playing(vlcPlayer))
        {
            libvlc_media_player_pause(vlcPlayer);
            playBut->setText("Play");
        }
        else
        {
            libvlc_media_player_play(vlcPlayer);
            playBut->setText("Pause");
        }
    }
}

int Mwindow::changeVolume(int vol) { //Called if you change the volume slider

    if(vlcPlayer)
        return libvlc_audio_set_volume (vlcPlayer,vol);

    return 0;
}

void Mwindow::changePosition(int pos) { //Called if you change the position slider

    if(vlcPlayer) //It segfault if vlcPlayer don't exist
        libvlc_media_player_set_position(vlcPlayer,(float)pos/(float)1000);
}

void Mwindow::updateInterface() { //Update interface and check if song is finished

    if(vlcPlayer) //It segfault if vlcPlayer don't exist
    {
        /* update the timeline */
        float pos = libvlc_media_player_get_position(vlcPlayer);
        int siderPos=(int)(pos*(float)(1000));
        slider->setValue(siderPos);

        /* Stop the media */
        if (libvlc_media_player_get_state(vlcPlayer) == 6) { this->stop(); }
    }
}

void Mwindow::stop() {
    if(vlcPlayer) {
        libvlc_media_player_stop(vlcPlayer);
        libvlc_media_player_release(vlcPlayer);
        slider->setValue(0);
        playBut->setText("Play");
    }
    vlcPlayer = NULL;
}

void Mwindow::mute() {
    if(vlcPlayer) {
        if(volumeSlider->value() == 0) { //if already muted...

                this->changeVolume(80);
                volumeSlider->setValue(80);

        } else { //else mute volume

                this->changeVolume(0);
                volumeSlider->setValue(0);

        }
    }
}

void Mwindow::closeEvent(QCloseEvent *event) {
    stop();
    event->accept();
}
<commit_msg>Doc: QtPlayer example: fix MacOS build with Qt4.8<commit_after>/******************************
 * Qt player using libVLC     *
 * By protonux                *
 *                            *
 * Under WTFPL                *
 ******************************/
#include "player.h"
#include <vlc/vlc.h>

#define qtu( i ) ((i).toUtf8().constData())

#include <QtGui>

Mwindow::Mwindow() {
    vlcPlayer = NULL;

    /* Init libVLC */
    if((vlcObject = libvlc_new(0,NULL)) == NULL) {
        printf("Could not init libVLC");
        exit(1);
    }

    /* Display libVLC version */
    printf("libVLC version: %s\n",libvlc_get_version());

    /* Interface initialisation */
    initMenus();
    initComponents();
}

Mwindow::~Mwindow() {
    if(vlcObject)
        libvlc_release(vlcObject);
}

void Mwindow::initMenus() {

    centralWidget = new QWidget;

    videoWidget = new QWidget;
    videoWidget->setAutoFillBackground( true );
    QPalette plt = palette();
    plt.setColor( QPalette::Window, Qt::black );
    videoWidget->setPalette( plt );

    QMenu *fileMenu = menuBar()->addMenu("&File");
    QMenu *editMenu = menuBar()->addMenu("&Edit");

    QAction *Open = new QAction("&Open", this);
    QAction *Quit = new QAction("&Quit", this);
    QAction *playAc = new QAction("&Play/Pause", this);

    Open->setShortcut(QKeySequence("Ctrl+O"));
    Quit->setShortcut(QKeySequence("Ctrl+Q"));

    fileMenu->addAction(Open);
    fileMenu->addAction(Quit);
    editMenu->addAction(playAc);

    connect(Open, SIGNAL(triggered()), this, SLOT(openFile()));
    connect(playAc, SIGNAL(triggered()), this, SLOT(play()));
    connect(Quit, SIGNAL(triggered()), qApp, SLOT(quit()));
}

void Mwindow::initComponents() {

    playBut = new QPushButton("Play");
    QObject::connect(playBut, SIGNAL(clicked()), this, SLOT(play()));

    stopBut = new QPushButton("Stop");
    QObject::connect(stopBut, SIGNAL(clicked()), this, SLOT(stop()));

    muteBut = new QPushButton("Mute");
    QObject::connect(muteBut, SIGNAL(clicked()), this, SLOT(mute()));

    volumeSlider = new QSlider(Qt::Horizontal);
    QObject::connect(volumeSlider, SIGNAL(sliderMoved(int)), this, SLOT(changeVolume(int)));
    volumeSlider->setValue(80);

    slider = new QSlider(Qt::Horizontal);
    slider->setMaximum(1000);
    QObject::connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(changePosition(int)));

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(updateInterface()));
    timer->start(100);

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(playBut);
    layout->addWidget(stopBut);
    layout->addWidget(muteBut);
    layout->addWidget(volumeSlider);

    QVBoxLayout *layout2 = new QVBoxLayout;
    layout2->addWidget(videoWidget);
    layout2->addWidget(slider);
    layout2->addLayout(layout);

    centralWidget->setLayout(layout2);
    setCentralWidget(centralWidget);
    resize( 600, 400);
}

void Mwindow::openFile() {
    /* Just the basic file-select box */
    QString fileOpen = QFileDialog::getOpenFileName(this,tr("Load a file"), "~");

    /* Stop if something is playing */
    if( vlcPlayer && libvlc_media_player_is_playing(vlcPlayer) )
        stop();

    /* New Media */
    libvlc_media_t *vlcMedia = libvlc_media_new_path(vlcObject,qtu(fileOpen));
    if( !vlcMedia )
        return;

    vlcPlayer = libvlc_media_player_new_from_media (vlcMedia);
    libvlc_media_release(vlcMedia);

    /* Integrate the video in the interface */
#if defined(Q_OS_MAC)
    libvlc_media_player_set_nsobject(vlcPlayer, (void *) videoWidget->winId());
#elif defined(Q_OS_UNIX)
    libvlc_media_player_set_xwindow(vlcPlayer, videoWidget->winId());
#elif defined(Q_OS_WIN)
    libvlc_media_player_set_hwnd(vlcPlayer, videoWidget->winId());
#endif

    /* And play */
    libvlc_media_player_play (vlcPlayer);

    //Set vars and text correctly
    playBut->setText("Pause");
}

void Mwindow::play() {

    if(vlcPlayer)
    {
        if (libvlc_media_player_is_playing(vlcPlayer))
        {
            libvlc_media_player_pause(vlcPlayer);
            playBut->setText("Play");
        }
        else
        {
            libvlc_media_player_play(vlcPlayer);
            playBut->setText("Pause");
        }
    }
}

int Mwindow::changeVolume(int vol) { //Called if you change the volume slider

    if(vlcPlayer)
        return libvlc_audio_set_volume (vlcPlayer,vol);

    return 0;
}

void Mwindow::changePosition(int pos) { //Called if you change the position slider

    if(vlcPlayer) //It segfault if vlcPlayer don't exist
        libvlc_media_player_set_position(vlcPlayer,(float)pos/(float)1000);
}

void Mwindow::updateInterface() { //Update interface and check if song is finished

    if(vlcPlayer) //It segfault if vlcPlayer don't exist
    {
        /* update the timeline */
        float pos = libvlc_media_player_get_position(vlcPlayer);
        int siderPos=(int)(pos*(float)(1000));
        slider->setValue(siderPos);

        /* Stop the media */
        if (libvlc_media_player_get_state(vlcPlayer) == 6) { this->stop(); }
    }
}

void Mwindow::stop() {
    if(vlcPlayer) {
        libvlc_media_player_stop(vlcPlayer);
        libvlc_media_player_release(vlcPlayer);
        slider->setValue(0);
        playBut->setText("Play");
    }
    vlcPlayer = NULL;
}

void Mwindow::mute() {
    if(vlcPlayer) {
        if(volumeSlider->value() == 0) { //if already muted...

                this->changeVolume(80);
                volumeSlider->setValue(80);

        } else { //else mute volume

                this->changeVolume(0);
                volumeSlider->setValue(0);

        }
    }
}

void Mwindow::closeEvent(QCloseEvent *event) {
    stop();
    event->accept();
}
<|endoftext|>


<commit_before><commit_msg>print message before calling the start function.<commit_after><|endoftext|>


<commit_before>namespace mant {
  namespace robotic {
    class ParallelKinematicMachine3PRRR {
      public:
        inline explicit ParallelKinematicMachine3PRRR() noexcept;

        inline arma::Mat<double>::fixed<2, 3> getLinkLengths() const noexcept;

        inline void setLinkLengths(
            const arma::Mat<double>::fixed<2, 3>& linkLengths) noexcept;

        inline arma::Mat<double>::fixed<2, 3> getEndEffectorJointPositions() const noexcept;

        inline void setEndEffectorJointPositions(
            const arma::Mat<double>::fixed<2, 3>& endEffectorJointPositions) noexcept;

        inline arma::Mat<double>::fixed<2, 3> getRedundantJointPositionStarts() const noexcept;

        inline void setRedundantJointPositionStarts(
            const arma::Mat<double>::fixed<2, 3>& redundantJointPositionStarts) noexcept;

        inline arma::Mat<double>::fixed<2, 3> getRedundantJointPositionEnds() const noexcept;

        inline void setRedundantJointPositionEnds(
            const arma::Mat<double>::fixed<2, 3>& redundantJointPositionEnds) noexcept;

        inline std::vector<arma::Mat<double>::fixed<2, 3>> getModel(
            const arma::Col<double>::fixed<3>& endEffectorPose,
            const arma::Col<double>& redundantJointActuations) const;

        inline arma::Col<double>::fixed<3> getActuation(
            const arma::Col<double>::fixed<3>& endEffectorPose,
            const arma::Col<double>& redundantJointActuations) const;

        inline arma::Col<double>::fixed<3> getEndEffectorPose(
            const arma::Col<double>::fixed<3>& actuations,
            const arma::Col<double>& redundantJointActuations) const;

        inline double getEndEffectorPoseAccuracy(
            const arma::Col<double>::fixed<3>& endEffectorPose,
            const arma::Col<double>& redundantJointActuations) const;

        arma::Mat<double>::fixed<2, 3> endEffectorJointPositions_;
        arma::Mat<double>::fixed<2, 3> linkLengths_;

        arma::Mat<double>::fixed<2, 3> redundantJointPositionStarts_;
        arma::Mat<double>::fixed<2, 3> redundantJointPositionEnds_;

        arma::Mat<double>::fixed<2, 3> redundantJointPositionStartToEnds_;

        arma::Col<unsigned int> redundantJointIndicies_;
        arma::Col<double> redundantJointAngleSines_;
        arma::Col<double> redundantJointAngleCosines_;
    };

    //
    // Implementation
    //

    inline ParallelKinematicMachine3PRRR::ParallelKinematicMachine3PRRR() noexcept {
      setLinkLengths({
        -0.000066580445834, 0.106954081945581,
        -0.092751709777083, -0.053477040972790,
        0.092818290222917, -0.053477040972790});

      setEndEffectorJointPositions({
        0.6, 0.6,
        0.6, 0.6,
        0.6, 0.6});

      setRedundantJointPositionStarts({
        0.1, 1.0392,
        0.0, 0.8,
        1.2, 0.8
      });

      setRedundantJointPositionEnds({
        1.1, 1.0392,
        0.0, -0.2,
        1.2, -0.2});

      redundantJointPositionStartToEnds_ = redundantJointEnds_ - redundantJointStarts_;
      redundantJointIndicies_ = arma::find(arma::any(redundantJointsStartToEnd_));

      redundantJointAngleSines_.set_size(redundantJointIndicies_.n_elem);
      redundantJointAngleCosines_.set_size(redundantJointIndicies_.n_elem);

      for (std::size_t n = 0; n < redundantJointIndicies_.n_elem; ++n) {
        const double redundantJointAngle = std::atan2(redundantJointPositionStartToEnds_.at(1, n), redundantJointPositionStartToEnds_.at(0, n));
        redundantJointAngleSines_.at(n) = std::sin(redundantJointAngle);
        redundantJointAngleCosines_.at(n) = std::cos(redundantJointAngle);
      }
    }

    inline arma::Mat<double>::fixed<2, 3> ParallelKinematicMachine3PRRR::getLinkLengths() const noexcept {
      return linkLengths_;
    }

    inline void ParallelKinematicMachine3PRRR::setLinkLengths(
        const arma::Mat<double>::fixed<2, 3>& linkLengths) noexcept {
      linkLengths_ = linkLengths;
    }

    inline arma::Mat<double>::fixed<2, 3> ParallelKinematicMachine3PRRR::getEndEffectorJointPositions() const noexcept {
      return endEffectorJointPositions_;
    }

    inline void ParallelKinematicMachine3PRRR::setEndEffectorJointPositions(
        const arma::Mat<double>::fixed<2, 3>& endEffectorJointPositions) noexcept {
      endEffectorJointPositions_ = endEffectorJointPositions;
    }

    inline arma::Mat<double>::fixed<2, 3> ParallelKinematicMachine3PRRR::getRedundantJointPositionStarts() const noexcept {
      return redundantJointPositionStarts_;
    }

    inline void ParallelKinematicMachine3PRRR::setRedundantJointPositionStarts(
        const arma::Mat<double>::fixed<2, 3>& redundantJointPositionStarts) noexcept {
      redundantJointPositionStarts_ = redundantJointPositionStarts;
    }

    inline arma::Mat<double>::fixed<2, 3> ParallelKinematicMachine3PRRR::getRedundantJointPositionEnds() const noexcept {
      return redundantJointPositionEnds_;
    }

    inline void ParallelKinematicMachine3PRRR::setRedundantJointPositionEnds(
        const arma::Mat<double>::fixed<2, 3>& redundantJointPositionEnds) noexcept {
      redundantJointPositionEnds_ = redundantJointPositionEnds;
    }

    inline std::vector<arma::Mat<double>::fixed<2, 3>> ParallelKinematicMachine3PRRR::getModel(
        const arma::Col<double>::fixed<3>& endEffectorPose,
        const arma::Col<double>& redundantJointActuations) const {
      if (arma::any(arma::vectorise(redundantJointActuations < 0)) || arma::any(arma::vectorise(redundantJointActuations > 1))) {
        throw std::logic_error("All values for the actuation of redundantion joints must be between [0, 1].");
      }

      const arma::Col<double>::fixed<2>& endEffectorPosition = endEffectorPose.subvec(0, 1);
      const double& endEffectorAngle = endEffectorPose.at(2);

      arma::Mat<double>::fixed<2, 3> baseJoints = redundantJointStarts_;
      for (std::size_t n = 0; n < redundantJointIndicies_.n_elem; n++) {
        const unsigned int& redundantJointIndex = redundantJointIndicies_.at(n);
        baseJoints.col(redundantJointIndex) += redundantJointActuations.at(redundantJointIndex) * redundantJointsStartToEnd_.col(redundantJointIndex);
      }

      arma::Mat<double>::fixed<2, 3> endEffectorJoints = get2DRotationMatrix(endEffectorAngle) * endEffectorJointsRelative_;
      endEffectorJoints.each_col() += endEffectorPosition;

      arma::Mat<double>::fixed<2, 3> passiveJoints;
      for (std::size_t n = 0; n < baseJoints.n_cols; ++n) {
        passiveJoints.col(n) = getCircleCircleIntersection(baseJoints.col(n), linkLengths_.at(0, n), endEffectorJoints.col(n), linkLengths_.at(1, n));
      }

      std::vector<arma::Mat<double>::fixed<2, 3>> model;

      model.push_back(baseJoints);
      model.push_back(passiveJoints);
      model.push_back(endEffectorJoints);

      return model;
    }

    inline arma::Col<double>::fixed<3> ParallelKinematicMachine3PRRR::getActuation(
        const arma::Col<double>::fixed<3>& endEffectorPose,
        const arma::Col<double>& redundantJointActuations) const {
      const std::vector<arma::Mat<double>::fixed<2, 3>>& model = getModel(endEffectorPose, redundantJointActuations);

      const arma::Mat<double>::fixed<2, 3>& baseJointPositions = model.at(0);
      const arma::Mat<double>::fixed<2, 3>& passiveJointPositions = model.at(1);

      const arma::Mat<double>::fixed<2, 3>& baseToPassiveJointPositions = passiveJointPositions - baseJointPositions;

      arma::Row<double>::fixed<3> actuation;
      for (std::size_t n = 0; n < baseToPassiveJointPositions.n_elem; ++n) {
        actuation.at(n) = std::atan2(baseToPassiveJointPositions.at(1, n), baseToPassiveJointPositions.at(0, n));
      }

      return actuation;
    }

    inline arma::Col<double>::fixed<3> ParallelKinematicMachine3PRRR::getEndEffectorPose(
        const arma::Col<double>::fixed<3>& actuations,
        const arma::Col<double>& redundantJointActuations) const {
      // TODO Direct kinematic (estimate position, using a simple HillCLimber algorithm)
    }

    inline double ParallelKinematicMachine3PRRR::getEndEffectorPoseAccuracy(
        const arma::Col<double>::fixed<3>& endEffectorPose,
        const arma::Col<double>& redundantJointActuations) const {
      const std::vector<arma::Mat<double>::fixed<2, 3>>& model = getModel(endEffectorPose, redundantJointActuations);

      const arma::Mat<double>::fixed<2, 3>& baseJoints = modelCharacterisation.at(0);

      const arma::Mat<double>::fixed<2, 3>& endEffectorJoints = model.at(2);
      arma::Mat<double>::fixed<2, 3> endEffectorJointsRotated = endEffectorJoints;
      endEffectorJointsRotated.each_col() -= endEffectorPose.subvec(0, 1);

      const arma::Mat<double>::fixed<2, 3>& passiveJoints = model.at(1);

      arma::Mat<double>::fixed<3, 3> forwardKinematic;
      forwardKinematic.rows(0, 1) = endEffectorJoints - passiveJoints;
      forwardKinematic.row(2) = -forwardKinematic.row(0) % endEffectorJointsRotated.row(1) + forwardKinematic.row(1) % endEffectorJointsRotated.row(0);

      const arma::Mat<double>::fixed<2, 3>& baseToPassiveJoints = passiveJoints - baseJoints;
      arma::Mat<double> inverseKinematic(3, 3 + redundantJointIndicies_.n_elem, arma::fill::zeros);
      inverseKinematic.diag() = forwardKinematic.row(0) % baseToPassiveJoints.row(1) - forwardKinematic.row(1) % baseToPassiveJoints.row(0);
      for (std::size_t n = 0; n < redundantJointIndicies_.n_elem; ++n) {
        const unsigned int& redundantJointIndex = redundantJointIndicies_.at(n);
        inverseKinematic.at(n, 3 + n) = -(forwardKinematic.at(redundantJointIndex, 0) * redundantJointAnglesCosine_.at(n) + forwardKinematic.at(redundantJointIndex, 1) * redundantJointAnglesSine_.at(n));
      }

      return -1.0 / arma::cond(arma::solve(forwardKinematic.t(), inverseKinematic));
    }
  }
}
<commit_msg>devel: Fixed some minor naming errors, introduced by previous changes<commit_after>namespace mant {
  namespace robotic {
    class ParallelKinematicMachine3PRRR {
      public:
        inline explicit ParallelKinematicMachine3PRRR() noexcept;

        inline arma::Mat<double>::fixed<2, 3> getLinkLengths() const noexcept;

        inline void setLinkLengths(
            const arma::Mat<double>::fixed<2, 3>& linkLengths) noexcept;

        inline arma::Mat<double>::fixed<2, 3> getEndEffectorJointPositions() const noexcept;

        inline void setEndEffectorJointPositions(
            const arma::Mat<double>::fixed<2, 3>& endEffectorJointPositions) noexcept;

        inline arma::Mat<double>::fixed<2, 3> getRedundantJointPositionStarts() const noexcept;

        inline void setRedundantJointPositionStarts(
            const arma::Mat<double>::fixed<2, 3>& redundantJointPositionStarts) noexcept;

        inline arma::Mat<double>::fixed<2, 3> getRedundantJointPositionEnds() const noexcept;

        inline void setRedundantJointPositionEnds(
            const arma::Mat<double>::fixed<2, 3>& redundantJointPositionEnds) noexcept;

        inline std::vector<arma::Mat<double>::fixed<2, 3>> getModel(
            const arma::Col<double>::fixed<3>& endEffectorPose,
            const arma::Col<double>& redundantJointActuations) const;

        inline arma::Col<double>::fixed<3> getActuation(
            const arma::Col<double>::fixed<3>& endEffectorPose,
            const arma::Col<double>& redundantJointActuations) const;

        inline arma::Col<double>::fixed<3> getEndEffectorPose(
            const arma::Col<double>::fixed<3>& actuations,
            const arma::Col<double>& redundantJointActuations) const;

        inline double getEndEffectorPoseAccuracy(
            const arma::Col<double>::fixed<3>& endEffectorPose,
            const arma::Col<double>& redundantJointActuations) const;

        arma::Mat<double>::fixed<2, 3> endEffectorJointPositions_;
        arma::Mat<double>::fixed<2, 3> linkLengths_;

        arma::Mat<double>::fixed<2, 3> redundantJointPositionStarts_;
        arma::Mat<double>::fixed<2, 3> redundantJointPositionEnds_;

        arma::Mat<double>::fixed<2, 3> redundantJointPositionStartToEnds_;

        arma::Col<unsigned int> redundantJointIndicies_;
        arma::Col<double> redundantJointAngleSines_;
        arma::Col<double> redundantJointAngleCosines_;
    };

    //
    // Implementation
    //

    inline ParallelKinematicMachine3PRRR::ParallelKinematicMachine3PRRR() noexcept {
      setLinkLengths({
        -0.000066580445834, 0.106954081945581,
        -0.092751709777083, -0.053477040972790,
        0.092818290222917, -0.053477040972790});

      setEndEffectorJointPositions({
        0.6, 0.6,
        0.6, 0.6,
        0.6, 0.6});

      setRedundantJointPositionStarts({
        0.1, 1.0392,
        0.0, 0.8,
        1.2, 0.8
      });

      setRedundantJointPositionEnds({
        1.1, 1.0392,
        0.0, -0.2,
        1.2, -0.2});

      redundantJointPositionStartToEnds_ = redundantJointPositionEnds_ - redundantJointPositionStarts_;
      redundantJointIndicies_ = arma::find(arma::any(redundantJointPositionStartToEnds_));

      redundantJointAngleSines_.set_size(redundantJointIndicies_.n_elem);
      redundantJointAngleCosines_.set_size(redundantJointIndicies_.n_elem);

      for (std::size_t n = 0; n < redundantJointIndicies_.n_elem; ++n) {
        const double redundantJointAngle = std::atan2(redundantJointPositionStartToEnds_.at(1, n), redundantJointPositionStartToEnds_.at(0, n));
        redundantJointAngleSines_.at(n) = std::sin(redundantJointAngle);
        redundantJointAngleCosines_.at(n) = std::cos(redundantJointAngle);
      }
    }

    inline arma::Mat<double>::fixed<2, 3> ParallelKinematicMachine3PRRR::getLinkLengths() const noexcept {
      return linkLengths_;
    }

    inline void ParallelKinematicMachine3PRRR::setLinkLengths(
        const arma::Mat<double>::fixed<2, 3>& linkLengths) noexcept {
      linkLengths_ = linkLengths;
    }

    inline arma::Mat<double>::fixed<2, 3> ParallelKinematicMachine3PRRR::getEndEffectorJointPositions() const noexcept {
      return endEffectorJointPositions_;
    }

    inline void ParallelKinematicMachine3PRRR::setEndEffectorJointPositions(
        const arma::Mat<double>::fixed<2, 3>& endEffectorJointPositions) noexcept {
      endEffectorJointPositions_ = endEffectorJointPositions;
    }

    inline arma::Mat<double>::fixed<2, 3> ParallelKinematicMachine3PRRR::getRedundantJointPositionStarts() const noexcept {
      return redundantJointPositionStarts_;
    }

    inline void ParallelKinematicMachine3PRRR::setRedundantJointPositionStarts(
        const arma::Mat<double>::fixed<2, 3>& redundantJointPositionStarts) noexcept {
      redundantJointPositionStarts_ = redundantJointPositionStarts;
    }

    inline arma::Mat<double>::fixed<2, 3> ParallelKinematicMachine3PRRR::getRedundantJointPositionEnds() const noexcept {
      return redundantJointPositionEnds_;
    }

    inline void ParallelKinematicMachine3PRRR::setRedundantJointPositionEnds(
        const arma::Mat<double>::fixed<2, 3>& redundantJointPositionEnds) noexcept {
      redundantJointPositionEnds_ = redundantJointPositionEnds;
    }

    inline std::vector<arma::Mat<double>::fixed<2, 3>> ParallelKinematicMachine3PRRR::getModel(
        const arma::Col<double>::fixed<3>& endEffectorPose,
        const arma::Col<double>& redundantJointActuations) const {
      if (arma::any(arma::vectorise(redundantJointActuations < 0)) || arma::any(arma::vectorise(redundantJointActuations > 1))) {
        throw std::logic_error("All values for the actuation of redundantion joints must be between [0, 1].");
      }

      const arma::Col<double>::fixed<2>& endEffectorPosition = endEffectorPose.subvec(0, 1);
      const double& endEffectorAngle = endEffectorPose.at(2);

      arma::Mat<double>::fixed<2, 3> baseJoints = redundantJointPositionStarts_;
      for (std::size_t n = 0; n < redundantJointIndicies_.n_elem; n++) {
        const unsigned int& redundantJointIndex = redundantJointIndicies_.at(n);
        baseJoints.col(redundantJointIndex) += redundantJointActuations.at(redundantJointIndex) * redundantJointPositionStartToEnds_.col(redundantJointIndex);
      }

      arma::Mat<double>::fixed<2, 3> endEffectorJoints = get2DRotationMatrix(endEffectorAngle) * endEffectorJointPositions_;
      endEffectorJoints.each_col() += endEffectorPosition;

      arma::Mat<double>::fixed<2, 3> passiveJoints;
      for (std::size_t n = 0; n < baseJoints.n_cols; ++n) {
        passiveJoints.col(n) = getCircleCircleIntersection(baseJoints.col(n), linkLengths_.at(0, n), endEffectorJoints.col(n), linkLengths_.at(1, n));
      }

      std::vector<arma::Mat<double>::fixed<2, 3>> model;

      model.push_back(baseJoints);
      model.push_back(passiveJoints);
      model.push_back(endEffectorJoints);

      return model;
    }

    inline arma::Col<double>::fixed<3> ParallelKinematicMachine3PRRR::getActuation(
        const arma::Col<double>::fixed<3>& endEffectorPose,
        const arma::Col<double>& redundantJointActuations) const {
      const std::vector<arma::Mat<double>::fixed<2, 3>>& model = getModel(endEffectorPose, redundantJointActuations);

      const arma::Mat<double>::fixed<2, 3>& baseJointPositions = model.at(0);
      const arma::Mat<double>::fixed<2, 3>& passiveJointPositions = model.at(1);

      const arma::Mat<double>::fixed<2, 3>& baseToPassiveJointPositions = passiveJointPositions - baseJointPositions;

      arma::Row<double>::fixed<3> actuation;
      for (std::size_t n = 0; n < baseToPassiveJointPositions.n_elem; ++n) {
        actuation.at(n) = std::atan2(baseToPassiveJointPositions.at(1, n), baseToPassiveJointPositions.at(0, n));
      }

      return actuation;
    }

    inline arma::Col<double>::fixed<3> ParallelKinematicMachine3PRRR::getEndEffectorPose(
        const arma::Col<double>::fixed<3>& actuations,
        const arma::Col<double>& redundantJointActuations) const {
      // TODO Direct kinematic (estimate position, using a simple HillCLimber algorithm)
    }

    inline double ParallelKinematicMachine3PRRR::getEndEffectorPoseAccuracy(
        const arma::Col<double>::fixed<3>& endEffectorPose,
        const arma::Col<double>& redundantJointActuations) const {
      const std::vector<arma::Mat<double>::fixed<2, 3>>& model = getModel(endEffectorPose, redundantJointActuations);

      const arma::Mat<double>::fixed<2, 3>& baseJoints = model.at(0);

      const arma::Mat<double>::fixed<2, 3>& endEffectorJoints = model.at(2);
      arma::Mat<double>::fixed<2, 3> endEffectorJointsRotated = endEffectorJoints;
      endEffectorJointsRotated.each_col() -= endEffectorPose.subvec(0, 1);

      const arma::Mat<double>::fixed<2, 3>& passiveJoints = model.at(1);

      arma::Mat<double>::fixed<3, 3> forwardKinematic;
      forwardKinematic.rows(0, 1) = endEffectorJoints - passiveJoints;
      forwardKinematic.row(2) = -forwardKinematic.row(0) % endEffectorJointsRotated.row(1) + forwardKinematic.row(1) % endEffectorJointsRotated.row(0);

      const arma::Mat<double>::fixed<2, 3>& baseToPassiveJoints = passiveJoints - baseJoints;
      arma::Mat<double> inverseKinematic(3, 3 + redundantJointIndicies_.n_elem, arma::fill::zeros);
      inverseKinematic.diag() = forwardKinematic.row(0) % baseToPassiveJoints.row(1) - forwardKinematic.row(1) % baseToPassiveJoints.row(0);
      for (std::size_t n = 0; n < redundantJointIndicies_.n_elem; ++n) {
        const unsigned int& redundantJointIndex = redundantJointIndicies_.at(n);
        inverseKinematic.at(n, 3 + n) = -(forwardKinematic.at(redundantJointIndex, 0) * redundantJointAngleCosines_.at(n) + forwardKinematic.at(redundantJointIndex, 1) * redundantJointAngleSines_.at(n));
      }

      return -1.0 / arma::cond(arma::solve(forwardKinematic.t(), inverseKinematic));
    }
  }
}
<|endoftext|>


<commit_before><commit_msg>[spaces.fv] add missing includes<commit_after><|endoftext|>


<commit_before><commit_msg>Removed extra debug info.<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: mailmodel.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-03-27 09:37:18 $
 *
 *  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 INCLUDED_SFX_MAILMODEL_HXX
#define INCLUDED_SFX_MAILMODEL_HXX

#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif

// class SfxMailModel_Impl -----------------------------------------------

class AddressList_Impl;

class SfxMailModel_Impl
{
public:
    enum MailPriority
    {
        PRIO_HIGHEST,
        PRIO_HIGH,
        PRIO_NORMAL,
        PRIO_LOW,
        PRIO_LOWEST
    };

    enum AddressRole
    {
        ROLE_TO,
        ROLE_CC,
        ROLE_BCC
    };

    enum MailDocType
    {
        TYPE_SELF,
        TYPE_ASPDF
    };

private:
    enum SaveResult
    {
        SAVE_SUCCESSFULL,
        SAVE_CANCELLED,
        SAVE_ERROR
    };

    AddressList_Impl*   mpToList;
    AddressList_Impl*   mpCcList;
    AddressList_Impl*   mpBccList;
    String              maFromAddress;
    String              maSubject;
    MailPriority        mePriority;

    sal_Bool            mbLoadDone;

    void                ClearList( AddressList_Impl* pList );
    void                MakeValueList( AddressList_Impl* pList, String& rValueList );
    SaveResult          SaveDocumentAsFormat( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame, const rtl::OUString& rType, rtl::OUString& rFileNamePath );

    DECL_LINK( DoneHdl, void* );

public:
    enum SendMailResult
    {
        SEND_MAIL_OK,
        SEND_MAIL_CANCELLED,
        SEND_MAIL_ERROR
    };

    SfxMailModel_Impl();
    ~SfxMailModel_Impl();

    void                AddAddress( const String& rAddress, AddressRole eRole );
    void                SetFromAddress( const String& rAddress )    { maFromAddress = rAddress; }
    void                SetSubject( const String& rSubject )        { maSubject = rSubject; }
    void                SetPriority( MailPriority ePrio )           { mePriority = ePrio; }

    SendMailResult      Send( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame, const rtl::OUString& rType );
};

BOOL CreateFromAddress_Impl( String& rFrom );

#endif // INCLUDED_SFX_MAILMODEL_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.5.580); FILE MERGED 2008/04/01 12:40:51 thb 1.5.580.2: #i85898# Stripping all external header guards 2008/03/31 13:38:35 rt 1.5.580.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: mailmodel.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef INCLUDED_SFX_MAILMODEL_HXX
#define INCLUDED_SFX_MAILMODEL_HXX

#include <com/sun/star/frame/XFrame.hpp>

// class SfxMailModel_Impl -----------------------------------------------

class AddressList_Impl;

class SfxMailModel_Impl
{
public:
    enum MailPriority
    {
        PRIO_HIGHEST,
        PRIO_HIGH,
        PRIO_NORMAL,
        PRIO_LOW,
        PRIO_LOWEST
    };

    enum AddressRole
    {
        ROLE_TO,
        ROLE_CC,
        ROLE_BCC
    };

    enum MailDocType
    {
        TYPE_SELF,
        TYPE_ASPDF
    };

private:
    enum SaveResult
    {
        SAVE_SUCCESSFULL,
        SAVE_CANCELLED,
        SAVE_ERROR
    };

    AddressList_Impl*   mpToList;
    AddressList_Impl*   mpCcList;
    AddressList_Impl*   mpBccList;
    String              maFromAddress;
    String              maSubject;
    MailPriority        mePriority;

    sal_Bool            mbLoadDone;

    void                ClearList( AddressList_Impl* pList );
    void                MakeValueList( AddressList_Impl* pList, String& rValueList );
    SaveResult          SaveDocumentAsFormat( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame, const rtl::OUString& rType, rtl::OUString& rFileNamePath );

    DECL_LINK( DoneHdl, void* );

public:
    enum SendMailResult
    {
        SEND_MAIL_OK,
        SEND_MAIL_CANCELLED,
        SEND_MAIL_ERROR
    };

    SfxMailModel_Impl();
    ~SfxMailModel_Impl();

    void                AddAddress( const String& rAddress, AddressRole eRole );
    void                SetFromAddress( const String& rAddress )    { maFromAddress = rAddress; }
    void                SetSubject( const String& rSubject )        { maSubject = rSubject; }
    void                SetPriority( MailPriority ePrio )           { mePriority = ePrio; }

    SendMailResult      Send( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame, const rtl::OUString& rType );
};

BOOL CreateFromAddress_Impl( String& rFrom );

#endif // INCLUDED_SFX_MAILMODEL_HXX
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: impframe.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 19:27:12 $
 *
 *  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 _SFX_IMPFRAME_HXX
#define _SFX_IMPFRAME_HXX

#ifndef _SFXCANCEL_HXX //autogen
#include <svtools/cancel.hxx>
#endif

#pragma hdrstop

#include "frame.hxx"
#include "loadenv.hxx"
#include "viewfrm.hxx"                  // SvBorder

class SfxViewFrame;
class SfxObjectShell;
class SfxExplorerBrowserConfig;

#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XTOPWINDOW_HPP_
#include <com/sun/star/awt/XTopWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_
#include <com/sun/star/awt/PosSize.hpp>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

#include <viewsh.hxx>
#include <sfxuno.hxx>

#ifndef FRAME_SEARCH_PARENT
#define FRAME_SEARCH_PARENT     0x00000001
#define FRAME_SEARCH_SELF       0x00000002
#define FRAME_SEARCH_CHILDREN   0x00000004
#define FRAME_SEARCH_CREATE     0x00000008
#endif

class SfxFrame_Impl : public SfxBroadcaster, public SvCompatWeakBase, public SfxListener
{
friend class SfxFrame;

    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >                     xFrame;
    String                  aFrameIdName;
    sal_uInt32              nType;
    sal_uInt32              nHistoryPos;
    SfxViewFrame*           pCurrentViewFrame;
    SfxObjectShell*         pCurrentObjectShell;
    SfxFrameDescriptor*     pDescr;
    SfxExplorerBrowserConfig* pBrowserCfg;
    sal_uInt16              nFrameId;
    sal_uInt16              nLocks;
    sal_Bool                bCloseOnUnlock : 1;
    sal_Bool                bClosing : 1;
    sal_Bool                bPrepClosing : 1;
    sal_Bool                bInCancelTransfers : 1;
    sal_Bool                bOwnsBindings : 1;
    sal_Bool                bReleasingComponent : 1;
    sal_Bool                bFocusLocked : 1;
    sal_Bool                bInPlace : 1;
    sal_uInt16              nHasBrowser;
    SfxCancelManager*       pCancelMgr;
    SfxCancellable*         pLoadCancellable;
    SfxFrame*               pFrame;
    const SfxItemSet*       pSet;
    SfxWorkWindow*          pWorkWin;
    SvBorder                aBorder;

                            SfxFrame_Impl( SfxFrame* pAntiImplP ) :
                                SvCompatWeakBase( pAntiImplP ),
                                pFrame( pAntiImplP ),
                                bClosing(sal_False),
                                bPrepClosing(sal_False),
                                nType( 0L ),
                                nHistoryPos( 0 ),
                                nFrameId( 0 ),
                                pCurrentObjectShell( NULL ),
                                pCurrentViewFrame( NULL ),
                                bInCancelTransfers( sal_False ),
                                bCloseOnUnlock( sal_False ),
                                bOwnsBindings( sal_False ),
                                bReleasingComponent( sal_False ),
                                bFocusLocked( sal_False ),
                                bInPlace( sal_False ),
                                nLocks( 0 ),
                                pBrowserCfg( NULL ),
                                pDescr( NULL ),
                                nHasBrowser( SFX_BEAMER_OFF ),
                                pCancelMgr( 0 ),
                                pLoadCancellable( 0 ),
                                pSet( 0 ),
                                pWorkWin( 0 )
                            {}

                            ~SfxFrame_Impl() { delete pCancelMgr;
                                               delete pLoadCancellable; }
    virtual void            Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
};

#endif

<commit_msg>INTEGRATION: CWS sfxcleanup (1.6.158); FILE MERGED 2006/02/24 23:08:58 mba 1.6.158.1: #132394#: remove obviously superfluous members and methods from SfxApplication<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: impframe.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2006-05-02 17:03:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SFX_IMPFRAME_HXX
#define _SFX_IMPFRAME_HXX

#ifndef _SFXCANCEL_HXX //autogen
#include <svtools/cancel.hxx>
#endif

#pragma hdrstop

#include "frame.hxx"
#include "viewfrm.hxx"                  // SvBorder

class SfxViewFrame;
class SfxObjectShell;

#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XTOPWINDOW_HPP_
#include <com/sun/star/awt/XTopWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_
#include <com/sun/star/awt/PosSize.hpp>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

#include <viewsh.hxx>
#include <sfxuno.hxx>

#ifndef FRAME_SEARCH_PARENT
#define FRAME_SEARCH_PARENT     0x00000001
#define FRAME_SEARCH_SELF       0x00000002
#define FRAME_SEARCH_CHILDREN   0x00000004
#define FRAME_SEARCH_CREATE     0x00000008
#endif

class SfxFrame_Impl : public SfxBroadcaster, public SvCompatWeakBase, public SfxListener
{
friend class SfxFrame;

    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >                     xFrame;
    String                  aFrameIdName;
    sal_uInt32              nType;
    sal_uInt32              nHistoryPos;
    SfxViewFrame*           pCurrentViewFrame;
    SfxObjectShell*         pCurrentObjectShell;
    SfxFrameDescriptor*     pDescr;
    sal_uInt16              nFrameId;
    sal_uInt16              nLocks;
    sal_Bool                bCloseOnUnlock : 1;
    sal_Bool                bClosing : 1;
    sal_Bool                bPrepClosing : 1;
    sal_Bool                bInCancelTransfers : 1;
    sal_Bool                bOwnsBindings : 1;
    sal_Bool                bReleasingComponent : 1;
    sal_Bool                bFocusLocked : 1;
    sal_Bool                bInPlace : 1;
    SfxCancelManager*       pCancelMgr;
    SfxCancellable*         pLoadCancellable;
    SfxFrame*               pFrame;
    const SfxItemSet*       pSet;
    SfxWorkWindow*          pWorkWin;
    SvBorder                aBorder;

                            SfxFrame_Impl( SfxFrame* pAntiImplP ) :
                                SvCompatWeakBase( pAntiImplP ),
                                pFrame( pAntiImplP ),
                                bClosing(sal_False),
                                bPrepClosing(sal_False),
                                nType( 0L ),
                                nHistoryPos( 0 ),
                                nFrameId( 0 ),
                                pCurrentObjectShell( NULL ),
                                pCurrentViewFrame( NULL ),
                                bInCancelTransfers( sal_False ),
                                bCloseOnUnlock( sal_False ),
                                bOwnsBindings( sal_False ),
                                bReleasingComponent( sal_False ),
                                bFocusLocked( sal_False ),
                                bInPlace( sal_False ),
                                nLocks( 0 ),
                                pDescr( NULL ),
                                pCancelMgr( 0 ),
                                pLoadCancellable( 0 ),
                                pSet( 0 ),
                                pWorkWin( 0 )
                            {}

                            ~SfxFrame_Impl() { delete pCancelMgr;
                                               delete pLoadCancellable; }
    virtual void            Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
};

#endif

<|endoftext|>


<commit_before>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>

using namespace std;
using namespace cv;

int main(int argc, char ** argv){
	VideoCapture in;
	VideoWriter out;
	VideoWriter test;

	if(argc >1){
		in.open(argv[1]);
//		int ex= static_cast<int>(in.get(CV_CAP_PROP_FOURCC));
		const string source = argv[1];
		string::size_type pAt = source.find_last_of('.');
		const string NAME= source.substr(0, pAt) + "E.avi";

		out.open(NAME, CV_FOURCC('D', 'I', 'V', 'X') , in.get(CV_CAP_PROP_FPS), Size( (int) in.get(CV_CAP_PROP_FRAME_WIDTH), (int) in.get(CV_CAP_PROP_FRAME_HEIGHT)), true);
	}

	else
		exit(1);

	if(!in.isOpened()){
		cerr<<"Was unable to open video input."<<endl;
	}

	if(!out.isOpened()){
		cerr<<"Was unable to open video output."<<endl;
	}

	int count=0;

	while(true){
		Mat frame;
		Mat colorImg;

		bool success = in.read(frame);

		if(!success){
			cout<<"VIDEO STREAM COMPLETE"<<endl;
			break;
		}

		//Lets do some thresholding.

		cvtColor(frame, colorImg, COLOR_BGR2HSV);

		for(int i=0; i<colorImg.rows; i++){
			for(int j=0; j<colorImg.cols; j++){

				Vec3i & pixel = colorImg.at<Vec3i>(Point(j, i));

				if( (pixel[0] > 8 && pixel[0] < 22) && (pixel[1] > 60 && pixel[1] < 120 ) && (pixel[2] > 0 && pixel[2] <255)){
					pixel[0] = 255;
					pixel[1] = 0;
					pixel[2] = 0;
				}
				else{
					pixel[0] = 0;
					pixel[1] = 0;
                                        pixel[2] = 0;

				}
				colorImg.at<Vec3i>(Point(j, i)) = pixel;

			}
		}

		//It is now time for line doings.
		Vec3i pixel;
		vector<Point> points;

		for(int i=0; i<colorImg.cols; i++){
			for(int j=0; j<colorImg.rows; j++){
				pixel = colorImg.at<Vec3i>(i, j);
				if(pixel[0] !=0){
					points.push_back(Point(i, j));
				}
			}
		}

		Point * pointArr = new Point[points.size()];
		Mat pointMat = Mat(1, points.size(), CV_32F, pointArr);
		Vec4f outVector;

		fitLine(points, outVector, CV_DIST_L2, 0, 0.01, 0.01);

		float d = sqrt((double)outVector[0]*outVector[0] + (double)outVector[1]*outVector[1]);
		outVector[0] /= d;
		outVector[1] /= d;
		float m = (float) (frame.cols + frame.rows);

		Point start;
		start.x = outVector[2] - m*outVector[0];
		start.y = outVector[3] - m*outVector[1];

		Point end;
		end.x = outVector[2] + m*outVector[0];
		end.y = outVector[3] + m*outVector[1];

		for(int i=0; i<points.size(); i++){
			circle(frame, points[i], 2, Scalar(255, 0, 0), CV_FILLED, CV_AA, 0);
		}

		circle(frame, Point(outVector[2], outVector[3]), 10, Scalar(255, 0, 0), 1, 8, 0);
		line(frame, start, end, Scalar(0, 0, 255), 3, CV_AA, 0 );

		if(count % 100 ==0)
			cout<<"WRITING FRAME "<<count<<endl;

		count++;
		out.write(frame);
	}

	in.release();
	cout<<argv[1]<<endl;
}
<commit_msg>started over, looking pretty good so far<commit_after>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>

using namespace std;
using namespace cv;

int main(int argc, char ** argv){
	VideoCapture in;
	VideoWriter out;
	VideoWriter test;

	if(argc >1){
		in.open(argv[1]);
		const string source = argv[1];
		string::size_type pAt = source.find_last_of('.');
		const string NAME= source.substr(0, pAt) + "E.avi";

		out.open(NAME, CV_FOURCC('D', 'I', 'V', 'X') , in.get(CV_CAP_PROP_FPS), Size( (int) in.get(CV_CAP_PROP_FRAME_WIDTH), (int) in.get(CV_CAP_PROP_FRAME_HEIGHT)), true);
	}

	else
		exit(1);

	if(!in.isOpened()){
		cerr<<"Was unable to open video input."<<endl;
	}

	if(!out.isOpened()){
		cerr<<"Was unable to open video output."<<endl;
	}

	int frameNum=0;
	while(true){
		Mat frame(in.get(CV_CAP_PROP_FRAME_HEIGHT), in.get(CV_CAP_PROP_FRAME_WIDTH), CV_8UC3);
		Mat color(frame.rows, frame.cols, CV_8UC3);
		Mat thresh(color.rows, color.cols, CV_8UC3);

		in.read(frame);

		cvtColor(frame, color, CV_BGR2HSV, 3);

		Vec3b pixel;
		vector<Point> points;

		for(int i=0; i<color.rows; i++){
			for(int j=0; j<color.cols; j++){
				pixel = color.at<Vec3b>(Point(j,i));
				if( (pixel[0] > 8 && pixel[0] < 22) && (pixel[1] > 22 && pixel[1] < 60)){
					points.push_back(Point(j, i));
					//thresh.at<Vec3b>(Point(j, i)) = Vec3b(179, 255, 255);
				}
				else{
					//thresh.at<Vec3b>(Point(j, i)) = Vec3b(0, 0, 0);
				}

			}
		}

		for(int k=0; k < points.size(); k++){
			circle(frame, points[k], 3, Scalar(255, 0, 0), -1,CV_AA, 0);
		}

		out.write(frame);

		if(frameNum % 100 == 0)
			cout<<"FRAME "<<frameNum<<endl;

		frameNum++;

	}

	out.release();

}
<|endoftext|>


<commit_before>#include "app/SimpleApp.h"
#include "sys/AbstractThread.h"
#include "sys/StopWatch.h"
#include "trace/log.h"
#include "trace/UdpBackEnd.h"

//#define PERFORMANCE_TEST 1

namespace
{
    class Th1 : public ::sys::AbstractThread
    {
    public:
        explicit Th1( const uint32_t id )
            : ::sys::AbstractThread( ::std::to_string( id ).c_str() )
            , m_char( 'A' + id )
        {
        }

    private:
        virtual void run()
        {
            uint32_t i = 200;
            while ( i != 0U )
            {
                if ( isStopRequested() )
                {
                    LOG_DEV_C( "Thread '%c' requested to stop on i = %u", m_char, i );
                    break;
                }

                LOG_INFO_C( "TH: %c, i = %u", m_char, i );
                sleep( 5 + ( m_char * 2U ) );
                --i;
            }
        }

        const char m_char;
    };
}

class DemoApp : public ::app::SimpleApp
{
public:
    DemoApp()
        : ::app::SimpleApp( "TraceLogDemo" )
    {

    }

private:
    virtual int32_t onRun( const TStringVector& args )
    {
#ifndef PERFORMANCE_TEST
        const size_t NUM_TH = 26U;

        Th1* threads[ NUM_TH ];

        for ( size_t i = 0U; i < NUM_TH; i++ )
        {
            threads[ i ] = new Th1( i );
            threads[ i ]->start();
        }

        if ( waitForExit( 15000U ) )
        {
            LOG_INFO_C( "Example running until end" );
        }
        else
        {
            LOG_WARN_C( "Example Timeout" );
        }

        for ( size_t i = 0U; i < NUM_TH; i++ )
        {
            threads[ i ]->requestStop();
            threads[ i ]->join();

            delete threads[ i ];
        }
#else
        /* Run the benchmark */
        LOG_INFO_C( "Start The Benchmark" );
        ::sys::StopWatch sw( true );

        for ( uint32_t i = 0; i < 100000; i++ )
        {
            LOG_INFO_C("TEST: and some text here :-)");
        }

        LOG_INFO_C( "Took: %u ms", sw.stop() / 1000U );
#endif // PERFORMANCE_TEST
        return 0;
    }
};

int32_t main( int argc, const char * const * argv )
{
    LOGGER_INIT_BE_UDP;

    LOG_INFO_C( "App Started: %c", 'a' );
    int32_t result = ::DemoApp().run( argc, argv );
    LOG_INFO_C( "App Exited: %d" , result );
    LOG_INFO_C( "- bye! -" );

    LOGGER_SHUTDOWN();

    return result;
}
<commit_msg>Add few console traces to the example<commit_after>#include "app/SimpleApp.h"
#include "sys/AbstractThread.h"
#include "sys/StopWatch.h"
#include "trace/log.h"
#include "trace/UdpBackEnd.h"

//#define PERFORMANCE_TEST 1

namespace
{
    class Th1 : public ::sys::AbstractThread
    {
    public:
        explicit Th1( const uint32_t id )
            : ::sys::AbstractThread( ::std::to_string( id ).c_str() )
            , m_char( 'A' + id )
        {
        }

    private:
        virtual void run()
        {
            uint32_t i = 200;
            while ( i != 0U )
            {
                if ( isStopRequested() )
                {
                    LOG_DEV_C( "Thread '%c' requested to stop on i = %u", m_char, i );
                    break;
                }

                LOG_INFO_C( "TH: %c, i = %u", m_char, i );
                sleep( 5 + ( m_char * 2U ) );
                --i;
            }
        }

        const char m_char;
    };
}

class DemoApp : public ::app::SimpleApp
{
public:
    DemoApp()
        : ::app::SimpleApp( "TraceLogDemo" )
    {

    }

private:
    virtual int32_t onRun( const TStringVector& args )
    {
        ::printf( "TraceLog Demo\n" );
#ifndef PERFORMANCE_TEST
        const size_t NUM_TH = 26U;

        Th1* threads[ NUM_TH ];

        for ( size_t i = 0U; i < NUM_TH; i++ )
        {
            threads[ i ] = new Th1( i );
            threads[ i ]->start();
        }

        if ( waitForExit( 15000U ) )
        {
            LOG_INFO_C( "Example running until end" );
            ::printf( "\nReceived BREAK signal...\n" );
        }
        else
        {
            LOG_WARN_C( "Example Timeout" );
        }

        for ( size_t i = 0U; i < NUM_TH; i++ )
        {
            threads[ i ]->requestStop();
            threads[ i ]->join();

            delete threads[ i ];
        }
#else
        /* Run the benchmark */
        LOG_INFO_C( "Start The Benchmark" );
        ::sys::StopWatch sw( true );

        for ( uint32_t i = 0; i < 100000; i++ )
        {
            LOG_INFO_C("TEST: and some text here :-)");
        }

        LOG_INFO_C( "Took: %u ms", sw.stop() / 1000U );
#endif // PERFORMANCE_TEST

        ::printf( "Exit\n" );

        return 0;
    }
};

int32_t main( int argc, const char * const * argv )
{
    LOGGER_INIT_BE_UDP;

    LOG_INFO_C( "App Started: %c", 'a' );
    int32_t result = ::DemoApp().run( argc, argv );
    LOG_INFO_C( "App Exited: %d" , result );
    LOG_INFO_C( "- bye! -" );

    LOGGER_SHUTDOWN();

    return result;
}
<|endoftext|>


<commit_before>/**
* * \file main.cpp
* \brief test/demo program
* \author Arthur Brainville
*
* Annwvyn test program http://annwvyn.org/
*
*/
#include "stdafx.h"

//Annwvyn
#include <Annwvyn.h>
#include "TestLevel.hpp"
#include <AnnSplashLevel.hpp>

using namespace std;
using namespace Annwvyn;

timerID demoTimer;

class MySaveTest : public AnnSaveDataInterpretor
{
public:
	MySaveTest(AnnSaveFileData* data) : AnnSaveDataInterpretor(data)
	{
	}

	AnnVect3 getPosition()
	{
		return pos;
	}

	AnnQuaternion getOrientation()
	{
		return orient;
	}

	float getPi()
	{
		return pi;
	}

	int getLives()
	{
		return lives;
	}

	virtual void extract()
	{
		pos = keyStringToVect3("pos");
		orient = keyStringToQuaternion("orient");
		pi = keyStringToFloat("PI");
		lives = keyStringToInt("lives");
	}
private:
	AnnVect3 pos;
	AnnQuaternion orient;
	float pi;
	int lives;
};

class DebugListener : LISTENER
{
public:
	DebugListener() : constructListener()
	{
	}

	void TimeEvent(AnnTimeEvent e)
	{
		AnnDebug() << "TimeEvent id : " << e.getID();
		if(e.getID() == demoTimer)
			AnnDebug() << "This is the demoTimer that was launched on the main function !";
	}
	void TriggerEvent(AnnTriggerEvent e)
	{
		AnnDebug() << "TriggerEvent contact status : " << e.getContactStatus() << " from " << e.getSender();
	}

	void testFileIO()
	{
		auto testFile = AnnGetFileSystemManager()->crateSaveFileDataObject("test");
		testFile->setValue("KEY0", "Thing");
		testFile->setValue("KEY1", "otherThing");
		testFile->setValue("lives", 10);
		testFile->setValue("PI", 3.14f);
		testFile->setValue("pos", AnnVect3(2.5, 4.8, Ogre::Math::HALF_PI));
		testFile->setValue("orient", AnnQuaternion(Ogre::Radian(Ogre::Math::HALF_PI), AnnVect3(.5, .5, .5)));

		AnnFileWriter* writer(AnnGetFileSystemManager()->getFileWriter());
		writer->write(testFile);

		AnnFileReader* reader(AnnGetFileSystemManager()->getFileReader());
		auto data = reader->read("test");

		AnnDebug() << "KEY0 val : " << data->getValue("KEY0");
		AnnDebug() << "KEY1 val : " << data->getValue("KEY1");

		MySaveTest tester(data);
		tester.extract();
		AnnDebug() << "stored vector value : " << tester.getPosition();
		AnnDebug() << "stored quaternion value : " << tester.getOrientation();
		AnnDebug() << "stored pi value : " << tester.getPi();
		AnnDebug() << "stored lives value : " << tester.getLives();

	}

	void KeyEvent(AnnKeyEvent e)
	{
		if (e.isPressed() && e.getKey() == KeyCode::h)
			testFileIO();
	}
};

AnnMain()
{
	//Only usefull on windows : Open a debug console to get stdout/stderr
	AnnEngine::openConsole();

	//Init game engine
	AnnInit("AnnTest");

	//Init some player body parameters
	AnnGetEngine()->initPlayerPhysics();
	AnnGetPhysicsEngine()->setDebugPhysics(false);

	AnnGetEventManager()->useDefaultEventListener();
	AnnGetVRRenderer()->recenter();
	AnnGetEngine()->getEventManager()->addListener(new DebugListener);
	demoTimer = AnnGetEngine()->getEventManager()->fireTimer(10);

	//load ressources
	AnnGetResourceManager()->loadDir("media/environement");
	AnnGetResourceManager()->loadDir("media/debug");
	AnnGetResourceManager()->initResources();

	AnnAbstractLevel* level = new TestLevel();
	AnnSplashLevel* splash = new AnnSplashLevel("splash.png", level, 7.1f);
	splash->setBGM("media/AnnSplash.ogg");

	AnnGetEngine()->getLevelManager()->addLevel(splash);
	AnnGetEngine()->getLevelManager()->addLevel(level);
	AnnGetEngine()->getLevelManager()->jumpToFirstLevel();

	AnnDebug() << "Starting the render loop";
	do
	{
		if(AnnGetEngine()->isKeyDown(OIS::KC_Q))
			AnnGetEngine()->getLevelManager()->unloadCurrentLevel();
		if(AnnGetEngine()->isKeyDown(OIS::KC_E))
			AnnGetEngine()->getLevelManager()->jumpToFirstLevel();
	}
	while(AnnGetEngine()->refresh());

	delete AnnGetEngine();
	return EXIT_SUCCESS;
}
<commit_msg>add code that test the POV in debug event of test<commit_after>/**
* * \file main.cpp
* \brief test/demo program
* \author Arthur Brainville
*
* Annwvyn test program http://annwvyn.org/
*
*/
#include "stdafx.h"

//Annwvyn
#include <Annwvyn.h>
#include "TestLevel.hpp"
#include <AnnSplashLevel.hpp>

using namespace std;
using namespace Annwvyn;

timerID demoTimer;

class MySaveTest : public AnnSaveDataInterpretor
{
public:
	MySaveTest(AnnSaveFileData* data) : AnnSaveDataInterpretor(data)
	{
	}

	AnnVect3 getPosition()
	{
		return pos;
	}

	AnnQuaternion getOrientation()
	{
		return orient;
	}

	float getPi()
	{
		return pi;
	}

	int getLives()
	{
		return lives;
	}

	virtual void extract()
	{
		pos = keyStringToVect3("pos");
		orient = keyStringToQuaternion("orient");
		pi = keyStringToFloat("PI");
		lives = keyStringToInt("lives");
	}
private:
	AnnVect3 pos;
	AnnQuaternion orient;
	float pi;
	int lives;
};

class DebugListener : LISTENER
{
public:
	DebugListener() : constructListener()
	{
	}

	void TimeEvent(AnnTimeEvent e)
	{
		AnnDebug() << "TimeEvent id : " << e.getID();
		if(e.getID() == demoTimer)
			AnnDebug() << "This is the demoTimer that was launched on the main function !";
	}
	void TriggerEvent(AnnTriggerEvent e)
	{
		AnnDebug() << "TriggerEvent contact status : " << e.getContactStatus() << " from " << e.getSender();
	}

	void testFileIO()
	{
		auto testFile = AnnGetFileSystemManager()->crateSaveFileDataObject("test");
		testFile->setValue("KEY0", "Thing");
		testFile->setValue("KEY1", "otherThing");
		testFile->setValue("lives", 10);
		testFile->setValue("PI", 3.14f);
		testFile->setValue("pos", AnnVect3(2.5, 4.8, Ogre::Math::HALF_PI));
		testFile->setValue("orient", AnnQuaternion(Ogre::Radian(Ogre::Math::HALF_PI), AnnVect3(.5, .5, .5)));

		AnnFileWriter* writer(AnnGetFileSystemManager()->getFileWriter());
		writer->write(testFile);

		AnnFileReader* reader(AnnGetFileSystemManager()->getFileReader());
		auto data = reader->read("test");

		AnnDebug() << "KEY0 val : " << data->getValue("KEY0");
		AnnDebug() << "KEY1 val : " << data->getValue("KEY1");

		MySaveTest tester(data);
		tester.extract();
		AnnDebug() << "stored vector value : " << tester.getPosition();
		AnnDebug() << "stored quaternion value : " << tester.getOrientation();
		AnnDebug() << "stored pi value : " << tester.getPi();
		AnnDebug() << "stored lives value : " << tester.getLives();

	}

	void KeyEvent(AnnKeyEvent e)
	{
		if (e.isPressed() && e.getKey() == KeyCode::h)
			testFileIO();
	}

	void StickEvent(AnnStickEvent e)
	{
		if (e.getStickID() == 0)
		{
			AnnStickPov pov = e.getPov(0);
			AnnDebug() << pov.getNorth() << pov.getSouth() << pov.getEast() << pov.getWest();
		}
	}
};

AnnMain()
{
	//Only usefull on windows : Open a debug console to get stdout/stderr
	AnnEngine::openConsole();

	//Init game engine
	AnnInit("AnnTest");

	//Init some player body parameters
	AnnGetEngine()->initPlayerPhysics();
	AnnGetPhysicsEngine()->setDebugPhysics(false);

	AnnGetEventManager()->useDefaultEventListener();
	AnnGetVRRenderer()->recenter();
	AnnGetEngine()->getEventManager()->addListener(new DebugListener);
	demoTimer = AnnGetEngine()->getEventManager()->fireTimer(10);

	//load ressources
	AnnGetResourceManager()->loadDir("media/environement");
	AnnGetResourceManager()->loadDir("media/debug");
	AnnGetResourceManager()->initResources();

	AnnAbstractLevel* level = new TestLevel();
	AnnSplashLevel* splash = new AnnSplashLevel("splash.png", level, 7.1f);
	splash->setBGM("media/AnnSplash.ogg");

	AnnGetEngine()->getLevelManager()->addLevel(splash);
	AnnGetEngine()->getLevelManager()->addLevel(level);
	AnnGetEngine()->getLevelManager()->jumpToFirstLevel();

	AnnDebug() << "Starting the render loop";
	do
	{
		if(AnnGetEngine()->isKeyDown(OIS::KC_Q))
			AnnGetEngine()->getLevelManager()->unloadCurrentLevel();
		if(AnnGetEngine()->isKeyDown(OIS::KC_E))
			AnnGetEngine()->getLevelManager()->jumpToFirstLevel();
	}
	while(AnnGetEngine()->refresh());

	delete AnnGetEngine();
	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2015.  All rights reserved
 */
#include    "../StroikaPreComp.h"

#include    <thread>

#if     qPlatform_POSIX
#include    <unistd.h>
#include    <fstream>
#elif   qPlatform_Windows
#include    <Windows.h>
#endif

#include    "../Characters/SDKString.h"
#include    "../Characters/Format.h"
#include    "../Characters/String_Constant.h"
#include    "../Characters/String2Int.h"
#include    "../Containers/Set.h"
#if     qPlatform_POSIX
#include    "../Execution/ErrNoException.h"
#elif   qPlatform_Windows
#include    "../Execution/Platform/Windows/Exception.h"
#endif
#include    "../Memory/SmallStackBuffer.h"
#include    "../IO/FileSystem/BinaryFileInputStream.h"
#include    "../Streams/BasicBinaryInputOutputStream.h"
#include    "../Streams/TextInputStreamBinaryAdapter.h"

#include    "SystemConfiguration.h"

#if     qPlatform_POSIX
#include    "../DataExchange/INI/Reader.h"
#include    "../Execution/ProcessRunner.h"
#include    "../Streams/iostream/FStreamSupport.h"
#endif

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Configuration;
using   namespace   Stroika::Foundation::Containers;
using   namespace   Stroika::Foundation::Streams;

using   Characters::String_Constant;
using   Characters::SDKChar;

// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define   USE_NOISY_TRACE_IN_THIS_MODULE_       1

/*
 ********************************************************************************
 ***************** Configuration::SystemConfiguration::CPU **********************
 ********************************************************************************
 */
unsigned int    SystemConfiguration::CPU::GetNumberOfSockets () const
{
    Set<unsigned int>   socketIds;
    for (auto i : fCores) {
        socketIds.Add (i.fSocketID);
    }
    return static_cast<unsigned int> (socketIds.size ());
}

/*
 ********************************************************************************
 *************** Configuration::GetSystemConfiguration_CPU **********************
 ********************************************************************************
 */
SystemConfiguration::CPU Configuration::GetSystemConfiguration_CPU ()
{
    using CPU = SystemConfiguration::CPU;
    CPU result;

#if     qPlatform_POSIX
    {
        using   Streams::TextInputStreamBinaryAdapter;
        using   IO::FileSystem::BinaryFileInputStream;
        using   Characters::String2Int;
        const   String_Constant kProcCPUInfoFileName_ { L"/proc/cpuinfo" };

        CPU::CoreDetails    coreDetails;
        // Note - /procfs files always unseekable
        for (String line : TextInputStreamBinaryAdapter (BinaryFileInputStream::mk (kProcCPUInfoFileName_, BinaryFileInputStream::eNotSeekable)).ReadLines ()) {
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
            DbgTrace (L"***in Configuration::GetSystemConfiguration_CPU capture_ line=%s", line.c_str ());
#endif
            static  const   String_Constant kModelNameLabel_ { L"model name	: " };
            //static    const   String_Constant kProcessorIDLabel_ { L"processor    : " };
            static  const   String_Constant kSocketIDLabel_ { L"physical id	: " };          // a bit of a guess?
            if (line.StartsWith (kModelNameLabel_)) {
                coreDetails.fModelName = line.SubString (kModelNameLabel_.length ()).Trim ();
            }
            else if (line.StartsWith (kSocketIDLabel_)) {
                unsigned int socketID = String2Int<unsigned int> (line.SubString (kSocketIDLabel_.length ()).Trim ());
                coreDetails.fSocketID = socketID;
            }
            if (line.Trim ().empty ()) {
                // ends each socket
                result.fCores.Append (coreDetails);
                coreDetails = CPU::CoreDetails ();
            }
        }
        if (coreDetails.fSocketID != 0 or not coreDetails.fModelName.empty ()) {
            result.fCores.Append (coreDetails);
        }
    }
#elif   qPlatform_Windows
    SYSTEM_INFO sysInfo;        // GetNativeSystemInfo cannot fail so no need to initialize data
    ::GetNativeSystemInfo (&sysInfo);
    //unclear if this is count of logical or physical cores, or how to compute the other.
    //@todo - fix as above for POSIX... maybe ask Sterl? But for now KISS
    //
    // Can use https://msdn.microsoft.com/en-us/library/hskdteyh%28v=vs.90%29.aspx?f=255&MSPPError=-2147217396
    //  __cpuid
    // to find this information (at least modelname string.
    //
    for (DWORD i = 0; i < sysInfo.dwNumberOfProcessors; ++i) {
        result.fCores.Append (CPU::CoreDetails ());
    }
#endif

    return result;
}

/*
 ********************************************************************************
 ************** Configuration::GetSystemConfiguration_Memory ********************
 ********************************************************************************
 */
SystemConfiguration::Memory Configuration::GetSystemConfiguration_Memory ()
{
    using   Memory = SystemConfiguration::Memory;
    Memory  result;
#if     qPlatform_POSIX
    result.fPageSize = ::sysconf (_SC_PAGESIZE);
    result.fTotalPhysicalRAM = ::sysconf (_SC_PHYS_PAGES) * result.fPageSize;
#elif   qPlatform_Windows
    SYSTEM_INFO sysInfo;
    ::GetNativeSystemInfo (&sysInfo);
    result.fPageSize = sysInfo.dwPageSize;

    MEMORYSTATUSEX memStatus;
    memStatus.dwLength = sizeof (memStatus);
    Verify (::GlobalMemoryStatusEx (&memStatus));
    result.fTotalPhysicalRAM = memStatus.ullTotalPhys;
    result.fTotalVirtualRAM = memStatus.ullTotalVirtual;
#endif
    return result;
}

/*
 ********************************************************************************
 ******** Configuration::GetSystemConfiguration_OperatingSystem *****************
 ********************************************************************************
 */
SystemConfiguration::OperatingSystem    Configuration::GetSystemConfiguration_OperatingSystem ()
{
    using   OperatingSystem =   SystemConfiguration::OperatingSystem;
    static  const   OperatingSystem    kCachedResult_ = []() ->OperatingSystem {
        OperatingSystem    tmp;
#if     qPlatform_POSIX
        tmp.fTokenName = String_Constant (L"Unix");
        try {
            tmp.fTokenName = Execution::ProcessRunner (L"uname").Run (String ()).Trim ();
        }
        catch (...)
        {
            DbgTrace ("Failure running uname");
        }
        try {
            ifstream s;
            Streams::iostream::OpenInputFileStream (&s, L"/etc/os-release");
            DataExchange::INI::Profile p = DataExchange::INI::Reader ().ReadProfile (s);
            tmp.fShortPrettyName = p.fUnnamedSection.fProperties.LookupValue (L"NAME");
            tmp.fPrettyNameWithMajorVersion = p.fUnnamedSection.fProperties.LookupValue (L"PRETTY_NAME");
        }
        catch (...)
        {
            DbgTrace ("Failure reading /etc/os-release");
        }
        if (tmp.fShortPrettyName.empty ())
        {
            tmp.fShortPrettyName = tmp.fTokenName;
        }
        if (tmp.fPrettyNameWithMajorVersion.empty ())
        {
            tmp.fPrettyNameWithMajorVersion = tmp.fShortPrettyName;
        }
        if (tmp.fRFC1945CompatProductTokenWithVersion.empty ())
        {
            tmp.fRFC1945CompatProductTokenWithVersion = tmp.fShortPrettyName.Trim ().ReplaceAll (L" ", L"-");
            if (not tmp.fMajorMinorVersionString.empty ()) {
                tmp.fRFC1945CompatProductTokenWithVersion += L"/" + tmp.fMajorMinorVersionString;
            }
        }
        //
        // @todo FIX/FIND BETTER WAY!
        //
        //http://docs.oracle.com/cd/E36784_01/html/E36874/sysconf-3c.html
        // Quite uncertain - this is not a good reference
        //      --LGP 2014-10-18
        //
        tmp.fBits = ::sysconf (_SC_V6_LP64_OFF64) == _POSIX_V6_LP64_OFF64 ? 64 : 32;
#elif   qPlatform_Windows
        tmp.fTokenName = String_Constant (L"Windows");
        /*
         *  Microslop declares this deprecated, but then fails to provide a reasonable alternative.
         *
         *  Sigh.
         *
         *  http://msdn.microsoft.com/en-us/library/windows/desktop/ms724429(v=vs.85).aspx -  GetFileVersionInfo (kernel32.dll)
         *  is a painful, and stupid alternative.
         */
        DISABLE_COMPILER_MSC_WARNING_START(4996)
        OSVERSIONINFOEX   osvi;
        memset(&osvi, 0, sizeof (osvi));
        osvi.dwOSVersionInfoSize = sizeof (osvi);
        Verify (::GetVersionEx (reinterpret_cast<LPOSVERSIONINFO> (&osvi)));
        DISABLE_COMPILER_MSC_WARNING_END(4996)
        if (osvi.dwMajorVersion == 6)
        {
            if (osvi.dwMinorVersion == 0) {
                tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows Vista") : String_Constant (L"Windows Server 2008");
            }
            else if (osvi.dwMinorVersion == 1) {
                tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows 7") : String_Constant (L"Windows Server 2008 R2");
            }
            else if (osvi.dwMinorVersion == 2) {
                tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows 8") : String_Constant (L"Windows Server 2012");
            }
            else if (osvi.dwMinorVersion == 3) {
                if (osvi.wProductType == VER_NT_WORKSTATION)
                    tmp.fShortPrettyName = String_Constant (L"Windows 8.1");
            }
        }
        if (tmp.fShortPrettyName.empty ())
        {
            tmp.fShortPrettyName = Characters::Format (L"Windows %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
        }
        tmp.fPrettyNameWithMajorVersion = tmp.fShortPrettyName;
        tmp.fMajorMinorVersionString = Characters::Format (L"%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
        tmp.fRFC1945CompatProductTokenWithVersion = Characters::Format (L"Windows/%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
        if (sizeof (void*) == 4)
        {
            tmp.fBits = 32;
            //IsWow64Process is not available on all supported versions of Windows.
            //Use GetModuleHandle to get a handle to the DLL that contains the function
            //and GetProcAddress to get a pointer to the function if available.
            typedef BOOL (WINAPI * LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
            LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process");
            if(NULL != fnIsWow64Process) {
                BOOL    isWOW64 = false;
                (void)fnIsWow64Process (GetCurrentProcess(), &isWOW64);
                if (isWOW64) {
                    tmp.fBits = 64;
                }
            }
        }
        else {
            // In windows, a 64 bit app cannot run on 32-bit windows
            Assert (sizeof (void*) == 8);
            tmp.fBits = 64;
        }
#else
        AssertNotImplemented ();
#endif
        return tmp;
    } ();
    return kCachedResult_;
}

/*
 ********************************************************************************
 ***************** GetSystemConfiguration_ComputerNames *************************
 ********************************************************************************
 */
#if     0 && qPlatform_POSIX
// ALTERNATE APPROACH TO CONSIDER
string  name;
{
    struct addrinfo* res;
    struct addrinfo hints;
    memset(&hints, '\0', sizeof(hints));
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_CANONNAME;
    int e = getaddrinfo(nullptr, nullptr, &hints, &res);
    if (e != 0) {
        //printf("failure %s\n", gai_strerror (e));
        return String ();
    }
    int sock = -1;
    for (struct addrinfo* r = res; r != NULL; r = r->ai_next) {
        name = r->ai_canonname ;
        break;
    }
    freeaddrinfo(res);
}
return String::FromSDKString (name);
#endif
SystemConfiguration::ComputerNames Configuration::GetSystemConfiguration_ComputerNames ()
{
    using ComputerNames = SystemConfiguration::ComputerNames;
    ComputerNames   result;
#if     qPlatform_POSIX
    char    nameBuf[1024];
    Execution::ThrowErrNoIfNegative (gethostname (nameBuf, NEltsOf (nameBuf)));
    nameBuf[NEltsOf (nameBuf) - 1] = '\0';  // http://linux.die.net/man/2/gethostname says not necessarily nul-terminated
    result.fHostname = String::FromNarrowSDKString (nameBuf);
#elif   qPlatform_Windows
    constexpr   COMPUTER_NAME_FORMAT    kUseNameFormat_ = ComputerNameNetBIOS;  // total WAG -- LGP 2014-10-10
    DWORD   dwSize = 0;
    (void) ::GetComputerNameEx (kUseNameFormat_, nullptr, &dwSize);
    Memory::SmallStackBuffer<SDKChar> buf(dwSize);
    Execution::Platform::Windows::ThrowIfFalseGetLastError (::GetComputerNameEx (kUseNameFormat_, buf, &dwSize));
    result.fHostname = String::FromSDKString (buf);
#else
    AssertNotImplemented ();
#endif
    return result;
}

/*
 ********************************************************************************
 ****************** SystemConfiguration GetSystemConfiguration ******************
 ********************************************************************************
 */
inline  SystemConfiguration Configuration::GetSystemConfiguration ()
{
    return SystemConfiguration {
        GetSystemConfiguration_CPU (),
        GetSystemConfiguration_Memory (),
        GetSystemConfiguration_OperatingSystem (),
        GetSystemConfiguration_ComputerNames ()
    };
}
<commit_msg>fixed typo in Configuration::GetSystemConfiguration ()<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2015.  All rights reserved
 */
#include    "../StroikaPreComp.h"

#include    <thread>

#if     qPlatform_POSIX
#include    <unistd.h>
#include    <fstream>
#elif   qPlatform_Windows
#include    <Windows.h>
#endif

#include    "../Characters/SDKString.h"
#include    "../Characters/Format.h"
#include    "../Characters/String_Constant.h"
#include    "../Characters/String2Int.h"
#include    "../Containers/Set.h"
#if     qPlatform_POSIX
#include    "../Execution/ErrNoException.h"
#elif   qPlatform_Windows
#include    "../Execution/Platform/Windows/Exception.h"
#endif
#include    "../Memory/SmallStackBuffer.h"
#include    "../IO/FileSystem/BinaryFileInputStream.h"
#include    "../Streams/BasicBinaryInputOutputStream.h"
#include    "../Streams/TextInputStreamBinaryAdapter.h"

#include    "SystemConfiguration.h"

#if     qPlatform_POSIX
#include    "../DataExchange/INI/Reader.h"
#include    "../Execution/ProcessRunner.h"
#include    "../Streams/iostream/FStreamSupport.h"
#endif

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Configuration;
using   namespace   Stroika::Foundation::Containers;
using   namespace   Stroika::Foundation::Streams;

using   Characters::String_Constant;
using   Characters::SDKChar;

// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define   USE_NOISY_TRACE_IN_THIS_MODULE_       1

/*
 ********************************************************************************
 ***************** Configuration::SystemConfiguration::CPU **********************
 ********************************************************************************
 */
unsigned int    SystemConfiguration::CPU::GetNumberOfSockets () const
{
    Set<unsigned int>   socketIds;
    for (auto i : fCores) {
        socketIds.Add (i.fSocketID);
    }
    return static_cast<unsigned int> (socketIds.size ());
}

/*
 ********************************************************************************
 *************** Configuration::GetSystemConfiguration_CPU **********************
 ********************************************************************************
 */
SystemConfiguration::CPU Configuration::GetSystemConfiguration_CPU ()
{
    using CPU = SystemConfiguration::CPU;
    CPU result;

#if     qPlatform_POSIX
    {
        using   Streams::TextInputStreamBinaryAdapter;
        using   IO::FileSystem::BinaryFileInputStream;
        using   Characters::String2Int;
        const   String_Constant kProcCPUInfoFileName_ { L"/proc/cpuinfo" };

        CPU::CoreDetails    coreDetails;
        // Note - /procfs files always unseekable
        for (String line : TextInputStreamBinaryAdapter (BinaryFileInputStream::mk (kProcCPUInfoFileName_, BinaryFileInputStream::eNotSeekable)).ReadLines ()) {
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
            DbgTrace (L"***in Configuration::GetSystemConfiguration_CPU capture_ line=%s", line.c_str ());
#endif
            static  const   String_Constant kModelNameLabel_ { L"model name	: " };
            //static    const   String_Constant kProcessorIDLabel_ { L"processor    : " };
            static  const   String_Constant kSocketIDLabel_ { L"physical id	: " };          // a bit of a guess?
            if (line.StartsWith (kModelNameLabel_)) {
                coreDetails.fModelName = line.SubString (kModelNameLabel_.length ()).Trim ();
            }
            else if (line.StartsWith (kSocketIDLabel_)) {
                unsigned int socketID = String2Int<unsigned int> (line.SubString (kSocketIDLabel_.length ()).Trim ());
                coreDetails.fSocketID = socketID;
            }
            if (line.Trim ().empty ()) {
                // ends each socket
                result.fCores.Append (coreDetails);
                coreDetails = CPU::CoreDetails ();
            }
        }
        if (coreDetails.fSocketID != 0 or not coreDetails.fModelName.empty ()) {
            result.fCores.Append (coreDetails);
        }
    }
#elif   qPlatform_Windows
    SYSTEM_INFO sysInfo;        // GetNativeSystemInfo cannot fail so no need to initialize data
    ::GetNativeSystemInfo (&sysInfo);
    //unclear if this is count of logical or physical cores, or how to compute the other.
    //@todo - fix as above for POSIX... maybe ask Sterl? But for now KISS
    //
    // Can use https://msdn.microsoft.com/en-us/library/hskdteyh%28v=vs.90%29.aspx?f=255&MSPPError=-2147217396
    //  __cpuid
    // to find this information (at least modelname string.
    //
    for (DWORD i = 0; i < sysInfo.dwNumberOfProcessors; ++i) {
        result.fCores.Append (CPU::CoreDetails ());
    }
#endif

    return result;
}

/*
 ********************************************************************************
 ************** Configuration::GetSystemConfiguration_Memory ********************
 ********************************************************************************
 */
SystemConfiguration::Memory Configuration::GetSystemConfiguration_Memory ()
{
    using   Memory = SystemConfiguration::Memory;
    Memory  result;
#if     qPlatform_POSIX
    result.fPageSize = ::sysconf (_SC_PAGESIZE);
    result.fTotalPhysicalRAM = ::sysconf (_SC_PHYS_PAGES) * result.fPageSize;
#elif   qPlatform_Windows
    SYSTEM_INFO sysInfo;
    ::GetNativeSystemInfo (&sysInfo);
    result.fPageSize = sysInfo.dwPageSize;

    MEMORYSTATUSEX memStatus;
    memStatus.dwLength = sizeof (memStatus);
    Verify (::GlobalMemoryStatusEx (&memStatus));
    result.fTotalPhysicalRAM = memStatus.ullTotalPhys;
    result.fTotalVirtualRAM = memStatus.ullTotalVirtual;
#endif
    return result;
}

/*
 ********************************************************************************
 ******** Configuration::GetSystemConfiguration_OperatingSystem *****************
 ********************************************************************************
 */
SystemConfiguration::OperatingSystem    Configuration::GetSystemConfiguration_OperatingSystem ()
{
    using   OperatingSystem =   SystemConfiguration::OperatingSystem;
    static  const   OperatingSystem    kCachedResult_ = []() ->OperatingSystem {
        OperatingSystem    tmp;
#if     qPlatform_POSIX
        tmp.fTokenName = String_Constant (L"Unix");
        try {
            tmp.fTokenName = Execution::ProcessRunner (L"uname").Run (String ()).Trim ();
        }
        catch (...)
        {
            DbgTrace ("Failure running uname");
        }
        try {
            ifstream s;
            Streams::iostream::OpenInputFileStream (&s, L"/etc/os-release");
            DataExchange::INI::Profile p = DataExchange::INI::Reader ().ReadProfile (s);
            tmp.fShortPrettyName = p.fUnnamedSection.fProperties.LookupValue (L"NAME");
            tmp.fPrettyNameWithMajorVersion = p.fUnnamedSection.fProperties.LookupValue (L"PRETTY_NAME");
        }
        catch (...)
        {
            DbgTrace ("Failure reading /etc/os-release");
        }
        if (tmp.fShortPrettyName.empty ())
        {
            tmp.fShortPrettyName = tmp.fTokenName;
        }
        if (tmp.fPrettyNameWithMajorVersion.empty ())
        {
            tmp.fPrettyNameWithMajorVersion = tmp.fShortPrettyName;
        }
        if (tmp.fRFC1945CompatProductTokenWithVersion.empty ())
        {
            tmp.fRFC1945CompatProductTokenWithVersion = tmp.fShortPrettyName.Trim ().ReplaceAll (L" ", L"-");
            if (not tmp.fMajorMinorVersionString.empty ()) {
                tmp.fRFC1945CompatProductTokenWithVersion += L"/" + tmp.fMajorMinorVersionString;
            }
        }
        //
        // @todo FIX/FIND BETTER WAY!
        //
        //http://docs.oracle.com/cd/E36784_01/html/E36874/sysconf-3c.html
        // Quite uncertain - this is not a good reference
        //      --LGP 2014-10-18
        //
        tmp.fBits = ::sysconf (_SC_V6_LP64_OFF64) == _POSIX_V6_LP64_OFF64 ? 64 : 32;
#elif   qPlatform_Windows
        tmp.fTokenName = String_Constant (L"Windows");
        /*
         *  Microslop declares this deprecated, but then fails to provide a reasonable alternative.
         *
         *  Sigh.
         *
         *  http://msdn.microsoft.com/en-us/library/windows/desktop/ms724429(v=vs.85).aspx -  GetFileVersionInfo (kernel32.dll)
         *  is a painful, and stupid alternative.
         */
        DISABLE_COMPILER_MSC_WARNING_START(4996)
        OSVERSIONINFOEX   osvi;
        memset(&osvi, 0, sizeof (osvi));
        osvi.dwOSVersionInfoSize = sizeof (osvi);
        Verify (::GetVersionEx (reinterpret_cast<LPOSVERSIONINFO> (&osvi)));
        DISABLE_COMPILER_MSC_WARNING_END(4996)
        if (osvi.dwMajorVersion == 6)
        {
            if (osvi.dwMinorVersion == 0) {
                tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows Vista") : String_Constant (L"Windows Server 2008");
            }
            else if (osvi.dwMinorVersion == 1) {
                tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows 7") : String_Constant (L"Windows Server 2008 R2");
            }
            else if (osvi.dwMinorVersion == 2) {
                tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows 8") : String_Constant (L"Windows Server 2012");
            }
            else if (osvi.dwMinorVersion == 3) {
                if (osvi.wProductType == VER_NT_WORKSTATION)
                    tmp.fShortPrettyName = String_Constant (L"Windows 8.1");
            }
        }
        if (tmp.fShortPrettyName.empty ())
        {
            tmp.fShortPrettyName = Characters::Format (L"Windows %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
        }
        tmp.fPrettyNameWithMajorVersion = tmp.fShortPrettyName;
        tmp.fMajorMinorVersionString = Characters::Format (L"%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
        tmp.fRFC1945CompatProductTokenWithVersion = Characters::Format (L"Windows/%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
        if (sizeof (void*) == 4)
        {
            tmp.fBits = 32;
            //IsWow64Process is not available on all supported versions of Windows.
            //Use GetModuleHandle to get a handle to the DLL that contains the function
            //and GetProcAddress to get a pointer to the function if available.
            typedef BOOL (WINAPI * LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
            LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process");
            if(NULL != fnIsWow64Process) {
                BOOL    isWOW64 = false;
                (void)fnIsWow64Process (GetCurrentProcess(), &isWOW64);
                if (isWOW64) {
                    tmp.fBits = 64;
                }
            }
        }
        else {
            // In windows, a 64 bit app cannot run on 32-bit windows
            Assert (sizeof (void*) == 8);
            tmp.fBits = 64;
        }
#else
        AssertNotImplemented ();
#endif
        return tmp;
    } ();
    return kCachedResult_;
}

/*
 ********************************************************************************
 ***************** GetSystemConfiguration_ComputerNames *************************
 ********************************************************************************
 */
#if     0 && qPlatform_POSIX
// ALTERNATE APPROACH TO CONSIDER
string  name;
{
    struct addrinfo* res;
    struct addrinfo hints;
    memset(&hints, '\0', sizeof(hints));
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_CANONNAME;
    int e = getaddrinfo(nullptr, nullptr, &hints, &res);
    if (e != 0) {
        //printf("failure %s\n", gai_strerror (e));
        return String ();
    }
    int sock = -1;
    for (struct addrinfo* r = res; r != NULL; r = r->ai_next) {
        name = r->ai_canonname ;
        break;
    }
    freeaddrinfo(res);
}
return String::FromSDKString (name);
#endif
SystemConfiguration::ComputerNames Configuration::GetSystemConfiguration_ComputerNames ()
{
    using ComputerNames = SystemConfiguration::ComputerNames;
    ComputerNames   result;
#if     qPlatform_POSIX
    char    nameBuf[1024];
    Execution::ThrowErrNoIfNegative (gethostname (nameBuf, NEltsOf (nameBuf)));
    nameBuf[NEltsOf (nameBuf) - 1] = '\0';  // http://linux.die.net/man/2/gethostname says not necessarily nul-terminated
    result.fHostname = String::FromNarrowSDKString (nameBuf);
#elif   qPlatform_Windows
    constexpr   COMPUTER_NAME_FORMAT    kUseNameFormat_ = ComputerNameNetBIOS;  // total WAG -- LGP 2014-10-10
    DWORD   dwSize = 0;
    (void) ::GetComputerNameEx (kUseNameFormat_, nullptr, &dwSize);
    Memory::SmallStackBuffer<SDKChar> buf(dwSize);
    Execution::Platform::Windows::ThrowIfFalseGetLastError (::GetComputerNameEx (kUseNameFormat_, buf, &dwSize));
    result.fHostname = String::FromSDKString (buf);
#else
    AssertNotImplemented ();
#endif
    return result;
}

/*
 ********************************************************************************
 ****************** SystemConfiguration GetSystemConfiguration ******************
 ********************************************************************************
 */
SystemConfiguration Configuration::GetSystemConfiguration ()
{
    return SystemConfiguration {
        GetSystemConfiguration_CPU (),
        GetSystemConfiguration_Memory (),
        GetSystemConfiguration_OperatingSystem (),
        GetSystemConfiguration_ComputerNames ()
    };
}
<|endoftext|>


<commit_before><commit_msg>update AddTask for MC<commit_after><|endoftext|>