<commit_before>#include "../Block_Diagonal_Matrix.hxx"

// Minimum eigenvalue of A.  A is assumed to be symmetric.

// Annoyingly, El::HermitianEig modifies 'block'.  It is OK, because
// it is only called from step_length(), which passes in a temporary.
// Still ugly.
El::BigFloat min_eigenvalue(Block_Diagonal_Matrix &A)
{
  El::BigFloat local_min(El::limits::Max<El::BigFloat>());

  for(auto &block : A.blocks)
    {
      El::DistMatrix<El::BigFloat, El::VR, El::STAR> eigenvalues(block.Grid());
      /// There is a bug in El::HermitianEig when there is more than
      /// one level of recursion when computing eigenvalues.  One fix
      /// is to increase the cutoff so that there is no more than one
      /// level of recursion.

      /// An alternate workaround is to compute both eigenvalues and
      /// eigenvectors, but that seems to be significantly slower.
      El::HermitianEigCtrl<El::BigFloat> hermitian_eig_ctrl;
      hermitian_eig_ctrl.tridiagEigCtrl.dcCtrl.cutoff=block.Height()/2+1;

      El::HermitianEig(El::UpperOrLowerNS::LOWER, block, eigenvalues);
      local_min = El::Min(local_min, El::Min(eigenvalues));
    }
  return El::mpi::AllReduce(local_min, El::mpi::MIN, El::mpi::COMM_WORLD);
}
<commit_msg>Really apply the eigenvalue workaround<commit_after>#include "../Block_Diagonal_Matrix.hxx"

// Minimum eigenvalue of A.  A is assumed to be symmetric.

// Annoyingly, El::HermitianEig modifies 'block'.  It is OK, because
// it is only called from step_length(), which passes in a temporary.
// Still ugly.
El::BigFloat min_eigenvalue(Block_Diagonal_Matrix &A)
{
  El::BigFloat local_min(El::limits::Max<El::BigFloat>());

  for(auto &block : A.blocks)
    {
      El::DistMatrix<El::BigFloat, El::VR, El::STAR> eigenvalues(block.Grid());
      /// There is a bug in El::HermitianEig when there is more than
      /// one level of recursion when computing eigenvalues.  One fix
      /// is to increase the cutoff so that there is no more than one
      /// level of recursion.

      /// An alternate workaround is to compute both eigenvalues and
      /// eigenvectors, but that seems to be significantly slower.
      El::HermitianEigCtrl<El::BigFloat> hermitian_eig_ctrl;
      hermitian_eig_ctrl.tridiagEigCtrl.dcCtrl.cutoff=block.Height()/2+1;

      El::HermitianEig(El::UpperOrLowerNS::LOWER, block, eigenvalues,
                       hermitian_eig_ctrl);
      local_min = El::Min(local_min, El::Min(eigenvalues));
    }
  return El::mpi::AllReduce(local_min, El::mpi::MIN, El::mpi::COMM_WORLD);
}
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// QUESO - a library to support the Quantification of Uncertainty
// for Estimation, Simulation and Optimization
//
// Copyright (C) 2008-2015 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

// This class
#include <queso/InterpolationSurrogateBuilder.h>

// QUESO
#include <queso/GslVector.h>
#include <queso/GslMatrix.h>
#include <queso/InterpolationSurrogateHelper.h>

// C++
#include <numeric>

namespace QUESO
{
  template<class V, class M>
  InterpolationSurrogateBuilder<V,M>::InterpolationSurrogateBuilder( InterpolationSurrogateData<V,M>& data )
    : SurrogateBuilderBase<V>(),
    m_data(data),
    m_njobs(data.get_paramDomain().env().numSubEnvironments(), 0)
  {
    this->partition_work();
  }

  template<class V, class M>
  void InterpolationSurrogateBuilder<V,M>::partition_work()
  {
    // Convenience
    unsigned int n_values = this->m_data.n_values();
    unsigned int n_workers = this->m_data.get_paramDomain().env().numSubEnvironments();

    unsigned int n_jobs = n_values/n_workers;
    unsigned int n_leftover = this->m_data.n_values() % n_workers;

    /* If the number of values is evenly divisible over all workers,
       then everyone gets the same amount work */
    if( n_leftover  == 0 )
      {
        for(unsigned int n = 0; n < n_workers; n++)
          this->m_njobs[n] = n_jobs;
      }
    /* Otherwise, some workers get more work than others*/
    else
      {
        for(unsigned int n = 0; n < n_workers; n++)
          {
            if( n < n_leftover )
              this->m_njobs[n] = n_jobs+1;
            else
              this->m_njobs[n] = n_jobs;
          }
      }

    // Sanity check
    queso_assert_equal_to( n_values, std::accumulate( m_njobs.begin(), m_njobs.end(), 0 ) );
  }

  template<class V, class M>
  void InterpolationSurrogateBuilder<V,M>::build_values()
  {
    unsigned int n_begin, n_end;
    this->set_work_bounds( n_begin, n_end );

    // Cache each processors work, then we only need to do 1 Allgather
    std::vector<unsigned int> local_n(n_end-n_begin);
    std::vector<double> local_values(n_end-n_begin);
    unsigned int count = 0;

    // vector to store current domain value
    V domain_vector(this->m_data.get_paramDomain().vectorSpace().zeroVector());

    for( unsigned int n = n_begin; n < n_end; n++ )
      {
        this->set_domain_vector( n, domain_vector );

        double value = this->evaluate_model( domain_vector );

        local_n[count] = n;
        local_values[count] = value;
        count += 1;
      }

    /* Sync all the locally computed values between the subenvironments
       so all processes have all the computed values. */
    this->sync_data( local_n, local_values );
  }

  template<class V, class M>
  void InterpolationSurrogateBuilder<V,M>::set_work_bounds( unsigned int& n_begin, unsigned int& n_end ) const
  {
    unsigned int my_subid = this->m_data.get_paramDomain().env().subId();

    /* Starting index will be the sum of the all the previous num jobs */
    n_begin = 0;
    for( unsigned int n = 0; n < my_subid; n++ )
      n_begin += m_njobs[n];

    n_end = n_begin + m_njobs[my_subid];
  }

  template<class V, class M>
  void InterpolationSurrogateBuilder<V,M>::sync_data( std::vector<unsigned int>& local_n,
                                                      std::vector<double>& local_values  )
  {
    // Scope this so we can be rid of all_indices/all_values when we're done.
    {
      std::vector<unsigned int> all_indices(this->m_data.n_values());
      std::vector<double> all_values(this->m_data.n_values());

      MPI_Comm comm = this->m_data.get_paramDomain().env().inter0Comm().Comm();

      int ierr = MPI_Allgather(&local_n[0], local_n.size(), MPI_UNSIGNED, &all_indices[0], all_indices.size(), MPI_UNSIGNED, comm );
      if( ierr != 0 )
        queso_error_msg("ERROR: Something bad happened in the MPI_Allgather");

      ierr = MPI_Allgather(&local_values[0], local_values.size(), MPI_DOUBLE, &all_values[0], all_values.size(), MPI_DOUBLE, comm );
      if( ierr != 0 )
        queso_error_msg("ERROR: Something bad happened in the MPI_Allgather");

      // Now set the values.
      /* PB: Although we are guaranteed per-rank ordering of the data we gathered,
         I'm not sure we can assume the same continuity of the inter0 ranks, i.e.
         I'm not sure how QUESO ordered the inter0 ranks. So, we go ahead and
         manually set the values. */
      if( this->m_data.get_paramDomain().env().subRank() == 0 )
        {
          for( unsigned int n = 0; n < this->m_data.n_values(); n++ )
            this->m_data.set_value( all_indices[n], all_values[n] );
        }
    }

    /* Now all rank 0 of each subEnvironment has the data. Now need to broadcast
       to remainder of subEnvironment processes (if the subenvironment size > 1). */
    /*! \todo PB: I'm not sure this is actually needed, but doing it just to be sure. */
    if( this->m_data.get_paramDomain().env().subComm().NumProc() > 1 )
      {
        std::vector<double>& values = this->m_data.get_values();
        MPI_Comm comm = this->m_data.get_paramDomain().env().subComm().Comm();

        int ierr = MPI_Bcast( &values[0], values.size(), MPI_DOUBLE, 0, comm );
        if( ierr != 0 )
          queso_error_msg("ERROR: Something bad happened in the MPI_Bcast");
      }
  }

  template<class V, class M>
  void InterpolationSurrogateBuilder<V,M>::set_domain_vector( unsigned int n, V& domain_vector ) const
  {
    // Convert global index n to local coordinates in each dimension
    std::vector<unsigned int> indices(this->m_data.dim());
    InterpolationSurrogateHelper::globalToCoord( n, this->m_data.get_n_points(), indices );

    // Use indices to get x coordinates and populate domain_vector
    for( unsigned int d = 0; d < this->m_data.dim(); d++ )
      {
        domain_vector[d] = this->m_data.get_x( d, indices[d] );
      }
  }

} // end namespace QUESO

// Instantiate
template class QUESO::InterpolationSurrogateBuilder<QUESO::GslVector,QUESO::GslMatrix>;
<commit_msg>MPI_Allgather wants data received *per process*<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// QUESO - a library to support the Quantification of Uncertainty
// for Estimation, Simulation and Optimization
//
// Copyright (C) 2008-2015 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

// This class
#include <queso/InterpolationSurrogateBuilder.h>

// QUESO
#include <queso/GslVector.h>
#include <queso/GslMatrix.h>
#include <queso/InterpolationSurrogateHelper.h>

// C++
#include <numeric>

namespace QUESO
{
  template<class V, class M>
  InterpolationSurrogateBuilder<V,M>::InterpolationSurrogateBuilder( InterpolationSurrogateData<V,M>& data )
    : SurrogateBuilderBase<V>(),
    m_data(data),
    m_njobs(data.get_paramDomain().env().numSubEnvironments(), 0)
  {
    this->partition_work();
  }

  template<class V, class M>
  void InterpolationSurrogateBuilder<V,M>::partition_work()
  {
    // Convenience
    unsigned int n_values = this->m_data.n_values();
    unsigned int n_workers = this->m_data.get_paramDomain().env().numSubEnvironments();

    unsigned int n_jobs = n_values/n_workers;
    unsigned int n_leftover = this->m_data.n_values() % n_workers;

    /* If the number of values is evenly divisible over all workers,
       then everyone gets the same amount work */
    if( n_leftover  == 0 )
      {
        for(unsigned int n = 0; n < n_workers; n++)
          this->m_njobs[n] = n_jobs;
      }
    /* Otherwise, some workers get more work than others*/
    else
      {
        for(unsigned int n = 0; n < n_workers; n++)
          {
            if( n < n_leftover )
              this->m_njobs[n] = n_jobs+1;
            else
              this->m_njobs[n] = n_jobs;
          }
      }

    // Sanity check
    queso_assert_equal_to( n_values, std::accumulate( m_njobs.begin(), m_njobs.end(), 0 ) );
  }

  template<class V, class M>
  void InterpolationSurrogateBuilder<V,M>::build_values()
  {
    unsigned int n_begin, n_end;
    this->set_work_bounds( n_begin, n_end );

    // Cache each processors work, then we only need to do 1 Allgather
    std::vector<unsigned int> local_n(n_end-n_begin);
    std::vector<double> local_values(n_end-n_begin);
    unsigned int count = 0;

    // vector to store current domain value
    V domain_vector(this->m_data.get_paramDomain().vectorSpace().zeroVector());

    for( unsigned int n = n_begin; n < n_end; n++ )
      {
        this->set_domain_vector( n, domain_vector );

        double value = this->evaluate_model( domain_vector );

        local_n[count] = n;
        local_values[count] = value;
        count += 1;
      }

    /* Sync all the locally computed values between the subenvironments
       so all processes have all the computed values. */
    this->sync_data( local_n, local_values );
  }

  template<class V, class M>
  void InterpolationSurrogateBuilder<V,M>::set_work_bounds( unsigned int& n_begin, unsigned int& n_end ) const
  {
    unsigned int my_subid = this->m_data.get_paramDomain().env().subId();

    /* Starting index will be the sum of the all the previous num jobs */
    n_begin = 0;
    for( unsigned int n = 0; n < my_subid; n++ )
      n_begin += m_njobs[n];

    n_end = n_begin + m_njobs[my_subid];
  }

  template<class V, class M>
  void InterpolationSurrogateBuilder<V,M>::sync_data( std::vector<unsigned int>& local_n,
                                                      std::vector<double>& local_values  )
  {
    // Scope this so we can be rid of all_indices/all_values when we're done.
    {
      std::vector<unsigned int> all_indices(this->m_data.n_values());
      std::vector<double> all_values(this->m_data.n_values());

      MPI_Comm comm = this->m_data.get_paramDomain().env().inter0Comm().Comm();

      // Gather the local data all together on each subrank 0 processor.
      int ierr = MPI_Allgather(&local_n[0], local_n.size(), MPI_UNSIGNED,
                               &all_indices[0], local_n.size(), MPI_UNSIGNED, comm );
      if( ierr != 0 )
        queso_error_msg("ERROR: Something bad happened in the MPI_Allgather");

      ierr = MPI_Allgather(&local_values[0], local_values.size(), MPI_DOUBLE,
                           &all_values[0], local_values.size(), MPI_DOUBLE, comm );
      if( ierr != 0 )
        queso_error_msg("ERROR: Something bad happened in the MPI_Allgather");

      // Now set the values.
      /* PB: Although we are guaranteed per-rank ordering of the data we gathered,
         I'm not sure we can assume the same continuity of the inter0 ranks, i.e.
         I'm not sure how QUESO ordered the inter0 ranks. So, we go ahead and
         manually set the values. */
      if( this->m_data.get_paramDomain().env().subRank() == 0 )
        {
          for( unsigned int n = 0; n < this->m_data.n_values(); n++ )
            this->m_data.set_value( all_indices[n], all_values[n] );
        }
    }

    /* Now all rank 0 of each subEnvironment has the data. Now need to broadcast
       to remainder of subEnvironment processes (if the subenvironment size > 1). */
    /*! \todo PB: I'm not sure this is actually needed, but doing it just to be sure. */
    if( this->m_data.get_paramDomain().env().subComm().NumProc() > 1 )
      {
        std::vector<double>& values = this->m_data.get_values();
        MPI_Comm comm = this->m_data.get_paramDomain().env().subComm().Comm();

        int ierr = MPI_Bcast( &values[0], values.size(), MPI_DOUBLE, 0, comm );
        if( ierr != 0 )
          queso_error_msg("ERROR: Something bad happened in the MPI_Bcast");
      }
  }

  template<class V, class M>
  void InterpolationSurrogateBuilder<V,M>::set_domain_vector( unsigned int n, V& domain_vector ) const
  {
    // Convert global index n to local coordinates in each dimension
    std::vector<unsigned int> indices(this->m_data.dim());
    InterpolationSurrogateHelper::globalToCoord( n, this->m_data.get_n_points(), indices );

    // Use indices to get x coordinates and populate domain_vector
    for( unsigned int d = 0; d < this->m_data.dim(); d++ )
      {
        domain_vector[d] = this->m_data.get_x( d, indices[d] );
      }
  }

} // end namespace QUESO

// Instantiate
template class QUESO::InterpolationSurrogateBuilder<QUESO::GslVector,QUESO::GslMatrix>;
<|endoftext|>


<commit_before>#include <test/test-models/good/variational/eta_should_be_small.hpp>
#include <stan/variational/advi.hpp>
#include <stan/callbacks/stream_logger.hpp>
#include <gtest/gtest.h>
#include <test/unit/util.hpp>
#include <vector>
#include <string>
#include <iostream>
#include <boost/random/additive_combine.hpp> // L'Ecuyer RNG
#include <boost/version.hpp>

typedef boost::ecuyer1988 rng_t;

class eta_adapt_small_test : public ::testing::Test {
public:
  eta_adapt_small_test()
    : logger(log_stream_, log_stream_, log_stream_, log_stream_, log_stream_) { }

  void SetUp() {
    static const std::string DATA = "";
    std::stringstream data_stream(DATA);
    stan::io::dump data_var_context(data_stream);

    model_ = new stan_model(data_var_context, &model_stream_);
    cont_params_ = Eigen::VectorXd::Zero(model_->num_params_r());
    base_rng_.seed(727802408);
    model_stream_.str("");
    log_stream_.str("");

    advi_meanfield_ = new stan::variational::advi<stan_model, stan::variational::normal_meanfield, rng_t>
      (*model_, cont_params_, base_rng_,
       1, 100,
       100, 1);

    advi_fullrank_ = new stan::variational::advi<stan_model, stan::variational::normal_fullrank, rng_t>
      (*model_, cont_params_, base_rng_,
       1, 100,
       100, 1);
  }

  void TearDown() {
    delete advi_meanfield_;
    delete advi_fullrank_;
    delete model_;
  }

  stan::variational::advi<stan_model, stan::variational::normal_meanfield, rng_t> *advi_meanfield_;
  stan::variational::advi<stan_model, stan::variational::normal_fullrank, rng_t> *advi_fullrank_;
  std::stringstream model_stream_;
  std::stringstream log_stream_;
  stan::callbacks::stream_logger logger;

  stan_model *model_;
  rng_t base_rng_;
  Eigen::VectorXd cont_params_;
};

TEST_F(eta_adapt_small_test, eta_should_be_small) {
  stan::variational::normal_meanfield meanfield_init =
    stan::variational::normal_meanfield(cont_params_);
  stan::variational::normal_fullrank fullrank_init =
    stan::variational::normal_fullrank(cont_params_);

#if BOOST_VERSION == 106400
  EXPECT_EQ(0.1, advi_meanfield_->adapt_eta(meanfield_init, 1000, logger));
  EXPECT_EQ(0.1, advi_fullrank_->adapt_eta(fullrank_init, 1000, logger));
#else
  EXPECT_EQ(0.1, advi_meanfield_->adapt_eta(meanfield_init, 50, logger));
  EXPECT_EQ(0.1, advi_fullrank_->adapt_eta(fullrank_init, 50, logger));
#endif
}
<commit_msg>generalize boost version check in ADVI tests<commit_after>#include <test/test-models/good/variational/eta_should_be_small.hpp>
#include <stan/variational/advi.hpp>
#include <stan/callbacks/stream_logger.hpp>
#include <gtest/gtest.h>
#include <test/unit/util.hpp>
#include <vector>
#include <string>
#include <iostream>
#include <boost/random/additive_combine.hpp> // L'Ecuyer RNG
#include <boost/version.hpp>

typedef boost::ecuyer1988 rng_t;

class eta_adapt_small_test : public ::testing::Test {
public:
  eta_adapt_small_test()
    : logger(log_stream_, log_stream_, log_stream_, log_stream_, log_stream_) { }

  void SetUp() {
    static const std::string DATA = "";
    std::stringstream data_stream(DATA);
    stan::io::dump data_var_context(data_stream);

    model_ = new stan_model(data_var_context, &model_stream_);
    cont_params_ = Eigen::VectorXd::Zero(model_->num_params_r());
    base_rng_.seed(727802408);
    model_stream_.str("");
    log_stream_.str("");

    advi_meanfield_ = new stan::variational::advi<stan_model, stan::variational::normal_meanfield, rng_t>
      (*model_, cont_params_, base_rng_,
       1, 100,
       100, 1);

    advi_fullrank_ = new stan::variational::advi<stan_model, stan::variational::normal_fullrank, rng_t>
      (*model_, cont_params_, base_rng_,
       1, 100,
       100, 1);
  }

  void TearDown() {
    delete advi_meanfield_;
    delete advi_fullrank_;
    delete model_;
  }

  stan::variational::advi<stan_model, stan::variational::normal_meanfield, rng_t> *advi_meanfield_;
  stan::variational::advi<stan_model, stan::variational::normal_fullrank, rng_t> *advi_fullrank_;
  std::stringstream model_stream_;
  std::stringstream log_stream_;
  stan::callbacks::stream_logger logger;

  stan_model *model_;
  rng_t base_rng_;
  Eigen::VectorXd cont_params_;
};

TEST_F(eta_adapt_small_test, eta_should_be_small) {
  stan::variational::normal_meanfield meanfield_init =
    stan::variational::normal_meanfield(cont_params_);
  stan::variational::normal_fullrank fullrank_init =
    stan::variational::normal_fullrank(cont_params_);

#if BOOST_VERSION > 106400
  EXPECT_EQ(0.1, advi_meanfield_->adapt_eta(meanfield_init, 1000, logger));
  EXPECT_EQ(0.1, advi_fullrank_->adapt_eta(fullrank_init, 1000, logger));
#else
  EXPECT_EQ(0.1, advi_meanfield_->adapt_eta(meanfield_init, 50, logger));
  EXPECT_EQ(0.1, advi_fullrank_->adapt_eta(fullrank_init, 50, logger));
#endif
}
<|endoftext|>


<commit_before>// Copyright 2014 Toggl Desktop developers.

#include "./mainwindowcontroller.h"
#include "./ui_mainwindowcontroller.h"

#include <iostream>  // NOLINT

#include <QAction>  // NOLINT
#include <QCloseEvent>  // NOLINT
#include <QtConcurrent/QtConcurrent>  // NOLINT
#include <QDebug>  // NOLINT
#include <QDesktopServices>  // NOLINT
#include <QImageReader>  // NOLINT
#include <QLabel>  // NOLINT
#include <QMenu>  // NOLINT
#include <QMessageBox>  // NOLINT
#include <QSettings>  // NOLINT
#include <QVBoxLayout>  // NOLINT
#include <QStatusBar>  // NOLINT

#include "./toggl.h"
#include "./errorviewcontroller.h"
#include "./loginwidget.h"
#include "./timeentrylistwidget.h"
#include "./timeentryeditorwidget.h"

MainWindowController::MainWindowController(
    QWidget *parent,
    QString logPathOverride,
    QString dbPathOverride,
    QString scriptPath)
    : QMainWindow(parent),
  ui(new Ui::MainWindowController),
  togglApi(new TogglApi(0, logPathOverride, dbPathOverride)),
  tracking(false),
  loggedIn(false),
  actionEmail(0),
  actionNew(0),
  actionContinue(0),
  actionStop(0),
  actionSync(0),
  actionLogout(0),
  actionClear_Cache(0),
  actionSend_Feedback(0),
  actionReports(0),
  preferencesDialog(new PreferencesDialog(this)),
  aboutDialog(new AboutDialog(this)),
  feedbackDialog(new FeedbackDialog(this)),
  idleNotificationDialog(new IdleNotificationDialog(this)),
  trayIcon(0),
  reminder(false),
  script(scriptPath),
  ui_started(false) {
    TogglApi::instance->setEnvironment(APP_ENVIRONMENT);

    ui->setupUi(this);

    ui->menuBar->setVisible(true);

    QVBoxLayout *verticalLayout = new QVBoxLayout();
    verticalLayout->addWidget(new ErrorViewController());
    verticalLayout->addWidget(new LoginWidget());
    verticalLayout->addWidget(new TimeEntryListWidget());
    verticalLayout->addWidget(new TimeEntryEditorWidget());
    verticalLayout->setContentsMargins(0, 0, 0, 0);
    verticalLayout->setSpacing(0);
    centralWidget()->setLayout(verticalLayout);

    readSettings();

    connect(QApplication::instance(), SIGNAL(showUp()),
            this, SLOT(raise()));

    connect(TogglApi::instance, SIGNAL(displayApp(bool)),  // NOLINT
            this, SLOT(displayApp(bool)));  // NOLINT

    connect(TogglApi::instance, SIGNAL(displayStoppedTimerState()),  // NOLINT
            this, SLOT(displayStoppedTimerState()));  // NOLINT

    connect(TogglApi::instance, SIGNAL(displayRunningTimerState(TimeEntryView*)),  // NOLINT
            this, SLOT(displayRunningTimerState(TimeEntryView*)));  // NOLINT

    connect(TogglApi::instance, SIGNAL(displayLogin(bool,uint64_t)),  // NOLINT
            this, SLOT(displayLogin(bool,uint64_t)));  // NOLINT

    connect(TogglApi::instance, SIGNAL(displayReminder(QString,QString)),  // NOLINT
            this, SLOT(displayReminder(QString,QString)));  // NOLINT

    connect(TogglApi::instance, SIGNAL(displayUpdate(QString)),  // NOLINT
            this, SLOT(displayUpdate(QString)));  // NOLINT

    connect(TogglApi::instance, SIGNAL(displayOnlineState(int64_t)),  // NOLINT
            this, SLOT(displayOnlineState(int64_t)));  // NOLINT

    hasTrayIconCached = hasTrayIcon();
    if (hasTrayIconCached) {
        icon.addFile(QString::fromUtf8(":/icons/1024x1024/toggldesktop.png"));

        iconDisabled.addFile(QString::fromUtf8(
            ":/icons/1024x1024/toggldesktop_gray.png"));

        trayIcon = new QSystemTrayIcon(this);
    }

    connectMenuActions();
    enableMenuActions();

    if (hasTrayIconCached) {
        // icon is set in enableMenuActions based on if tracking is in progress
        trayIcon->show();
    } else {
        setWindowIcon(icon);
    }
}

MainWindowController::~MainWindowController() {
    delete togglApi;
    togglApi = 0;

    delete ui;
}

void MainWindowController::displayOnlineState(
    int64_t state) {

    switch (state) {
    case 0:  // online
        statusBar()->clearMessage();
        break;
    case 1:  // no network
        statusBar()->showMessage("Status: Offline, no network");
        break;
    case 2:  // backend down
        statusBar()->showMessage("Status: Offline, Toggl not responding");
        break;
    default:
        qDebug() << "Unknown online state " << state;
        break;
    }
}

void MainWindowController::displayReminder(
    const QString title,
    const QString informative_text) {

    if (reminder) {
        return;
    }
    reminder = true;

    QMessageBox(
        QMessageBox::Information,
        title,
        informative_text,
        QMessageBox::Ok).exec();

    reminder = false;
}

void MainWindowController::displayLogin(
    const bool open,
    const uint64_t user_id) {

    loggedIn = !open && user_id;
    enableMenuActions();
}

void MainWindowController::displayRunningTimerState(
    TimeEntryView *te) {
    tracking = true;
    enableMenuActions();
}

void MainWindowController::displayStoppedTimerState() {
    tracking = false;
    enableMenuActions();
}

void MainWindowController::enableMenuActions() {
    actionNew->setEnabled(loggedIn);
    actionContinue->setEnabled(loggedIn && !tracking);
    actionStop->setEnabled(loggedIn && tracking);
    actionSync->setEnabled(loggedIn);
    actionLogout->setEnabled(loggedIn);
    actionClear_Cache->setEnabled(loggedIn);
    actionSend_Feedback->setEnabled(loggedIn);
    actionReports->setEnabled(loggedIn);
    actionEmail->setText(TogglApi::instance->userEmail());
    if (hasTrayIconCached) {
        if (tracking) {
            trayIcon->setIcon(icon);
            setWindowIcon(icon);
        } else {
            trayIcon->setIcon(iconDisabled);
            setWindowIcon(iconDisabled);
        }
    }
}

void MainWindowController::connectMenuActions() {
    foreach(QMenu *menu, ui->menuBar->findChildren<QMenu *>()) {
        if (trayIcon) {
            trayIcon->setContextMenu(menu);
        }
        foreach(QAction *action, menu->actions()) {
            connectMenuAction(action);
        }
    }
}

void MainWindowController::connectMenuAction(
    QAction *action) {
    if ("actionEmail" == action->objectName()) {
        actionEmail = action;
    } else if ("actionNew" == action->objectName()) {
        actionNew = action;
        connect(action, SIGNAL(triggered()), this, SLOT(onActionNew()));
    } else if ("actionContinue" == action->objectName()) {
        actionContinue = action;
        connect(action, SIGNAL(triggered()), this, SLOT(onActionContinue()));
    } else if ("actionStop" == action->objectName()) {
        actionStop = action;
        connect(action, SIGNAL(triggered()), this, SLOT(onActionStop()));
    } else if ("actionSync" == action->objectName()) {
        actionSync = action;
        connect(action, SIGNAL(triggered()), this, SLOT(onActionSync()));
    } else if ("actionLogout" == action->objectName()) {
        actionLogout = action;
        connect(action, SIGNAL(triggered()), this, SLOT(onActionLogout()));
    } else if ("actionClear_Cache" == action->objectName()) {
        actionClear_Cache = action;
        connect(action, SIGNAL(triggered()), this, SLOT(onActionClear_Cache()));
    } else if ("actionSend_Feedback" == action->objectName()) {
        actionSend_Feedback = action;
        connect(action, SIGNAL(triggered()),
                this, SLOT(onActionSend_Feedback()));
    } else if ("actionReports" == action->objectName()) {
        actionReports = action;
        connect(action, SIGNAL(triggered()), this, SLOT(onActionReports()));
    } else if ("actionShow" == action->objectName()) {
        connect(action, SIGNAL(triggered()), this, SLOT(onActionShow()));
    } else if ("actionPreferences" == action->objectName()) {
        connect(action, SIGNAL(triggered()), this, SLOT(onActionPreferences()));
    } else if ("actionAbout" == action->objectName()) {
        connect(action, SIGNAL(triggered()), this, SLOT(onActionAbout()));
    } else if ("actionQuit" == action->objectName()) {
        connect(action, SIGNAL(triggered()), this, SLOT(onActionQuit()));
    } else if ("actionHelp" == action->objectName()) {
        connect(action, SIGNAL(triggered()), this, SLOT(onActionHelp()));
    }
}

void MainWindowController::onActionNew() {
    TogglApi::instance->start("", "", 0, 0);
}

void MainWindowController::onActionContinue() {
    TogglApi::instance->continueLatestTimeEntry();
}

void MainWindowController::onActionStop() {
    TogglApi::instance->stop();
}

void MainWindowController::onActionShow() {
    displayApp(true);
}

void MainWindowController::onActionSync() {
    TogglApi::instance->sync();
}

void MainWindowController::onActionReports() {
    TogglApi::instance->openInBrowser();
}

void MainWindowController::onActionPreferences() {
    TogglApi::instance->editPreferences();
}

void MainWindowController::onActionAbout() {
    aboutDialog->show();
}

void MainWindowController::onActionSend_Feedback() {
    feedbackDialog->show();
}

void MainWindowController::onActionLogout() {
    TogglApi::instance->logout();
}

void MainWindowController::onActionQuit() {
    quitApp();
}

void MainWindowController::quitApp() {
    TogglApi::instance->shutdown = true;
    qApp->exit(0);
}

void MainWindowController::onActionClear_Cache() {
    if (QMessageBox::Ok == QMessageBox(
        QMessageBox::Question,
        "Clear Cache?",
        "Clearing cache will delete any unsaved time entries and log you out.",
        QMessageBox::Ok|QMessageBox::Cancel).exec()) {
        TogglApi::instance->clearCache();
    }
}

void MainWindowController::onActionHelp() {
    TogglApi::instance->getSupport();
}

void MainWindowController::displayApp(const bool open) {
    if (open) {
        show();
        raise();
    }
}

void MainWindowController::readSettings() {
    QSettings settings("Toggl", "TogglDesktop");
    restoreGeometry(settings.value("geometry").toByteArray());
    restoreState(settings.value("windowState").toByteArray());
}

void MainWindowController::writeSettings() {
    QSettings settings("Toggl", "TogglDesktop");
    settings.setValue("geometry", saveGeometry());
    settings.setValue("windowState", saveState());
}

void MainWindowController::closeEvent(QCloseEvent *event) {
    QMessageBox::StandardButton dialog;
    dialog = QMessageBox::question(this,
                                   "Toggl Desktop",
                                   "Really quit the app?",
                                   QMessageBox::Ok | QMessageBox::Cancel);
    if (QMessageBox::Ok == dialog) {
        writeSettings();
        close();
    } else {
        event->ignore();
        return;
    }

    QMainWindow::closeEvent(event);
}

bool MainWindowController::hasTrayIcon() const {
#if (QT_VERSION >= QT_VERSION_CHECK(5, 5, 0))
    return true;
#endif
    QString currentDesktop = QProcessEnvironment::systemEnvironment().value(
        "XDG_CURRENT_DESKTOP", "");
    return "Unity" != currentDesktop;
}

void MainWindowController::showEvent(QShowEvent *event) {
    QMainWindow::showEvent(event);

    // Avoid 'user already logged in' error from double UI start
    if (ui_started) {
        return;
    }
    ui_started = true;

    if (!TogglApi::instance->startEvents()) {
        QMessageBox(
            QMessageBox::Warning,
            "Error",
            "The application could not start. Please inspect the log file.",
            QMessageBox::Ok|QMessageBox::Cancel).exec();
        return;
    }
    if (script.isEmpty()) {
        qDebug() << "no script to run";
        return;
    }
    qDebug() << "will run script: " << script;

    QtConcurrent::run(this, &MainWindowController::runScript);
}

void MainWindowController::displayUpdate(const QString url) {
    if (aboutDialog->isVisible()
            || url.isEmpty()) {
        return;
    }
    if (QMessageBox::Yes == QMessageBox(
        QMessageBox::Question,
        "Download new version?",
        "A new version of Toggl Desktop is available. Continue with download?",
        QMessageBox::No|QMessageBox::Yes).exec()) {
        QDesktopServices::openUrl(QUrl(url));
        quitApp();
    }
}

void MainWindowController::runScript() {
    if (TogglApi::instance->runScriptFile(script)) {
        quitApp();
    }
}
<commit_msg>Hide app when tray icon is present, fixes #1342 (linux)<commit_after>// Copyright 2014 Toggl Desktop developers.

#include "./mainwindowcontroller.h"
#include "./ui_mainwindowcontroller.h"

#include <iostream>  // NOLINT

#include <QAction>  // NOLINT
#include <QCloseEvent>  // NOLINT
#include <QtConcurrent/QtConcurrent>  // NOLINT
#include <QDebug>  // NOLINT
#include <QDesktopServices>  // NOLINT
#include <QImageReader>  // NOLINT
#include <QLabel>  // NOLINT
#include <QMenu>  // NOLINT
#include <QMessageBox>  // NOLINT
#include <QSettings>  // NOLINT
#include <QVBoxLayout>  // NOLINT
#include <QStatusBar>  // NOLINT

#include "./toggl.h"
#include "./errorviewcontroller.h"
#include "./loginwidget.h"
#include "./timeentrylistwidget.h"
#include "./timeentryeditorwidget.h"

MainWindowController::MainWindowController(
    QWidget *parent,
    QString logPathOverride,
    QString dbPathOverride,
    QString scriptPath)
    : QMainWindow(parent),
  ui(new Ui::MainWindowController),
  togglApi(new TogglApi(0, logPathOverride, dbPathOverride)),
  tracking(false),
  loggedIn(false),
  actionEmail(0),
  actionNew(0),
  actionContinue(0),
  actionStop(0),
  actionSync(0),
  actionLogout(0),
  actionClear_Cache(0),
  actionSend_Feedback(0),
  actionReports(0),
  preferencesDialog(new PreferencesDialog(this)),
  aboutDialog(new AboutDialog(this)),
  feedbackDialog(new FeedbackDialog(this)),
  idleNotificationDialog(new IdleNotificationDialog(this)),
  trayIcon(0),
  reminder(false),
  script(scriptPath),
  ui_started(false) {
    TogglApi::instance->setEnvironment(APP_ENVIRONMENT);

    ui->setupUi(this);

    ui->menuBar->setVisible(true);

    QVBoxLayout *verticalLayout = new QVBoxLayout();
    verticalLayout->addWidget(new ErrorViewController());
    verticalLayout->addWidget(new LoginWidget());
    verticalLayout->addWidget(new TimeEntryListWidget());
    verticalLayout->addWidget(new TimeEntryEditorWidget());
    verticalLayout->setContentsMargins(0, 0, 0, 0);
    verticalLayout->setSpacing(0);
    centralWidget()->setLayout(verticalLayout);

    readSettings();

    connect(QApplication::instance(), SIGNAL(showUp()),
            this, SLOT(raise()));

    connect(TogglApi::instance, SIGNAL(displayApp(bool)),  // NOLINT
            this, SLOT(displayApp(bool)));  // NOLINT

    connect(TogglApi::instance, SIGNAL(displayStoppedTimerState()),  // NOLINT
            this, SLOT(displayStoppedTimerState()));  // NOLINT

    connect(TogglApi::instance, SIGNAL(displayRunningTimerState(TimeEntryView*)),  // NOLINT
            this, SLOT(displayRunningTimerState(TimeEntryView*)));  // NOLINT

    connect(TogglApi::instance, SIGNAL(displayLogin(bool,uint64_t)),  // NOLINT
            this, SLOT(displayLogin(bool,uint64_t)));  // NOLINT

    connect(TogglApi::instance, SIGNAL(displayReminder(QString,QString)),  // NOLINT
            this, SLOT(displayReminder(QString,QString)));  // NOLINT

    connect(TogglApi::instance, SIGNAL(displayUpdate(QString)),  // NOLINT
            this, SLOT(displayUpdate(QString)));  // NOLINT

    connect(TogglApi::instance, SIGNAL(displayOnlineState(int64_t)),  // NOLINT
            this, SLOT(displayOnlineState(int64_t)));  // NOLINT

    hasTrayIconCached = hasTrayIcon();
    if (hasTrayIconCached) {
        icon.addFile(QString::fromUtf8(":/icons/1024x1024/toggldesktop.png"));

        iconDisabled.addFile(QString::fromUtf8(
            ":/icons/1024x1024/toggldesktop_gray.png"));

        trayIcon = new QSystemTrayIcon(this);
    }

    connectMenuActions();
    enableMenuActions();

    if (hasTrayIconCached) {
        // icon is set in enableMenuActions based on if tracking is in progress
        trayIcon->show();
    } else {
        setWindowIcon(icon);
    }
}

MainWindowController::~MainWindowController() {
    delete togglApi;
    togglApi = 0;

    delete ui;
}

void MainWindowController::displayOnlineState(
    int64_t state) {

    switch (state) {
    case 0:  // online
        statusBar()->clearMessage();
        break;
    case 1:  // no network
        statusBar()->showMessage("Status: Offline, no network");
        break;
    case 2:  // backend down
        statusBar()->showMessage("Status: Offline, Toggl not responding");
        break;
    default:
        qDebug() << "Unknown online state " << state;
        break;
    }
}

void MainWindowController::displayReminder(
    const QString title,
    const QString informative_text) {

    if (reminder) {
        return;
    }
    reminder = true;

    QMessageBox(
        QMessageBox::Information,
        title,
        informative_text,
        QMessageBox::Ok).exec();

    reminder = false;
}

void MainWindowController::displayLogin(
    const bool open,
    const uint64_t user_id) {

    loggedIn = !open && user_id;
    enableMenuActions();
}

void MainWindowController::displayRunningTimerState(
    TimeEntryView *te) {
    tracking = true;
    enableMenuActions();
}

void MainWindowController::displayStoppedTimerState() {
    tracking = false;
    enableMenuActions();
}

void MainWindowController::enableMenuActions() {
    actionNew->setEnabled(loggedIn);
    actionContinue->setEnabled(loggedIn && !tracking);
    actionStop->setEnabled(loggedIn && tracking);
    actionSync->setEnabled(loggedIn);
    actionLogout->setEnabled(loggedIn);
    actionClear_Cache->setEnabled(loggedIn);
    actionSend_Feedback->setEnabled(loggedIn);
    actionReports->setEnabled(loggedIn);
    actionEmail->setText(TogglApi::instance->userEmail());
    if (hasTrayIconCached) {
        if (tracking) {
            trayIcon->setIcon(icon);
            setWindowIcon(icon);
        } else {
            trayIcon->setIcon(iconDisabled);
            setWindowIcon(iconDisabled);
        }
    }
}

void MainWindowController::connectMenuActions() {
    foreach(QMenu *menu, ui->menuBar->findChildren<QMenu *>()) {
        if (trayIcon) {
            trayIcon->setContextMenu(menu);
        }
        foreach(QAction *action, menu->actions()) {
            connectMenuAction(action);
        }
    }
}

void MainWindowController::connectMenuAction(
    QAction *action) {
    if ("actionEmail" == action->objectName()) {
        actionEmail = action;
    } else if ("actionNew" == action->objectName()) {
        actionNew = action;
        connect(action, SIGNAL(triggered()), this, SLOT(onActionNew()));
    } else if ("actionContinue" == action->objectName()) {
        actionContinue = action;
        connect(action, SIGNAL(triggered()), this, SLOT(onActionContinue()));
    } else if ("actionStop" == action->objectName()) {
        actionStop = action;
        connect(action, SIGNAL(triggered()), this, SLOT(onActionStop()));
    } else if ("actionSync" == action->objectName()) {
        actionSync = action;
        connect(action, SIGNAL(triggered()), this, SLOT(onActionSync()));
    } else if ("actionLogout" == action->objectName()) {
        actionLogout = action;
        connect(action, SIGNAL(triggered()), this, SLOT(onActionLogout()));
    } else if ("actionClear_Cache" == action->objectName()) {
        actionClear_Cache = action;
        connect(action, SIGNAL(triggered()), this, SLOT(onActionClear_Cache()));
    } else if ("actionSend_Feedback" == action->objectName()) {
        actionSend_Feedback = action;
        connect(action, SIGNAL(triggered()),
                this, SLOT(onActionSend_Feedback()));
    } else if ("actionReports" == action->objectName()) {
        actionReports = action;
        connect(action, SIGNAL(triggered()), this, SLOT(onActionReports()));
    } else if ("actionShow" == action->objectName()) {
        connect(action, SIGNAL(triggered()), this, SLOT(onActionShow()));
    } else if ("actionPreferences" == action->objectName()) {
        connect(action, SIGNAL(triggered()), this, SLOT(onActionPreferences()));
    } else if ("actionAbout" == action->objectName()) {
        connect(action, SIGNAL(triggered()), this, SLOT(onActionAbout()));
    } else if ("actionQuit" == action->objectName()) {
        connect(action, SIGNAL(triggered()), this, SLOT(onActionQuit()));
    } else if ("actionHelp" == action->objectName()) {
        connect(action, SIGNAL(triggered()), this, SLOT(onActionHelp()));
    }
}

void MainWindowController::onActionNew() {
    TogglApi::instance->start("", "", 0, 0);
}

void MainWindowController::onActionContinue() {
    TogglApi::instance->continueLatestTimeEntry();
}

void MainWindowController::onActionStop() {
    TogglApi::instance->stop();
}

void MainWindowController::onActionShow() {
    displayApp(true);
}

void MainWindowController::onActionSync() {
    TogglApi::instance->sync();
}

void MainWindowController::onActionReports() {
    TogglApi::instance->openInBrowser();
}

void MainWindowController::onActionPreferences() {
    TogglApi::instance->editPreferences();
}

void MainWindowController::onActionAbout() {
    aboutDialog->show();
}

void MainWindowController::onActionSend_Feedback() {
    feedbackDialog->show();
}

void MainWindowController::onActionLogout() {
    TogglApi::instance->logout();
}

void MainWindowController::onActionQuit() {
    quitApp();
}

void MainWindowController::quitApp() {
    TogglApi::instance->shutdown = true;
    qApp->exit(0);
}

void MainWindowController::onActionClear_Cache() {
    if (QMessageBox::Ok == QMessageBox(
        QMessageBox::Question,
        "Clear Cache?",
        "Clearing cache will delete any unsaved time entries and log you out.",
        QMessageBox::Ok|QMessageBox::Cancel).exec()) {
        TogglApi::instance->clearCache();
    }
}

void MainWindowController::onActionHelp() {
    TogglApi::instance->getSupport();
}

void MainWindowController::displayApp(const bool open) {
    if (open) {
        show();
        raise();
    }
}

void MainWindowController::readSettings() {
    QSettings settings("Toggl", "TogglDesktop");
    restoreGeometry(settings.value("geometry").toByteArray());
    restoreState(settings.value("windowState").toByteArray());
}

void MainWindowController::writeSettings() {
    QSettings settings("Toggl", "TogglDesktop");
    settings.setValue("geometry", saveGeometry());
    settings.setValue("windowState", saveState());
}

void MainWindowController::closeEvent(QCloseEvent *event) {
    if (hasTrayIcon()) {
        event->ignore();
        hide();
        return;
    }

    QMessageBox::StandardButton dialog;
    dialog = QMessageBox::question(this,
                                   "Toggl Desktop",
                                   "Really quit the app?",
                                   QMessageBox::Ok | QMessageBox::Cancel);
    if (QMessageBox::Ok == dialog) {
        writeSettings();
        close();
    } else {
        event->ignore();
        return;
    }

    QMainWindow::closeEvent(event);
}

bool MainWindowController::hasTrayIcon() const {
#if (QT_VERSION >= QT_VERSION_CHECK(5, 5, 0))
    return true;
#endif
    QString currentDesktop = QProcessEnvironment::systemEnvironment().value(
        "XDG_CURRENT_DESKTOP", "");
    return "Unity" != currentDesktop;
}

void MainWindowController::showEvent(QShowEvent *event) {
    QMainWindow::showEvent(event);

    // Avoid 'user already logged in' error from double UI start
    if (ui_started) {
        return;
    }
    ui_started = true;

    if (!TogglApi::instance->startEvents()) {
        QMessageBox(
            QMessageBox::Warning,
            "Error",
            "The application could not start. Please inspect the log file.",
            QMessageBox::Ok|QMessageBox::Cancel).exec();
        return;
    }
    if (script.isEmpty()) {
        qDebug() << "no script to run";
        return;
    }
    qDebug() << "will run script: " << script;

    QtConcurrent::run(this, &MainWindowController::runScript);
}

void MainWindowController::displayUpdate(const QString url) {
    if (aboutDialog->isVisible()
            || url.isEmpty()) {
        return;
    }
    if (QMessageBox::Yes == QMessageBox(
        QMessageBox::Question,
        "Download new version?",
        "A new version of Toggl Desktop is available. Continue with download?",
        QMessageBox::No|QMessageBox::Yes).exec()) {
        QDesktopServices::openUrl(QUrl(url));
        quitApp();
    }
}

void MainWindowController::runScript() {
    if (TogglApi::instance->runScriptFile(script)) {
        quitApp();
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: scanlineformats.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-05 08:55:07 $
 *
 *  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_BASEBMP_SCANLINEFORMATS_HXX
#define INCLUDED_BASEBMP_SCANLINEFORMATS_HXX

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

/* Definition of Scanline formats */

namespace basebmp { namespace Format
{
    static const sal_Int32 NONE                         = 0;
    static const sal_Int32 ONE_BIT_MSB_GREY             = (sal_Int32)0x01;
    static const sal_Int32 ONE_BIT_LSB_GREY             = (sal_Int32)0x02;
    static const sal_Int32 ONE_BIT_MSB_PAL              = (sal_Int32)0x03;
    static const sal_Int32 ONE_BIT_LSB_PAL              = (sal_Int32)0x04;
    static const sal_Int32 FOUR_BIT_MSB_GREY            = (sal_Int32)0x05;
    static const sal_Int32 FOUR_BIT_LSB_GREY            = (sal_Int32)0x06;
    static const sal_Int32 FOUR_BIT_MSB_PAL             = (sal_Int32)0x07;
    static const sal_Int32 FOUR_BIT_LSB_PAL             = (sal_Int32)0x08;
    static const sal_Int32 EIGHT_BIT_PAL                = (sal_Int32)0x09;
    static const sal_Int32 EIGHT_BIT_GREY               = (sal_Int32)0x0A;
    static const sal_Int32 SIXTEEN_BIT_LSB_TC_MASK      = (sal_Int32)0x0B;
    static const sal_Int32 SIXTEEN_BIT_MSB_TC_MASK      = (sal_Int32)0x0C;
    static const sal_Int32 TWENTYFOUR_BIT_TC_MASK       = (sal_Int32)0x0D;
    static const sal_Int32 THIRTYTWO_BIT_TC_MASK        = (sal_Int32)0x0E;
    static const sal_Int32 THIRTYTWO_BIT_TC_MASK_ARGB   = (sal_Int32)0x0F;
    static const sal_Int32 MAX                          = (sal_Int32)0x0F;
} }

#endif /* INCLUDED_BASEBMP_SCANLINEFORMATS_HXX */
<commit_msg>INTEGRATION: CWS changefileheader (1.9.24); FILE MERGED 2008/04/01 15:00:51 thb 1.9.24.2: #i85898# Stripping all external header guards 2008/03/31 13:07:57 rt 1.9.24.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: scanlineformats.hxx,v $
 * $Revision: 1.10 $
 *
 * 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_BASEBMP_SCANLINEFORMATS_HXX
#define INCLUDED_BASEBMP_SCANLINEFORMATS_HXX

#include <sal/types.h>

/* Definition of Scanline formats */

namespace basebmp { namespace Format
{
    static const sal_Int32 NONE                         = 0;
    static const sal_Int32 ONE_BIT_MSB_GREY             = (sal_Int32)0x01;
    static const sal_Int32 ONE_BIT_LSB_GREY             = (sal_Int32)0x02;
    static const sal_Int32 ONE_BIT_MSB_PAL              = (sal_Int32)0x03;
    static const sal_Int32 ONE_BIT_LSB_PAL              = (sal_Int32)0x04;
    static const sal_Int32 FOUR_BIT_MSB_GREY            = (sal_Int32)0x05;
    static const sal_Int32 FOUR_BIT_LSB_GREY            = (sal_Int32)0x06;
    static const sal_Int32 FOUR_BIT_MSB_PAL             = (sal_Int32)0x07;
    static const sal_Int32 FOUR_BIT_LSB_PAL             = (sal_Int32)0x08;
    static const sal_Int32 EIGHT_BIT_PAL                = (sal_Int32)0x09;
    static const sal_Int32 EIGHT_BIT_GREY               = (sal_Int32)0x0A;
    static const sal_Int32 SIXTEEN_BIT_LSB_TC_MASK      = (sal_Int32)0x0B;
    static const sal_Int32 SIXTEEN_BIT_MSB_TC_MASK      = (sal_Int32)0x0C;
    static const sal_Int32 TWENTYFOUR_BIT_TC_MASK       = (sal_Int32)0x0D;
    static const sal_Int32 THIRTYTWO_BIT_TC_MASK        = (sal_Int32)0x0E;
    static const sal_Int32 THIRTYTWO_BIT_TC_MASK_ARGB   = (sal_Int32)0x0F;
    static const sal_Int32 MAX                          = (sal_Int32)0x0F;
} }

#endif /* INCLUDED_BASEBMP_SCANLINEFORMATS_HXX */
<|endoftext|>


<commit_before>#include "stan/math/functions/fma.hpp"
#include <gtest/gtest.h>

TEST(MathFunctions, fma) {
  using stan::math::fma;

  EXPECT_FLOAT_EQ(5.0, fma(1.0,2.0,3.0));
  EXPECT_FLOAT_EQ(10.0, fma(2.0,3.0,4.0));
}

<commit_msg>added NaN test for fma<commit_after>#include <stan/math/functions/fma.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <gtest/gtest.h>

TEST(MathFunctions, fma) {
  using stan::math::fma;

  EXPECT_FLOAT_EQ(5.0, fma(1.0,2.0,3.0));
  EXPECT_FLOAT_EQ(10.0, fma(2.0,3.0,4.0));
}

TEST(MathFunctions, fma_nan) {
  double nan = std::numeric_limits<double>::quiet_NaN();

  EXPECT_PRED1(boost::math::isnan<double>,
               stan::math::fma(1.0, 2.0, nan));

  EXPECT_PRED1(boost::math::isnan<double>,
               stan::math::fma(1.0, nan, 3.0));

  EXPECT_PRED1(boost::math::isnan<double>,
               stan::math::fma(1.0, nan, nan));

  EXPECT_PRED1(boost::math::isnan<double>,
               stan::math::fma(nan, 2.0, 3.0));

  EXPECT_PRED1(boost::math::isnan<double>,
               stan::math::fma(nan, 2.0, nan));

  EXPECT_PRED1(boost::math::isnan<double>,
               stan::math::fma(nan, nan, 3.0));

  EXPECT_PRED1(boost::math::isnan<double>,
               stan::math::fma(nan, nan, nan));
}
<|endoftext|>


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

#include "vktApiDescriptorPoolTests.hpp"
#include "vktTestCaseUtil.hpp"

#include "vkDefs.hpp"
#include "vkRef.hpp"
#include "vkRefUtil.hpp"
#include "vkPlatform.hpp"
#include "vkDeviceUtil.hpp"
#include "vkQueryUtil.hpp"

#include "tcuCommandLine.hpp"
#include "tcuTestLog.hpp"
#include "tcuPlatform.hpp"

#include "deUniquePtr.hpp"
#include "deSharedPtr.hpp"
#include "deInt32.h"
#include "deSTLUtil.hpp"

#define VK_DESCRIPTOR_TYPE_LAST (VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT + 1)

namespace vkt
{
namespace api
{

namespace
{

using namespace std;
using namespace vk;

struct ResetDescriptorPoolTestParams
{
	ResetDescriptorPoolTestParams	(deUint32 numIterations, bool freeDescriptorSets = false)
		: m_numIterations		(numIterations)
		, m_freeDescriptorSets	(freeDescriptorSets)
	{}

	deUint32	m_numIterations;
	bool		m_freeDescriptorSets;
};

tcu::TestStatus resetDescriptorPoolTest (Context& context, const ResetDescriptorPoolTestParams params)
{
	const deUint32				numDescriptorSetsPerIter = 2048;
	const DeviceInterface&		vkd						 = context.getDeviceInterface();
	const VkDevice				device					 = context.getDevice();

	const VkDescriptorPoolSize descriptorPoolSize =
	{
		VK_DESCRIPTOR_TYPE_SAMPLER, // type
		numDescriptorSetsPerIter	// descriptorCount
	};

	const VkDescriptorPoolCreateInfo descriptorPoolInfo =
	{
		VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,																			// sType
		NULL,																													// pNext
		(params.m_freeDescriptorSets) ? (VkDescriptorPoolCreateFlags)VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT : 0u,	// flags
		numDescriptorSetsPerIter,																								// maxSets
		1,																														// poolSizeCount
		&descriptorPoolSize																										// pPoolSizes
	};

	{
		const Unique<VkDescriptorPool> descriptorPool(
			createDescriptorPool(vkd, device,
								 &descriptorPoolInfo));

		const VkDescriptorSetLayoutBinding descriptorSetLayoutBinding =
		{
			0,							// binding
			VK_DESCRIPTOR_TYPE_SAMPLER, // descriptorType
			1,							// descriptorCount
			VK_SHADER_STAGE_ALL,		// stageFlags
			NULL						// pImmutableSamplers
		};

		const VkDescriptorSetLayoutCreateInfo descriptorSetLayoutInfo =
		{
			VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,	// sType
			NULL,													// pNext
			0,														// flags
			1,														// bindingCount
			&descriptorSetLayoutBinding								// pBindings
		};

		{
			typedef de::SharedPtr<Unique<VkDescriptorSetLayout> > DescriptorSetLayoutPtr;

			vector<DescriptorSetLayoutPtr> descriptorSetLayouts;
			descriptorSetLayouts.reserve(numDescriptorSetsPerIter);

			for (deUint32 ndx = 0; ndx < numDescriptorSetsPerIter; ++ndx)
			{
				descriptorSetLayouts.push_back(
					DescriptorSetLayoutPtr(
						new Unique<VkDescriptorSetLayout>(
							createDescriptorSetLayout(vkd, device,
													  &descriptorSetLayoutInfo))));
			}

			vector<VkDescriptorSetLayout> descriptorSetLayoutsRaw(numDescriptorSetsPerIter);

			for (deUint32 ndx = 0; ndx < numDescriptorSetsPerIter; ++ndx)
			{
				descriptorSetLayoutsRaw[ndx] = **descriptorSetLayouts[ndx];
			}

			const VkDescriptorSetAllocateInfo descriptorSetInfo =
			{
				VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, // sType
				NULL,											// pNext
				*descriptorPool,								// descriptorPool
				numDescriptorSetsPerIter,						// descriptorSetCount
				&descriptorSetLayoutsRaw[0]						// pSetLayouts
			};

			vector<VkDescriptorSet> testSets(numDescriptorSetsPerIter);

			for (deUint32 ndx = 0; ndx < params.m_numIterations; ++ndx)
			{
				// The test should crash in this loop at some point if there is a memory leak
				VK_CHECK(vkd.allocateDescriptorSets(device, &descriptorSetInfo, &testSets[0]));
				if (params.m_freeDescriptorSets)
					VK_CHECK(vkd.freeDescriptorSets(device, *descriptorPool, 1, &testSets[0]));
				VK_CHECK(vkd.resetDescriptorPool(device, *descriptorPool, 0));
			}

		}
	}

	// If it didn't crash, pass
	return tcu::TestStatus::pass("Pass");
}

tcu::TestStatus outOfPoolMemoryTest (Context& context)
{
	const DeviceInterface&	vkd							= context.getDeviceInterface();
	const VkDevice			device						= context.getDevice();
	const bool				expectOutOfPoolMemoryError	= context.isDeviceFunctionalitySupported("VK_KHR_maintenance1");
	deUint32				numErrorsReturned			= 0;

	const struct FailureCase
	{
		deUint32	poolDescriptorCount;		//!< total number of descriptors (of a given type) in the descriptor pool
		deUint32	poolMaxSets;				//!< max number of descriptor sets that can be allocated from the pool
		deUint32	bindingCount;				//!< number of bindings per descriptor set layout
		deUint32	bindingDescriptorCount;		//!< number of descriptors in a binding (array size) (in all bindings)
		deUint32	descriptorSetCount;			//!< number of descriptor sets to allocate
		string		description;				//!< the log message for this failure condition
	} failureCases[] =
	{
		//	pool			pool		binding		binding		alloc set
		//	descr. count	max sets	count		array size	count
		{	4u,				2u,			1u,			1u,			3u,		"Out of descriptor sets",											},
		{	3u,				4u,			1u,			1u,			4u,		"Out of descriptors (due to the number of sets)",					},
		{	2u,				1u,			3u,			1u,			1u,		"Out of descriptors (due to the number of bindings)",				},
		{	3u,				2u,			1u,			2u,			2u,		"Out of descriptors (due to descriptor array size)",				},
		{	5u,				1u,			2u,			3u,			1u,		"Out of descriptors (due to descriptor array size in all bindings)",},
	};

	context.getTestContext().getLog()
		<< tcu::TestLog::Message
		<< "Creating a descriptor pool with insufficient resources. Descriptor set allocation is likely to fail."
		<< tcu::TestLog::EndMessage;

	for (deUint32 failureCaseNdx = 0u; failureCaseNdx < DE_LENGTH_OF_ARRAY(failureCases); ++failureCaseNdx)
	{
		const FailureCase& params = failureCases[failureCaseNdx];
		context.getTestContext().getLog() << tcu::TestLog::Message << "Checking: " << params.description << tcu::TestLog::EndMessage;

		for (VkDescriptorType	descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
								descriptorType < VK_DESCRIPTOR_TYPE_LAST;
								descriptorType = static_cast<VkDescriptorType>(descriptorType + 1))
		{
			context.getTestContext().getLog() << tcu::TestLog::Message << "- " << getDescriptorTypeName(descriptorType) << tcu::TestLog::EndMessage;

			const VkDescriptorPoolSize					descriptorPoolSize =
			{
				descriptorType,												// type
				params.poolDescriptorCount,									// descriptorCount
			};

			const VkDescriptorPoolCreateInfo			descriptorPoolCreateInfo =
			{
				VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,				// VkStructureType                sType;
				DE_NULL,													// const void*                    pNext;
				(VkDescriptorPoolCreateFlags)0,								// VkDescriptorPoolCreateFlags    flags;
				params.poolMaxSets,											// uint32_t                       maxSets;
				1u,															// uint32_t                       poolSizeCount;
				&descriptorPoolSize,										// const VkDescriptorPoolSize*    pPoolSizes;
			};

			const Unique<VkDescriptorPool>				descriptorPool(createDescriptorPool(vkd, device, &descriptorPoolCreateInfo));

			const VkDescriptorSetLayoutBinding			descriptorSetLayoutBinding =
			{
				0u,															// uint32_t              binding;
				descriptorType,												// VkDescriptorType      descriptorType;
				params.bindingDescriptorCount,								// uint32_t              descriptorCount;
				VK_SHADER_STAGE_ALL,										// VkShaderStageFlags    stageFlags;
				DE_NULL,													// const VkSampler*      pImmutableSamplers;
			};

			vector<VkDescriptorSetLayoutBinding>	descriptorSetLayoutBindings (params.bindingCount, descriptorSetLayoutBinding);

			for (deUint32 binding = 0; binding < deUint32(descriptorSetLayoutBindings.size()); ++binding)
			{
				descriptorSetLayoutBindings[binding].binding = binding;
			}

			const VkDescriptorSetLayoutCreateInfo		descriptorSetLayoutInfo =
			{
				VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,		// VkStructureType                        sType;
				DE_NULL,													// const void*                            pNext;
				(VkDescriptorSetLayoutCreateFlags)0,						// VkDescriptorSetLayoutCreateFlags       flags;
				static_cast<deUint32>(descriptorSetLayoutBindings.size()),	// uint32_t                               bindingCount;
				&descriptorSetLayoutBindings[0],							// const VkDescriptorSetLayoutBinding*    pBindings;
			};

			const Unique<VkDescriptorSetLayout>			descriptorSetLayout	(createDescriptorSetLayout(vkd, device, &descriptorSetLayoutInfo));
			const vector<VkDescriptorSetLayout>			rawSetLayouts		(params.descriptorSetCount, *descriptorSetLayout);
			vector<VkDescriptorSet>						rawDescriptorSets	(params.descriptorSetCount, DE_NULL);

			const VkDescriptorSetAllocateInfo			descriptorSetAllocateInfo =
			{
				VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,				// VkStructureType                 sType;
				DE_NULL,													// const void*                     pNext;
				*descriptorPool,											// VkDescriptorPool                descriptorPool;
				static_cast<deUint32>(rawSetLayouts.size()),				// uint32_t                        descriptorSetCount;
				&rawSetLayouts[0],											// const VkDescriptorSetLayout*    pSetLayouts;
			};

			const VkResult result = vkd.allocateDescriptorSets(device, &descriptorSetAllocateInfo, &rawDescriptorSets[0]);

			if (result != VK_SUCCESS)
			{
				++numErrorsReturned;

				if (expectOutOfPoolMemoryError && result != VK_ERROR_OUT_OF_POOL_MEMORY)
					return tcu::TestStatus::fail("Expected VK_ERROR_OUT_OF_POOL_MEMORY but got " + string(getResultName(result)) + " instead");
			}
			else
				context.getTestContext().getLog() << tcu::TestLog::Message << "  Allocation was successful anyway" << tcu::TestLog::EndMessage;
		}
	}

	if (numErrorsReturned == 0u)
		return tcu::TestStatus::pass("Not validated");
	else
		return tcu::TestStatus::pass("Pass");
}

} // anonymous

tcu::TestCaseGroup* createDescriptorPoolTests (tcu::TestContext& testCtx)
{
	const deUint32 numIterationsHigh = 4096;

	de::MovePtr<tcu::TestCaseGroup> descriptorPoolTests(
		new tcu::TestCaseGroup(testCtx, "descriptor_pool", "Descriptor Pool Tests"));

	addFunctionCase(descriptorPoolTests.get(),
					"repeated_reset_short",
					"Test 2 cycles of vkAllocateDescriptorSets and vkResetDescriptorPool (should pass)",
					resetDescriptorPoolTest, ResetDescriptorPoolTestParams(2U));
	addFunctionCase(descriptorPoolTests.get(),
					"repeated_reset_long",
					"Test many cycles of vkAllocateDescriptorSets and vkResetDescriptorPool",
					resetDescriptorPoolTest, ResetDescriptorPoolTestParams(numIterationsHigh));
	addFunctionCase(descriptorPoolTests.get(),
					"repeated_free_reset_short",
					"Test 2 cycles of vkAllocateDescriptorSets, vkFreeDescriptorSets and vkResetDescriptorPool (should pass)",
					resetDescriptorPoolTest, ResetDescriptorPoolTestParams(2U, true));
	addFunctionCase(descriptorPoolTests.get(),
					"repeated_free_reset_long",
					"Test many cycles of vkAllocateDescriptorSets, vkFreeDescriptorSets and vkResetDescriptorPool",
					resetDescriptorPoolTest, ResetDescriptorPoolTestParams(numIterationsHigh, true));
	addFunctionCase(descriptorPoolTests.get(),
					"out_of_pool_memory",
					"Test that when we run out of descriptors a correct error code is returned",
					outOfPoolMemoryTest);

	return descriptorPoolTests.release();
}

} // api
} // vkt
<commit_msg>Add watchdog touches to descriptor_pool test<commit_after>/*-------------------------------------------------------------------------
 * Vulkan Conformance Tests
 * ------------------------
 *
 * Copyright (c) 2016 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *//*!
 * \file
 * \brief Descriptor pool tests
 *//*--------------------------------------------------------------------*/

#include "vktApiDescriptorPoolTests.hpp"
#include "vktTestCaseUtil.hpp"

#include "vkDefs.hpp"
#include "vkRef.hpp"
#include "vkRefUtil.hpp"
#include "vkPlatform.hpp"
#include "vkDeviceUtil.hpp"
#include "vkQueryUtil.hpp"

#include "tcuCommandLine.hpp"
#include "tcuTestLog.hpp"
#include "tcuPlatform.hpp"

#include "deUniquePtr.hpp"
#include "deSharedPtr.hpp"
#include "deInt32.h"
#include "deSTLUtil.hpp"

#define VK_DESCRIPTOR_TYPE_LAST (VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT + 1)

namespace vkt
{
namespace api
{

namespace
{

using namespace std;
using namespace vk;

struct ResetDescriptorPoolTestParams
{
	ResetDescriptorPoolTestParams	(deUint32 numIterations, bool freeDescriptorSets = false)
		: m_numIterations		(numIterations)
		, m_freeDescriptorSets	(freeDescriptorSets)
	{}

	deUint32	m_numIterations;
	bool		m_freeDescriptorSets;
};

tcu::TestStatus resetDescriptorPoolTest (Context& context, const ResetDescriptorPoolTestParams params)
{
	const deUint32				numDescriptorSetsPerIter = 2048;
	const DeviceInterface&		vkd						 = context.getDeviceInterface();
	const VkDevice				device					 = context.getDevice();

	const VkDescriptorPoolSize descriptorPoolSize =
	{
		VK_DESCRIPTOR_TYPE_SAMPLER, // type
		numDescriptorSetsPerIter	// descriptorCount
	};

	const VkDescriptorPoolCreateInfo descriptorPoolInfo =
	{
		VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,																			// sType
		NULL,																													// pNext
		(params.m_freeDescriptorSets) ? (VkDescriptorPoolCreateFlags)VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT : 0u,	// flags
		numDescriptorSetsPerIter,																								// maxSets
		1,																														// poolSizeCount
		&descriptorPoolSize																										// pPoolSizes
	};

	{
		const Unique<VkDescriptorPool> descriptorPool(
			createDescriptorPool(vkd, device,
								 &descriptorPoolInfo));

		const VkDescriptorSetLayoutBinding descriptorSetLayoutBinding =
		{
			0,							// binding
			VK_DESCRIPTOR_TYPE_SAMPLER, // descriptorType
			1,							// descriptorCount
			VK_SHADER_STAGE_ALL,		// stageFlags
			NULL						// pImmutableSamplers
		};

		const VkDescriptorSetLayoutCreateInfo descriptorSetLayoutInfo =
		{
			VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,	// sType
			NULL,													// pNext
			0,														// flags
			1,														// bindingCount
			&descriptorSetLayoutBinding								// pBindings
		};

		{
			typedef de::SharedPtr<Unique<VkDescriptorSetLayout> > DescriptorSetLayoutPtr;

			vector<DescriptorSetLayoutPtr> descriptorSetLayouts;
			descriptorSetLayouts.reserve(numDescriptorSetsPerIter);

			for (deUint32 ndx = 0; ndx < numDescriptorSetsPerIter; ++ndx)
			{
				descriptorSetLayouts.push_back(
					DescriptorSetLayoutPtr(
						new Unique<VkDescriptorSetLayout>(
							createDescriptorSetLayout(vkd, device,
													  &descriptorSetLayoutInfo))));
			}

			vector<VkDescriptorSetLayout> descriptorSetLayoutsRaw(numDescriptorSetsPerIter);

			for (deUint32 ndx = 0; ndx < numDescriptorSetsPerIter; ++ndx)
			{
				descriptorSetLayoutsRaw[ndx] = **descriptorSetLayouts[ndx];
			}

			const VkDescriptorSetAllocateInfo descriptorSetInfo =
			{
				VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, // sType
				NULL,											// pNext
				*descriptorPool,								// descriptorPool
				numDescriptorSetsPerIter,						// descriptorSetCount
				&descriptorSetLayoutsRaw[0]						// pSetLayouts
			};

			vector<VkDescriptorSet> testSets(numDescriptorSetsPerIter);

			for (deUint32 ndx = 0; ndx < params.m_numIterations; ++ndx)
			{
				if (ndx % 1024 == 0) context.getTestContext().touchWatchdog();
				// The test should crash in this loop at some point if there is a memory leak
				VK_CHECK(vkd.allocateDescriptorSets(device, &descriptorSetInfo, &testSets[0]));
				if (params.m_freeDescriptorSets)
					VK_CHECK(vkd.freeDescriptorSets(device, *descriptorPool, 1, &testSets[0]));
				VK_CHECK(vkd.resetDescriptorPool(device, *descriptorPool, 0));
			}

		}
	}

	// If it didn't crash, pass
	return tcu::TestStatus::pass("Pass");
}

tcu::TestStatus outOfPoolMemoryTest (Context& context)
{
	const DeviceInterface&	vkd							= context.getDeviceInterface();
	const VkDevice			device						= context.getDevice();
	const bool				expectOutOfPoolMemoryError	= context.isDeviceFunctionalitySupported("VK_KHR_maintenance1");
	deUint32				numErrorsReturned			= 0;

	const struct FailureCase
	{
		deUint32	poolDescriptorCount;		//!< total number of descriptors (of a given type) in the descriptor pool
		deUint32	poolMaxSets;				//!< max number of descriptor sets that can be allocated from the pool
		deUint32	bindingCount;				//!< number of bindings per descriptor set layout
		deUint32	bindingDescriptorCount;		//!< number of descriptors in a binding (array size) (in all bindings)
		deUint32	descriptorSetCount;			//!< number of descriptor sets to allocate
		string		description;				//!< the log message for this failure condition
	} failureCases[] =
	{
		//	pool			pool		binding		binding		alloc set
		//	descr. count	max sets	count		array size	count
		{	4u,				2u,			1u,			1u,			3u,		"Out of descriptor sets",											},
		{	3u,				4u,			1u,			1u,			4u,		"Out of descriptors (due to the number of sets)",					},
		{	2u,				1u,			3u,			1u,			1u,		"Out of descriptors (due to the number of bindings)",				},
		{	3u,				2u,			1u,			2u,			2u,		"Out of descriptors (due to descriptor array size)",				},
		{	5u,				1u,			2u,			3u,			1u,		"Out of descriptors (due to descriptor array size in all bindings)",},
	};

	context.getTestContext().getLog()
		<< tcu::TestLog::Message
		<< "Creating a descriptor pool with insufficient resources. Descriptor set allocation is likely to fail."
		<< tcu::TestLog::EndMessage;

	for (deUint32 failureCaseNdx = 0u; failureCaseNdx < DE_LENGTH_OF_ARRAY(failureCases); ++failureCaseNdx)
	{
		const FailureCase& params = failureCases[failureCaseNdx];
		context.getTestContext().getLog() << tcu::TestLog::Message << "Checking: " << params.description << tcu::TestLog::EndMessage;

		for (VkDescriptorType	descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
								descriptorType < VK_DESCRIPTOR_TYPE_LAST;
								descriptorType = static_cast<VkDescriptorType>(descriptorType + 1))
		{
			context.getTestContext().getLog() << tcu::TestLog::Message << "- " << getDescriptorTypeName(descriptorType) << tcu::TestLog::EndMessage;

			const VkDescriptorPoolSize					descriptorPoolSize =
			{
				descriptorType,												// type
				params.poolDescriptorCount,									// descriptorCount
			};

			const VkDescriptorPoolCreateInfo			descriptorPoolCreateInfo =
			{
				VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,				// VkStructureType                sType;
				DE_NULL,													// const void*                    pNext;
				(VkDescriptorPoolCreateFlags)0,								// VkDescriptorPoolCreateFlags    flags;
				params.poolMaxSets,											// uint32_t                       maxSets;
				1u,															// uint32_t                       poolSizeCount;
				&descriptorPoolSize,										// const VkDescriptorPoolSize*    pPoolSizes;
			};

			const Unique<VkDescriptorPool>				descriptorPool(createDescriptorPool(vkd, device, &descriptorPoolCreateInfo));

			const VkDescriptorSetLayoutBinding			descriptorSetLayoutBinding =
			{
				0u,															// uint32_t              binding;
				descriptorType,												// VkDescriptorType      descriptorType;
				params.bindingDescriptorCount,								// uint32_t              descriptorCount;
				VK_SHADER_STAGE_ALL,										// VkShaderStageFlags    stageFlags;
				DE_NULL,													// const VkSampler*      pImmutableSamplers;
			};

			vector<VkDescriptorSetLayoutBinding>	descriptorSetLayoutBindings (params.bindingCount, descriptorSetLayoutBinding);

			for (deUint32 binding = 0; binding < deUint32(descriptorSetLayoutBindings.size()); ++binding)
			{
				descriptorSetLayoutBindings[binding].binding = binding;
			}

			const VkDescriptorSetLayoutCreateInfo		descriptorSetLayoutInfo =
			{
				VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,		// VkStructureType                        sType;
				DE_NULL,													// const void*                            pNext;
				(VkDescriptorSetLayoutCreateFlags)0,						// VkDescriptorSetLayoutCreateFlags       flags;
				static_cast<deUint32>(descriptorSetLayoutBindings.size()),	// uint32_t                               bindingCount;
				&descriptorSetLayoutBindings[0],							// const VkDescriptorSetLayoutBinding*    pBindings;
			};

			const Unique<VkDescriptorSetLayout>			descriptorSetLayout	(createDescriptorSetLayout(vkd, device, &descriptorSetLayoutInfo));
			const vector<VkDescriptorSetLayout>			rawSetLayouts		(params.descriptorSetCount, *descriptorSetLayout);
			vector<VkDescriptorSet>						rawDescriptorSets	(params.descriptorSetCount, DE_NULL);

			const VkDescriptorSetAllocateInfo			descriptorSetAllocateInfo =
			{
				VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,				// VkStructureType                 sType;
				DE_NULL,													// const void*                     pNext;
				*descriptorPool,											// VkDescriptorPool                descriptorPool;
				static_cast<deUint32>(rawSetLayouts.size()),				// uint32_t                        descriptorSetCount;
				&rawSetLayouts[0],											// const VkDescriptorSetLayout*    pSetLayouts;
			};

			const VkResult result = vkd.allocateDescriptorSets(device, &descriptorSetAllocateInfo, &rawDescriptorSets[0]);

			if (result != VK_SUCCESS)
			{
				++numErrorsReturned;

				if (expectOutOfPoolMemoryError && result != VK_ERROR_OUT_OF_POOL_MEMORY)
					return tcu::TestStatus::fail("Expected VK_ERROR_OUT_OF_POOL_MEMORY but got " + string(getResultName(result)) + " instead");
			}
			else
				context.getTestContext().getLog() << tcu::TestLog::Message << "  Allocation was successful anyway" << tcu::TestLog::EndMessage;
		}
	}

	if (numErrorsReturned == 0u)
		return tcu::TestStatus::pass("Not validated");
	else
		return tcu::TestStatus::pass("Pass");
}

} // anonymous

tcu::TestCaseGroup* createDescriptorPoolTests (tcu::TestContext& testCtx)
{
	const deUint32 numIterationsHigh = 4096;

	de::MovePtr<tcu::TestCaseGroup> descriptorPoolTests(
		new tcu::TestCaseGroup(testCtx, "descriptor_pool", "Descriptor Pool Tests"));

	addFunctionCase(descriptorPoolTests.get(),
					"repeated_reset_short",
					"Test 2 cycles of vkAllocateDescriptorSets and vkResetDescriptorPool (should pass)",
					resetDescriptorPoolTest, ResetDescriptorPoolTestParams(2U));
	addFunctionCase(descriptorPoolTests.get(),
					"repeated_reset_long",
					"Test many cycles of vkAllocateDescriptorSets and vkResetDescriptorPool",
					resetDescriptorPoolTest, ResetDescriptorPoolTestParams(numIterationsHigh));
	addFunctionCase(descriptorPoolTests.get(),
					"repeated_free_reset_short",
					"Test 2 cycles of vkAllocateDescriptorSets, vkFreeDescriptorSets and vkResetDescriptorPool (should pass)",
					resetDescriptorPoolTest, ResetDescriptorPoolTestParams(2U, true));
	addFunctionCase(descriptorPoolTests.get(),
					"repeated_free_reset_long",
					"Test many cycles of vkAllocateDescriptorSets, vkFreeDescriptorSets and vkResetDescriptorPool",
					resetDescriptorPoolTest, ResetDescriptorPoolTestParams(numIterationsHigh, true));
	addFunctionCase(descriptorPoolTests.get(),
					"out_of_pool_memory",
					"Test that when we run out of descriptors a correct error code is returned",
					outOfPoolMemoryTest);

	return descriptorPoolTests.release();
}

} // api
} // vkt
<|endoftext|>


<commit_before>/*
 * Ubitrack - Library for Ubiquitous Tracking
 * Copyright 2006, Technische Universitaet Muenchen, and individual
 * contributors as indicated by the @authors tag. See the
 * copyright.txt in the distribution for a full listing of individual
 * contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

/**
 * @ingroup vision_components
 * @file
 * A component that recives colored images and converts them to grayscale.
 *
 * @author Christian Waechter <christian.waechter@in.tum.de>
 */

#include <string>
#include <list>
#include <iostream>

#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/scoped_ptr.hpp>
#include <log4cpp/Category.hh>

#include <utDataflow/PushSupplier.h>
#include <utDataflow/PushConsumer.h>
#include <utDataflow/Component.h>
#include <utDataflow/ComponentFactory.h>
#include <utMeasurement/Measurement.h>
#include <utUtil/OS.h>
#include <utUtil/Exception.h>
#include <utVision/Image.h>
#include <utVision/OpenCLManager.h>

#include <opencv/cv.h>

using namespace Ubitrack;
using namespace Ubitrack::Vision;
using namespace Ubitrack::Measurement;

static log4cpp::Category& logger( log4cpp::Category::getInstance( "Ubitrack.Vision.ImageGPUUpload" ) );

namespace Ubitrack { namespace Drivers {

class ImageGPUUpload
	: public Dataflow::Component
{
public:

	/** constructor */
	ImageGPUUpload( const std::string& sName, boost::shared_ptr< Graph::UTQLSubgraph > );

	/** destructor, waits until thread stops */
	~ImageGPUUpload();

protected:
	// event handler
	void pushImage( const ImageMeasurement& m );

	unsigned m_factor;
	// the ports
	Dataflow::PushSupplier< ImageMeasurement > m_outPort;
	Dataflow::PushConsumer< ImageMeasurement > m_inPort;
};

ImageGPUUpload::ImageGPUUpload( const std::string& sName, boost::shared_ptr< Graph::UTQLSubgraph > subgraph )
	: Dataflow::Component( sName )
	, m_factor ( 0 )
	, m_outPort( "Output", *this )
	, m_inPort( "Input", *this, boost::bind( &ImageGPUUpload::pushImage, this, _1 ) )
{
}

ImageGPUUpload::~ImageGPUUpload()
{
}

void ImageGPUUpload::pushImage( const ImageMeasurement& m )
{
	Vision::OpenCLManager& oclManager = Vision::OpenCLManager::singleton();
	if (oclManager.isInitialized()) {
		//force upload to the GPU
		m->uMat();
	} else {
		LOG4CPP_WARN(logger, "GPU Upload node active, but OpenCL Manager is not initialized.");
	}
	m_outPort.send( m );
}

} } // namespace Ubitrack::Driver

UBITRACK_REGISTER_COMPONENT( Dataflow::ComponentFactory* const cf ) {
	cf->registerComponent< Ubitrack::Drivers::ImageGPUUpload > ( "ImageGPUUpload" );
}
<commit_msg>fixed bug in texture/opencl initialization<commit_after>/*
 * Ubitrack - Library for Ubiquitous Tracking
 * Copyright 2006, Technische Universitaet Muenchen, and individual
 * contributors as indicated by the @authors tag. See the
 * copyright.txt in the distribution for a full listing of individual
 * contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

/**
 * @ingroup vision_components
 * @file
 * A component that recives colored images and converts them to grayscale.
 *
 * @author Christian Waechter <christian.waechter@in.tum.de>
 */

#include <string>
#include <list>
#include <iostream>

#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/scoped_ptr.hpp>
#include <log4cpp/Category.hh>

#include <utDataflow/PushSupplier.h>
#include <utDataflow/PushConsumer.h>
#include <utDataflow/Component.h>
#include <utDataflow/ComponentFactory.h>
#include <utMeasurement/Measurement.h>
#include <utUtil/OS.h>
#include <utUtil/Exception.h>
#include <utVision/Image.h>
#include <utVision/OpenCLManager.h>

#include <opencv/cv.h>

using namespace Ubitrack;
using namespace Ubitrack::Vision;
using namespace Ubitrack::Measurement;

static log4cpp::Category& logger( log4cpp::Category::getInstance( "Ubitrack.Vision.ImageGPUUpload" ) );

namespace Ubitrack { namespace Drivers {

class ImageGPUUpload
	: public Dataflow::Component
{
public:

	/** constructor */
	ImageGPUUpload( const std::string& sName, boost::shared_ptr< Graph::UTQLSubgraph > );

	/** destructor, waits until thread stops */
	~ImageGPUUpload();

protected:
	// event handler
	void pushImage( const ImageMeasurement& m );

	unsigned m_factor;
	// the ports
	Dataflow::PushSupplier< ImageMeasurement > m_outPort;
	Dataflow::PushConsumer< ImageMeasurement > m_inPort;
};

ImageGPUUpload::ImageGPUUpload( const std::string& sName, boost::shared_ptr< Graph::UTQLSubgraph > subgraph )
	: Dataflow::Component( sName )
	, m_factor ( 0 )
	, m_outPort( "Output", *this )
	, m_inPort( "Input", *this, boost::bind( &ImageGPUUpload::pushImage, this, _1 ) )
{
}

ImageGPUUpload::~ImageGPUUpload()
{
}

void ImageGPUUpload::pushImage( const ImageMeasurement& m )
{
	Vision::OpenCLManager& oclManager = Vision::OpenCLManager::singleton();
	if (oclManager.isInitialized()) {
		//force upload to the GPU
		m->uMat();
	} else {
		LOG4CPP_WARN(logger, "GPU Upload node active, but OpenCL is not enabled.");
	}
	m_outPort.send( m );
}

} } // namespace Ubitrack::Driver

UBITRACK_REGISTER_COMPONENT( Dataflow::ComponentFactory* const cf ) {
	cf->registerComponent< Ubitrack::Drivers::ImageGPUUpload > ( "ImageGPUUpload" );
}
<|endoftext|>