<commit_before>// This file is part of the dune-hdd project:
//   http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_HDD_EXAMPLES_LINEARELLIPTIC_OS2014_HH
#define DUNE_HDD_EXAMPLES_LINEARELLIPTIC_OS2014_HH

#define DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_DISABLE_WARNING

#include <boost/numeric/conversion/cast.hpp>

#include <dune/fem/misc/mpimanager.hh>

#include <dune/stuff/common/logging.hh>
#include <dune/stuff/functions/expression.hh>

#include <dune/pymor/parameters/base.hh>

#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/operators/projections.hh>
#include <dune/gdt/operators/prolongations.hh>
#include <dune/gdt/playground/products/elliptic-swipdg.hh>

#include <dune/hdd/linearelliptic/testcases/OS2014.hh>
#include <dune/hdd/linearelliptic/testcases/spe10.hh>
#include <dune/hdd/linearelliptic/discretizations/block-swipdg.hh>
#include <dune/hdd/linearelliptic/estimators/block-swipdg.hh>

namespace internal {

class Initializer
{
public:
  Initializer(const ssize_t info_log_levels,
              const ssize_t debug_log_levels,
              const bool enable_warnings,
              const bool enable_colors,
              const std::string info_color,
              const std::string debug_color,
              const std::string warn_color)
  {
    try {
      int argc = 0;
      char** argv = new char* [0];
      Dune::Fem::MPIManager::initialize(argc, argv);
    } catch (...) {}
    DSC::TimedLogger().create(info_log_levels,
                              debug_log_levels,
                              enable_warnings,
                              enable_colors,
                              info_color,
                              debug_color,
                              warn_color);
    DSC::TimedLogger().get("OS2014.initializer").info() << "creating grid and problem... " << std::endl;
  }
}; // class Initializer

template< class TestCaseType >
class Example
  : Initializer
{
public:
  typedef typename TestCaseType::GridType GridType;
  typedef double RangeFieldType;
  typedef Dune::HDD::LinearElliptic::Discretizations::BlockSWIPDG< GridType, RangeFieldType, 1 > DiscretizationType;
  typedef typename DiscretizationType::VectorType VectorType;
  typedef typename TestCaseType::ParametersMapType ParametersMapType;

private:
  typedef Dune::HDD::LinearElliptic::Estimators::BlockSWIPDG< typename DiscretizationType::AnsatzSpaceType,
                                                              VectorType,
                                                              typename DiscretizationType::ProblemType,
                                                              GridType > Estimator;

public:
  Example(const ParametersMapType& parameter_range,
          const std::string partitioning = "[1 1 1]",
          const DUNE_STUFF_SSIZE_T num_refinements = 0,
          const std::vector< std::string > products = {},
          const ssize_t info_log_levels  = 0,
          const ssize_t debug_log_levels = -1,
          const bool enable_warnings = true,
          const bool enable_colors   = true,
          const std::string info_color  = DSC::TimedLogging::default_info_color(),
          const std::string debug_color = DSC::TimedLogging::default_debug_color(),
          const std::string warn_color  = DSC::TimedLogging::default_warning_color())
    : Initializer(info_log_levels,
                  debug_log_levels,
                  enable_warnings,
                  enable_colors,
                  info_color,
                  debug_color,
                  warn_color)
    , parameter_range_(parameter_range)
    , test_case_(merge_parameters({{"mu", Dune::Pymor::Parameter("mu", 1)},     // <- it does not matter which parameters we give to the
                                   {"mu_hat", Dune::Pymor::Parameter("mu", 1)}, //    test case here, since we use test_case_.problem()
                                   {"mu_bar", Dune::Pymor::Parameter("mu", 1)}}, //    (which is the parametric problem) anyway
                                  parameter_range_),
                 partitioning,
                 boost::numeric_cast< size_t >(num_refinements))
    , reference_test_case_(merge_parameters({{"mu", Dune::Pymor::Parameter("mu", 1)},
                                             {"mu_hat", Dune::Pymor::Parameter("mu", 1)},
                                             {"mu_bar", Dune::Pymor::Parameter("mu", 1)}},
                                            parameter_range_),
                           partitioning,
                           boost::numeric_cast< size_t >(num_refinements + 1))
    , discretization_(*test_case_.reference_provider(),
                      test_case_.boundary_info(),
                      test_case_.problem(),
                      products)
    , reference_discretization_(*reference_test_case_.reference_provider(),
                                reference_test_case_.boundary_info(),
                                reference_test_case_.problem(),
                                products)
  {
    auto logger = DSC::TimedLogger().get("OS2014.example");
    logger.info() << "initializing discretization... " << std::flush;
    discretization_.init();
    reference_discretization_.init();
    logger.info() << "done (grid has " << discretization_.grid_view().indexSet().size(0)
                  << " elements, discretization has " << discretization_.ansatz_space()->mapper().size() << " DoFs)"
                  << std::endl;
  } // ... OS2014Spe10Model1Example(...)

  const TestCaseType& test_case() const
  {
    return test_case_;
  }

  DiscretizationType& discretization()
  {
    return discretization_;
  }

  DiscretizationType* discretization_and_return_ptr() const
  {
    return new DiscretizationType(discretization_);
  }

  VectorType project(const std::string expression) const
  {
    using namespace Dune;
    typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;
    typedef GDT::DiscreteFunction< AnsatzSpaceType, VectorType > DiscreteFunctionType;
    DiscreteFunctionType discrete_function(*discretization_.ansatz_space());

    typedef Stuff::Functions::Expression< typename DiscreteFunctionType::EntityType,
                                          typename DiscreteFunctionType::DomainFieldType,
                                          DiscreteFunctionType::dimDomain,
                                          typename DiscreteFunctionType::RangeFieldType,
                                          DiscreteFunctionType::dimRange > ExpressionFunctionType;
    ExpressionFunctionType func("x", expression);

    GDT::Operators::Projection< typename DiscretizationType::GridViewType > projection(discretization_.grid_view());
    projection.apply(func, discrete_function);

    return discrete_function.vector();
  } // ... project(...)

  RangeFieldType compute_error(const VectorType& solution,
                               const std::string product_type = "",
                               const Dune::Pymor::Parameter mu = Dune::Pymor::Parameter(),
                               const Dune::Pymor::Parameter mu_product = Dune::Pymor::Parameter())
  {
    const std::string type = (product_type.empty() && reference_discretization_.available_products().size() == 1)
                             ? reference_discretization_.available_products()[0]
                             : product_type;
    // wrap solution into a discrete function
    using namespace Dune;
    typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;
    typedef GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType > ConstDiscreteFunctionType;
    ConstDiscreteFunctionType coarse_solution(*discretization_.ansatz_space(), solution);
    // prolong to reference grid view
    typedef GDT::DiscreteFunction< AnsatzSpaceType, VectorType > DiscreteFunctionType;
    DiscreteFunctionType fine_solution(*reference_discretization_.ansatz_space());
    GDT::Operators::Prolongation< typename DiscretizationType::GridViewType >
        prolongation_operator(reference_discretization_.grid_view());
    prolongation_operator.apply(coarse_solution, fine_solution);
    // compute reference solution
    DiscreteFunctionType reference_solution(*reference_discretization_.ansatz_space());
    reference_discretization_.solve(reference_solution.vector(), mu);
    // compute error
    const auto difference = reference_solution.vector() - fine_solution.vector();
    const auto product = reference_discretization_.get_product(type);
    return std::sqrt(product.apply2(difference, difference, mu_product));
  } // ... compute_error(...)

  RangeFieldType compute_jump_norm(const VectorType& solution_vector,
                                   const Dune::Pymor::Parameter mu_product = Dune::Pymor::Parameter())
  {
    using namespace Dune;
    typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;
    typedef GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType > ConstDiscreteFunctionType;
    ConstDiscreteFunctionType solution(*discretization_.ansatz_space(), solution_vector);
    const auto diffusion_factor = discretization_.problem().diffusion_factor()->with_mu(mu_product);
    const auto diffusion_tensor = discretization_.problem().diffusion_tensor()->with_mu(mu_product);
    typedef GDT::Products::EllipticSWIPDGPenaltyLocalizable
        < typename DiscretizationType::GridViewType,
          typename DiscretizationType::ProblemType::DiffusionFactorType::NonparametricType,
          ConstDiscreteFunctionType,
          ConstDiscreteFunctionType,
          RangeFieldType,
          typename DiscretizationType::ProblemType::DiffusionTensorType::NonparametricType > ProductType;
    ProductType penalty_product(discretization_.grid_view(),
                                solution,
                                solution,
                                *diffusion_factor,
                                *diffusion_tensor,
                                2);
    return std::sqrt(penalty_product.apply2());
  } // ... compute_jump_norm(...)

  std::vector< std::string > available_estimators() const
  {
    return Estimator::available();
  }

  RangeFieldType estimate(const VectorType& vector,
                          const std::string type,
                          const Dune::Pymor::Parameter mu_hat = Dune::Pymor::Parameter(),
                          const Dune::Pymor::Parameter mu_bar = Dune::Pymor::Parameter(),
                          const Dune::Pymor::Parameter mu     = Dune::Pymor::Parameter())
  {
    return Estimator::estimate(*discretization_.ansatz_space(),
                               vector,
                               discretization_.problem(),
                               type,
                               merge_parameters({{"mu_hat", mu_hat},
                                                 {"mu_bar", mu_bar},
                                                 {"mu",     mu}},
                                                parameter_range_));
  } // ... estimate(...)

  RangeFieldType alpha(const Dune::Pymor::Parameter& mu_1, const Dune::Pymor::Parameter& mu_2)
  {
    return test_case_.problem().diffusion_factor()->alpha(mu_1, mu_2);
  }

  RangeFieldType gamma(const Dune::Pymor::Parameter& mu_1, const Dune::Pymor::Parameter& mu_2)
  {
    return test_case_.problem().diffusion_factor()->gamma(mu_1, mu_2);
  }

private:
  static ParametersMapType merge_parameters(const ParametersMapType& first,
                                            const ParametersMapType& second)
  {
    ParametersMapType ret = first;
    for (const auto& element : second)
      ret.insert(element);
    return ret;
  }

  const ParametersMapType parameter_range_;
  TestCaseType test_case_;
  TestCaseType reference_test_case_;
  DiscretizationType discretization_;
  DiscretizationType reference_discretization_;
}; // class Example

} // namespace internal

//template< class GridImp >
//class Spe10Model1Example
//  : public internal::Example< Dune::HDD::LinearElliptic::TestCases::Spe10::ParametricBlockModel1< GridImp > >
//{
//  static_assert(GridImp::dimension == 2, "Only available in 2d!");
//  typedef internal::Example< Dune::HDD::LinearElliptic::TestCases::Spe10::ParametricBlockModel1< GridImp > > BaseType;

//public:
//  template< class... Args >
//  Spe10Model1Example(Args&& ...args)
//    : BaseType({{"parameter_range_min", Dune::Pymor::Parameter("mu", 0.1)},
//                {"parameter_range_max", Dune::Pymor::Parameter("mu", 1.0)}},
//               std::forward< Args >(args)...)
//  {}
//}; // class Spe10Model1Example

template< class GridImp >
class OS2014Example
  : public internal::Example< Dune::HDD::LinearElliptic::TestCases::OS2014::ParametricBlockConvergence< GridImp > >
{
  static_assert(GridImp::dimension == 2, "Only available in 2d!");
  typedef internal::Example
      < Dune::HDD::LinearElliptic::TestCases::OS2014::ParametricBlockConvergence< GridImp > > BaseType;

public:
  template< class... Args >
  OS2014Example(Args&& ...args)
    : BaseType({{"parameter_range_min", Dune::Pymor::Parameter("mu", 0.1)},
                {"parameter_range_max", Dune::Pymor::Parameter("mu", 1.0)}},
               std::forward< Args >(args)...)
  {}
}; // class OS2014Example

template< class GridImp >
class FiveSpotExample
  : public internal::Example< Dune::HDD::LinearElliptic::TestCases::OS2014::FiveSpotBlock< GridImp > >
{
  static_assert(GridImp::dimension == 2, "Only available in 2d!");
  typedef internal::Example
      < Dune::HDD::LinearElliptic::TestCases::OS2014::FiveSpotBlock< GridImp > > BaseType;

public:
  template< class... Args >
  FiveSpotExample(Args&& ...args)
    : BaseType({{"parameter_range_min", Dune::Pymor::Parameter("mu", 0.1)},
                {"parameter_range_max", Dune::Pymor::Parameter("mu", 0.9)}},
               std::forward< Args >(args)...)
  {}
}; // class FiveSpotExample

#endif // DUNE_HDD_EXAMPLES_LINEARELLIPTIC_OS2014_HH
<commit_msg>[examples.linearelliptic.OS2014] whitespace<commit_after>// This file is part of the dune-hdd project:
//   http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_HDD_EXAMPLES_LINEARELLIPTIC_OS2014_HH
#define DUNE_HDD_EXAMPLES_LINEARELLIPTIC_OS2014_HH

#define DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_DISABLE_WARNING

#include <boost/numeric/conversion/cast.hpp>

#include <dune/fem/misc/mpimanager.hh>

#include <dune/stuff/common/logging.hh>
#include <dune/stuff/functions/expression.hh>

#include <dune/pymor/parameters/base.hh>

#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/operators/projections.hh>
#include <dune/gdt/operators/prolongations.hh>
#include <dune/gdt/playground/products/elliptic-swipdg.hh>

#include <dune/hdd/linearelliptic/testcases/OS2014.hh>
#include <dune/hdd/linearelliptic/testcases/spe10.hh>
#include <dune/hdd/linearelliptic/discretizations/block-swipdg.hh>
#include <dune/hdd/linearelliptic/estimators/block-swipdg.hh>

namespace internal {

class Initializer
{
public:
  Initializer(const ssize_t info_log_levels,
              const ssize_t debug_log_levels,
              const bool enable_warnings,
              const bool enable_colors,
              const std::string info_color,
              const std::string debug_color,
              const std::string warn_color)
  {
    try {
      int argc = 0;
      char** argv = new char* [0];
      Dune::Fem::MPIManager::initialize(argc, argv);
    } catch (...) {}
    DSC::TimedLogger().create(info_log_levels,
                              debug_log_levels,
                              enable_warnings,
                              enable_colors,
                              info_color,
                              debug_color,
                              warn_color);
    DSC::TimedLogger().get("OS2014.initializer").info() << "creating grid and problem... " << std::endl;
  }
}; // class Initializer

template< class TestCaseType >
class Example
  : Initializer
{
public:
  typedef typename TestCaseType::GridType GridType;
  typedef double RangeFieldType;
  typedef Dune::HDD::LinearElliptic::Discretizations::BlockSWIPDG< GridType, RangeFieldType, 1 > DiscretizationType;
  typedef typename DiscretizationType::VectorType VectorType;
  typedef typename TestCaseType::ParametersMapType ParametersMapType;

private:
  typedef Dune::HDD::LinearElliptic::Estimators::BlockSWIPDG< typename DiscretizationType::AnsatzSpaceType,
                                                              VectorType,
                                                              typename DiscretizationType::ProblemType,
                                                              GridType > Estimator;

public:
  Example(const ParametersMapType& parameter_range,
          const std::string partitioning = "[1 1 1]",
          const DUNE_STUFF_SSIZE_T num_refinements = 0,
          const std::vector< std::string > products = {},
          const ssize_t info_log_levels  = 0,
          const ssize_t debug_log_levels = -1,
          const bool enable_warnings = true,
          const bool enable_colors   = true,
          const std::string info_color  = DSC::TimedLogging::default_info_color(),
          const std::string debug_color = DSC::TimedLogging::default_debug_color(),
          const std::string warn_color  = DSC::TimedLogging::default_warning_color())
    : Initializer(info_log_levels,
                  debug_log_levels,
                  enable_warnings,
                  enable_colors,
                  info_color,
                  debug_color,
                  warn_color)
    , parameter_range_(parameter_range)
    , test_case_(merge_parameters({{"mu",     Dune::Pymor::Parameter("mu", 1)},  // <- it does not matter which parameters we give to the
                                   {"mu_hat", Dune::Pymor::Parameter("mu", 1)},  //    test case here, since we use test_case_.problem()
                                   {"mu_bar", Dune::Pymor::Parameter("mu", 1)}}, //    (which is the parametric problem) anyway
                                  parameter_range_),
                 partitioning,
                 boost::numeric_cast< size_t >(num_refinements))
    , reference_test_case_(merge_parameters({{"mu",     Dune::Pymor::Parameter("mu", 1)},
                                             {"mu_hat", Dune::Pymor::Parameter("mu", 1)},
                                             {"mu_bar", Dune::Pymor::Parameter("mu", 1)}},
                                            parameter_range_),
                           partitioning,
                           boost::numeric_cast< size_t >(num_refinements + 1))
    , discretization_(*test_case_.reference_provider(),
                      test_case_.boundary_info(),
                      test_case_.problem(),
                      products)
    , reference_discretization_(*reference_test_case_.reference_provider(),
                                reference_test_case_.boundary_info(),
                                reference_test_case_.problem(),
                                products)
  {
    auto logger = DSC::TimedLogger().get("OS2014.example");
    logger.info() << "initializing discretization... " << std::flush;
    discretization_.init();
    reference_discretization_.init();
    logger.info() << "done (grid has " << discretization_.grid_view().indexSet().size(0)
                  << " elements, discretization has " << discretization_.ansatz_space()->mapper().size() << " DoFs)"
                  << std::endl;
  } // ... OS2014Spe10Model1Example(...)

  const TestCaseType& test_case() const
  {
    return test_case_;
  }

  DiscretizationType& discretization()
  {
    return discretization_;
  }

  DiscretizationType* discretization_and_return_ptr() const
  {
    return new DiscretizationType(discretization_);
  }

  VectorType project(const std::string expression) const
  {
    using namespace Dune;
    typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;
    typedef GDT::DiscreteFunction< AnsatzSpaceType, VectorType > DiscreteFunctionType;
    DiscreteFunctionType discrete_function(*discretization_.ansatz_space());

    typedef Stuff::Functions::Expression< typename DiscreteFunctionType::EntityType,
                                          typename DiscreteFunctionType::DomainFieldType,
                                          DiscreteFunctionType::dimDomain,
                                          typename DiscreteFunctionType::RangeFieldType,
                                          DiscreteFunctionType::dimRange > ExpressionFunctionType;
    ExpressionFunctionType func("x", expression);

    GDT::Operators::Projection< typename DiscretizationType::GridViewType > projection(discretization_.grid_view());
    projection.apply(func, discrete_function);

    return discrete_function.vector();
  } // ... project(...)

  RangeFieldType compute_error(const VectorType& solution,
                               const std::string product_type = "",
                               const Dune::Pymor::Parameter mu = Dune::Pymor::Parameter(),
                               const Dune::Pymor::Parameter mu_product = Dune::Pymor::Parameter())
  {
    const std::string type = (product_type.empty() && reference_discretization_.available_products().size() == 1)
                             ? reference_discretization_.available_products()[0]
                             : product_type;
    // wrap solution into a discrete function
    using namespace Dune;
    typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;
    typedef GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType > ConstDiscreteFunctionType;
    ConstDiscreteFunctionType coarse_solution(*discretization_.ansatz_space(), solution);
    // prolong to reference grid view
    typedef GDT::DiscreteFunction< AnsatzSpaceType, VectorType > DiscreteFunctionType;
    DiscreteFunctionType fine_solution(*reference_discretization_.ansatz_space());
    GDT::Operators::Prolongation< typename DiscretizationType::GridViewType >
        prolongation_operator(reference_discretization_.grid_view());
    prolongation_operator.apply(coarse_solution, fine_solution);
    // compute reference solution
    DiscreteFunctionType reference_solution(*reference_discretization_.ansatz_space());
    reference_discretization_.solve(reference_solution.vector(), mu);
    // compute error
    const auto difference = reference_solution.vector() - fine_solution.vector();
    const auto product = reference_discretization_.get_product(type);
    return std::sqrt(product.apply2(difference, difference, mu_product));
  } // ... compute_error(...)

  RangeFieldType compute_jump_norm(const VectorType& solution_vector,
                                   const Dune::Pymor::Parameter mu_product = Dune::Pymor::Parameter())
  {
    using namespace Dune;
    typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;
    typedef GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType > ConstDiscreteFunctionType;
    ConstDiscreteFunctionType solution(*discretization_.ansatz_space(), solution_vector);
    const auto diffusion_factor = discretization_.problem().diffusion_factor()->with_mu(mu_product);
    const auto diffusion_tensor = discretization_.problem().diffusion_tensor()->with_mu(mu_product);
    typedef GDT::Products::EllipticSWIPDGPenaltyLocalizable
        < typename DiscretizationType::GridViewType,
          typename DiscretizationType::ProblemType::DiffusionFactorType::NonparametricType,
          ConstDiscreteFunctionType,
          ConstDiscreteFunctionType,
          RangeFieldType,
          typename DiscretizationType::ProblemType::DiffusionTensorType::NonparametricType > ProductType;
    ProductType penalty_product(discretization_.grid_view(),
                                solution,
                                solution,
                                *diffusion_factor,
                                *diffusion_tensor,
                                2);
    return std::sqrt(penalty_product.apply2());
  } // ... compute_jump_norm(...)

  std::vector< std::string > available_estimators() const
  {
    return Estimator::available();
  }

  RangeFieldType estimate(const VectorType& vector,
                          const std::string type,
                          const Dune::Pymor::Parameter mu_hat = Dune::Pymor::Parameter(),
                          const Dune::Pymor::Parameter mu_bar = Dune::Pymor::Parameter(),
                          const Dune::Pymor::Parameter mu     = Dune::Pymor::Parameter())
  {
    return Estimator::estimate(*discretization_.ansatz_space(),
                               vector,
                               discretization_.problem(),
                               type,
                               merge_parameters({{"mu_hat", mu_hat},
                                                 {"mu_bar", mu_bar},
                                                 {"mu",     mu}},
                                                parameter_range_));
  } // ... estimate(...)

  RangeFieldType alpha(const Dune::Pymor::Parameter& mu_1, const Dune::Pymor::Parameter& mu_2)
  {
    return test_case_.problem().diffusion_factor()->alpha(mu_1, mu_2);
  }

  RangeFieldType gamma(const Dune::Pymor::Parameter& mu_1, const Dune::Pymor::Parameter& mu_2)
  {
    return test_case_.problem().diffusion_factor()->gamma(mu_1, mu_2);
  }

private:
  static ParametersMapType merge_parameters(const ParametersMapType& first,
                                            const ParametersMapType& second)
  {
    ParametersMapType ret = first;
    for (const auto& element : second)
      ret.insert(element);
    return ret;
  }

  const ParametersMapType parameter_range_;
  TestCaseType test_case_;
  TestCaseType reference_test_case_;
  DiscretizationType discretization_;
  DiscretizationType reference_discretization_;
}; // class Example

} // namespace internal

//template< class GridImp >
//class Spe10Model1Example
//  : public internal::Example< Dune::HDD::LinearElliptic::TestCases::Spe10::ParametricBlockModel1< GridImp > >
//{
//  static_assert(GridImp::dimension == 2, "Only available in 2d!");
//  typedef internal::Example< Dune::HDD::LinearElliptic::TestCases::Spe10::ParametricBlockModel1< GridImp > > BaseType;

//public:
//  template< class... Args >
//  Spe10Model1Example(Args&& ...args)
//    : BaseType({{"parameter_range_min", Dune::Pymor::Parameter("mu", 0.1)},
//                {"parameter_range_max", Dune::Pymor::Parameter("mu", 1.0)}},
//               std::forward< Args >(args)...)
//  {}
//}; // class Spe10Model1Example

template< class GridImp >
class OS2014Example
  : public internal::Example< Dune::HDD::LinearElliptic::TestCases::OS2014::ParametricBlockConvergence< GridImp > >
{
  static_assert(GridImp::dimension == 2, "Only available in 2d!");
  typedef internal::Example
      < Dune::HDD::LinearElliptic::TestCases::OS2014::ParametricBlockConvergence< GridImp > > BaseType;

public:
  template< class... Args >
  OS2014Example(Args&& ...args)
    : BaseType({{"parameter_range_min", Dune::Pymor::Parameter("mu", 0.1)},
                {"parameter_range_max", Dune::Pymor::Parameter("mu", 1.0)}},
               std::forward< Args >(args)...)
  {}
}; // class OS2014Example

template< class GridImp >
class FiveSpotExample
  : public internal::Example< Dune::HDD::LinearElliptic::TestCases::OS2014::FiveSpotBlock< GridImp > >
{
  static_assert(GridImp::dimension == 2, "Only available in 2d!");
  typedef internal::Example
      < Dune::HDD::LinearElliptic::TestCases::OS2014::FiveSpotBlock< GridImp > > BaseType;

public:
  template< class... Args >
  FiveSpotExample(Args&& ...args)
    : BaseType({{"parameter_range_min", Dune::Pymor::Parameter("mu", 0.1)},
                {"parameter_range_max", Dune::Pymor::Parameter("mu", 0.9)}},
               std::forward< Args >(args)...)
  {}
}; // class FiveSpotExample

#endif // DUNE_HDD_EXAMPLES_LINEARELLIPTIC_OS2014_HH
<|endoftext|>


<commit_before>
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Parse/ParseAST.h"
#include "clang/AST/Mangle.h"
#include "clang/Rewrite/Frontend/Rewriters.h"
#include "clang/Rewrite/Core/Rewriter.h"

#include "utilsllvm.h"
#include "fileutils.h"

#include <iostream>
#include <vector>
#include <string>
#include <locale>

using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::tooling;
using namespace llvm;

using namespace std;

std::vector<std::string> excludedPathPatterns={"extlibs/",
                                               "/usr/include/qt4/",
                                               "framework/sofa/helper",
                                               "framework/sofa/defaulttype",
                                               "framework/sofa/core",
                                               "simulation/common"};

cl::list<string> listofpath("L", cl::Prefix, cl::desc("Specify path pattern"), cl::value_desc("directory")) ;

bool isInExcludedPath(const std::string& path){
    if(listofpath.size()!=0){
        for(auto pattern : listofpath)
        {
            if( path.find(pattern) != std::string::npos )
            {
                return false ;
            }
        }
        return true;
    }else{
        for(auto pattern : excludedPathPatterns)
        {
            if( path.find(pattern) != std::string::npos )
            {
                return true ;
            }
        }
        return false ;
    }
    return false ;
}

class StyleChecker : public RecursiveASTVisitor<StyleChecker> {
public:

    void setContext(const ASTContext* ctx){
        Context=ctx;
    }

    // http://clang.llvm.org/doxygen/classclang_1_1Stmt.html
    // For each declaration
    // http://clang.llvm.org/doxygen/classclang_1_1Decl.html
    // http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html
    // and
    // http://clang.llvm.org/doxygen/classclang_1_1RecursiveASTVisitor.html
    bool VisitCXXRecordDecl(CXXRecordDecl *record) {
        if(Context==NULL)
            return true ;

        FullSourceLoc FullLocation = Context->getFullLoc(record->getLocStart());

        // Check this declaration is not in the system headers...
        if ( FullLocation.isValid() && !exclude(FullLocation.getManager() , record) )
        {
            const SourceManager& smanager=Context->getSourceManager();

            // Now check the attributes...
            RecordDecl::field_iterator it=record->field_begin() ;
            for(;it!=record->field_end();it++){
                clang::FieldDecl* ff=*it;
                ff->isTemplateDecl();

                SourceRange declsr=ff->getMostRecentDecl()->getSourceRange() ;
                SourceLocation sl=declsr.getBegin();
                std::string name=ff->getName() ;

                if( smanager.getFileEntryForID(smanager.getFileID(sl)) == NULL ){
                    continue ;
                }

                if(isInExcludedPath(smanager.getFileEntryForID(smanager.getFileID(sl))->getName())){
                    continue ;
                }

                if(name.size()==0){
                    continue ;
                }

                // RULES NUMBER 1: The name of members cannot be terminated by an underscore.
                if(name.rfind("_")!=name.size()-1){
                }else{
                    std::cerr << smanager.getFileEntryForID(smanager.getFileID(sl))->getName()
                              << ":" << smanager.getPresumedLineNumber(sl)
                              << ":" << smanager.getPresumedColumnNumber(sl)
                              << ": warning: member [" << record->getNameAsString() << ":" <<name << "] is violating the sofa coding style http://www.sofa.../codingstyle.html...member's name cannot be terminated with an underscore.' " << std::endl;
                }

                // THE FOLLOWING RULES ARE ONLY CHECK ON PRIVATE & PROTECTED FIELDS
                if(ff->getAccess()==AS_public){
                    continue ;
                }

                if(ff->getType()->isPointerType()){
                    if(name.size() > 2 && name[0] == 'p' && isupper(name[1]) ){}
                    else{
                        std::cerr << smanager.getFileEntryForID(smanager.getFileID(sl))->getName()
                                  << ":" << smanager.getPresumedLineNumber(sl)
                                  << ":" << smanager.getPresumedColumnNumber(sl)
                                  << ": warning: member [" << record->getNameAsString() << ":" <<name << "] is violating the sofa coding style http://www.sofa.../codingstyle.html... it should prefixed with pUpperCased " << std::endl;
                    }
                    continue ;
                }

                if(ff->getType()->isBooleanType()){
                    if(name.size() > 2 && name[0] == 'b' && isupper(name[1]) ){}
                    else{
                        std::cerr << smanager.getFileEntryForID(smanager.getFileID(sl))->getName()
                                  << ":" << smanager.getPresumedLineNumber(sl)
                                  << ":" << smanager.getPresumedColumnNumber(sl)
                                  << ": warning: member [" << record->getNameAsString() << ":" <<name << "] is violating the sofa coding style http://www.sofa.../codingstyle.html... it should prefixed with bUpperCased " << std::endl;
                    }
                    continue ;
                }

                CXXRecordDecl* rd=ff->getType()->getAsCXXRecordDecl() ;
                if(rd){

                    std::string type=rd->getNameAsString() ;
                    if(type.find("Data")!=std::string::npos){
                        if(name.find("d_")==0){
                        }else{
                            std::cerr << smanager.getFileEntryForID(smanager.getFileID(sl))->getName()
                                      << ":" << smanager.getPresumedLineNumber(sl)
                                      << ":" << smanager.getPresumedColumnNumber(sl)
                                      << ": warning: member [" << record->getNameAsString() << ":" <<name << "] is violating the sofa coding style http://www.sofa.../codingstyle.html...all Data<> members should start with d_ " << std::endl;
                        }
                    }else if(type.find("SingleLink")!=std::string::npos || type.find("DualLink")!=std::string::npos){
                        if(name.find("d_")==0){
                        }else{
                            std::cerr << smanager.getFileEntryForID(smanager.getFileID(sl))->getName()
                                      << ":" << smanager.getPresumedLineNumber(sl)
                                      << ":" << smanager.getPresumedColumnNumber(sl)
                                      << ": warning: member [" << record->getNameAsString() << ":" <<name << "] is violating the sofa coding style http://www.sofa.../codingstyle.html...all Link<> members should start with l_ " << std::endl;
                        }
                    }
                }else{
                    if(name.find("m_")==0){
                    }else{
                        std::cerr << smanager.getFileEntryForID(smanager.getFileID(sl))->getName()
                                  << ":" << smanager.getPresumedLineNumber(sl)
                                  << ":" << smanager.getPresumedColumnNumber(sl)
                                  << ": warning: member [" << record->getNameAsString() << ":" << name << "] is violating the sofa coding style http://www.sofa.../codingstyle.html...all non public attributes should start with m_ " << std::endl;
                    }
                }
            }
        }
        return true;
    }
private:
    const ASTContext *Context;
    MangleContext* mctx;
};

int main(int argc, const char** argv){
    static cl::OptionCategory MyToolCategory("StyleChecker");
    CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);

    ClangTool Tool(OptionsParser.getCompilations(),
                   OptionsParser.getSourcePathList());

    std::vector<std::string> localFilename;
    for(unsigned int i=1;i<argc;i++){
        localFilename.push_back(argv[i]);
    }

    // Build the ast for each file given as arguments
    std::vector<std::unique_ptr<ASTUnit> > asts;
    Tool.buildASTs(asts);

    // Create a StyleChecker visitor
    StyleChecker* sr=new StyleChecker();

    // For each file...
    for(unsigned int i=0;i<asts.size();i++){
        ASTContext& ctx=asts[i]->getASTContext();

        int j=0;
        auto it=ctx.getSourceManager().fileinfo_begin() ;
        for(;it!=ctx.getSourceManager().fileinfo_end();++it){
            j++ ;
        }
        auto& smanager=ctx.getSourceManager();
        std::cerr << smanager.getFileEntryForID(smanager.getMainFileID())->getName()
                  << ":1:1: info: number of loaded include files: " << j << std::endl ;

        //ésr->setContext(&ctx);
        //sr->TraverseDecl(ctx.getTranslationUnitDecl());
    }

}
<commit_msg>Complete version of stylecheck<commit_after>
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Parse/ParseAST.h"
#include "clang/AST/Mangle.h"
#include "clang/Rewrite/Frontend/Rewriters.h"
#include "clang/Rewrite/Core/Rewriter.h"

#include "utilsllvm.h"
#include "fileutils.h"

#include <iostream>
#include <vector>
#include <string>
#include <locale>

using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::tooling;
using namespace llvm;

using namespace std;

std::vector<std::string> excludedPathPatterns={"extlibs/",
                                               "/usr/include/qt4/",
                                               "framework/sofa/helper",
                                               "framework/sofa/defaulttype",
                                               "framework/sofa/core",
                                               "simulation/common"};

cl::list<string> listofpath("L", cl::Prefix, cl::desc("Specify path pattern"), cl::value_desc("directory")) ;

bool isInExcludedPath(const std::string& path){
    if(listofpath.size()!=0){
        for(auto pattern : listofpath)
        {
            if( path.find(pattern) != std::string::npos )
            {
                return false ;
            }
        }
        return true;
    }else{
        for(auto pattern : excludedPathPatterns)
        {
            if( path.find(pattern) != std::string::npos )
            {
                return true ;
            }
        }
        return false ;
    }
    return false ;
}

class StyleChecker : public RecursiveASTVisitor<StyleChecker> {
public:

    void setContext(const ASTContext* ctx){
        Context=ctx;
    }

    // http://clang.llvm.org/doxygen/classclang_1_1Stmt.html
    // For each declaration
    // http://clang.llvm.org/doxygen/classclang_1_1Decl.html
    // http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html
    // and
    // http://clang.llvm.org/doxygen/classclang_1_1RecursiveASTVisitor.html
    bool VisitCXXRecordDecl(CXXRecordDecl *record) {
        if(Context==NULL)
            return true ;

        FullSourceLoc FullLocation = Context->getFullLoc(record->getLocStart());

        // Check this declaration is not in the system headers...
        if ( FullLocation.isValid() && !exclude(FullLocation.getManager() , record) )
        {
            const SourceManager& smanager=Context->getSourceManager();

            // Now check the attributes...
            RecordDecl::field_iterator it=record->field_begin() ;
            for(;it!=record->field_end();it++){
                clang::FieldDecl* ff=*it;
                ff->isTemplateDecl();

                SourceRange declsr=ff->getMostRecentDecl()->getSourceRange() ;
                SourceLocation sl=declsr.getBegin();
                std::string name=ff->getName() ;

                if( smanager.getFileEntryForID(smanager.getFileID(sl)) == NULL ){
                    continue ;
                }

                if(isInExcludedPath(smanager.getFileEntryForID(smanager.getFileID(sl))->getName())){
                    continue ;
                }

                if(name.size()==0){
                    continue ;
                }

                // RULES NUMBER 1: The name of members cannot be terminated by an underscore.
                if(name.rfind("_")!=name.size()-1){
                }else{
                    std::cerr << smanager.getFileEntryForID(smanager.getFileID(sl))->getName()
                              << ":" << smanager.getPresumedLineNumber(sl)
                              << ":" << smanager.getPresumedColumnNumber(sl)
                              << ": warning: member [" << record->getNameAsString() << ":" <<name << "] is violating the sofa coding style http://www.sofa.../codingstyle.html...member's name cannot be terminated with an underscore.' " << std::endl;
                }

                // THE FOLLOWING RULES ARE ONLY CHECK ON PRIVATE & PROTECTED FIELDS
                if(ff->getAccess()==AS_public){
                    continue ;
                }

                if(ff->getType()->isPointerType()){
                    if(name.size() > 2 && name[0] == 'p' && isupper(name[1]) ){}
                    else{
                        std::cerr << smanager.getFileEntryForID(smanager.getFileID(sl))->getName()
                                  << ":" << smanager.getPresumedLineNumber(sl)
                                  << ":" << smanager.getPresumedColumnNumber(sl)
                                  << ": warning: member [" << record->getNameAsString() << ":" <<name << "] is violating the sofa coding style http://www.sofa.../codingstyle.html... it should prefixed with pUpperCased " << std::endl;
                    }
                    continue ;
                }

                if(ff->getType()->isBooleanType()){
                    if(name.size() > 2 && name[0] == 'b' && isupper(name[1]) ){}
                    else{
                        std::cerr << smanager.getFileEntryForID(smanager.getFileID(sl))->getName()
                                  << ":" << smanager.getPresumedLineNumber(sl)
                                  << ":" << smanager.getPresumedColumnNumber(sl)
                                  << ": warning: member [" << record->getNameAsString() << ":" <<name << "] is violating the sofa coding style http://www.sofa.../codingstyle.html... it should prefixed with bUpperCased " << std::endl;
                    }
                    continue ;
                }

                CXXRecordDecl* rd=ff->getType()->getAsCXXRecordDecl() ;
                if(rd){
                    std::string type=rd->getNameAsString() ;
                    if(type.find("Data")!=std::string::npos){
                        if(name.find("d_")==0){
                        }else{
                            std::cerr << smanager.getFileEntryForID(smanager.getFileID(sl))->getName()
                                      << ":" << smanager.getPresumedLineNumber(sl)
                                      << ":" << smanager.getPresumedColumnNumber(sl)
                                      << ": warning: member [" << record->getNameAsString() << ":" <<name << "] is violating the sofa coding style http://www.sofa.../codingstyle.html...all Data<> members should start with d_ " << std::endl;
                        }
                    }else if(type.find("SingleLink")!=std::string::npos || type.find("DualLink")!=std::string::npos){
                        if(name.find("d_")==0){
                        }else{
                            std::cerr << smanager.getFileEntryForID(smanager.getFileID(sl))->getName()
                                      << ":" << smanager.getPresumedLineNumber(sl)
                                      << ":" << smanager.getPresumedColumnNumber(sl)
                                      << ": warning: member [" << record->getNameAsString() << ":" <<name << "] is violating the sofa coding style http://www.sofa.../codingstyle.html...all Link<> members should start with l_ " << std::endl;
                        }
                    }
                }else{
                    if(name.find("m_")==0){
                    }else{
                        std::cerr << smanager.getFileEntryForID(smanager.getFileID(sl))->getName()
                                  << ":" << smanager.getPresumedLineNumber(sl)
                                  << ":" << smanager.getPresumedColumnNumber(sl)
                                  << ": warning: member [" << record->getNameAsString() << ":" << name << "] is violating the sofa coding style http://www.sofa.../codingstyle.html...all non public attributes should start with m_ " << std::endl;
                    }
                }
            }
        }
        return true;
    }
private:
    const ASTContext *Context;
    MangleContext* mctx;
};

int main(int argc, const char** argv){
    static cl::OptionCategory MyToolCategory("StyleChecker");
    CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);

    ClangTool Tool(OptionsParser.getCompilations(),
                   OptionsParser.getSourcePathList());

    std::vector<std::string> localFilename;
    for(unsigned int i=1;i<argc;i++){
        localFilename.push_back(argv[i]);
    }

    // Build the ast for each file given as arguments
    std::vector<std::unique_ptr<ASTUnit> > asts;
    Tool.buildASTs(asts);

    // Create a StyleChecker visitor
    StyleChecker* sr=new StyleChecker();

    // For each file...
    for(unsigned int i=0;i<asts.size();i++){
        ASTContext& ctx=asts[i]->getASTContext();

        int j=0;
        auto it=ctx.getSourceManager().fileinfo_begin() ;
        for(;it!=ctx.getSourceManager().fileinfo_end();++it){
            j++ ;
        }
        auto& smanager=ctx.getSourceManager();
        std::cerr << smanager.getFileEntryForID(smanager.getMainFileID())->getName()
                  << ":1:1: info: number of loaded include files: " << j << std::endl ;

        //ésr->setContext(&ctx);
        //sr->TraverseDecl(ctx.getTranslationUnitDecl());
    }

}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QPointF>
#include <QNetworkProxy>
#include <QMessageBox>
#include <QTimer>

#include <QGeoCoordinate>

#ifdef Q_OS_SYMBIAN
#include <QMessageBox>
#include <qnetworksession.h>
#include <qnetworkconfigmanager.h>
#endif

QTM_USE_NAMESPACE

MapWidget::MapWidget(QGeoMappingManager *manager)
    : QGeoMapWidget(manager),
    panActive(false) {}

MapWidget::~MapWidget() {}

void MapWidget::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
    setFocus();
    if (event->button() == Qt::LeftButton)
        panActive = true;

    event->accept();
}

void MapWidget::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
{
    if (event->button() == Qt::LeftButton)
        panActive = false;

    event->accept();
}

void MapWidget::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
    if (panActive) {
        int deltaLeft = event->lastPos().x() - event->pos().x();
        int deltaTop  = event->lastPos().y() - event->pos().y();
        pan(deltaLeft, deltaTop);
    }

    event->accept();
}

void MapWidget::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
    setFocus();

    pan(event->lastPos().x() -  size().width() / 2.0, event->lastPos().y() - size().height() / 2.0);
    if (zoomLevel() < maximumZoomLevel())
        setZoomLevel(zoomLevel() + 1);

    event->accept();
}

void MapWidget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Minus) {
        if (zoomLevel() > minimumZoomLevel()) {
            setZoomLevel(zoomLevel() - 1);
        }
    } else if (event->key() == Qt::Key_Plus) {
        if (zoomLevel() < maximumZoomLevel()) {
            setZoomLevel(zoomLevel() + 1);
        }
    }

    event->accept();
}

void MapWidget::wheelEvent(QGraphicsSceneWheelEvent* event)
{
    if (event->delta() > 0) { //zoom in
        if (zoomLevel() > minimumZoomLevel()) {
            setZoomLevel(zoomLevel() + 1);
        }
    } else { //zoom out
        if (zoomLevel() < maximumZoomLevel()) {
            setZoomLevel(zoomLevel() - 1);
        }
    }
    event->accept();
}

MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow),
        m_serviceProvider(0)
{
    ui->setupUi(this);
    setProvider("nokia");

    qgv = new QGraphicsView(this);
    qgv->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    qgv->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    qgv->setVisible(true);
    qgv->setGeometry(QRect(0, 0, width(), height()));
    qgv->setInteractive(true);

    QGraphicsScene* scene = new QGraphicsScene(0, 0, width(), height());
    qgv->setScene(scene);

    m_mapWidget = new MapWidget(m_mapManager);
    qgv->scene()->addItem(m_mapWidget);
    m_mapWidget->setGeometry(0, 0, width(), height());
    //m_mapWidget->setZoomLevel(8);
    m_mapWidget->setCenter(QGeoCoordinate(52.5,13.0));

    setWindowTitle(tr("Map Viewer Demo"));

    //QTimer::singleShot(0, this, SLOT(delayedInit()));
}

MainWindow::~MainWindow()
{
    delete m_serviceProvider;
    delete ui;
}

void MainWindow::setProvider(QString providerId)
{
    QMap<QString, QString> parameters;
    if (providerId == "nokia") {
        parameters.insert("places.proxy", "172.16.42.137");
        parameters.insert("places.host", "dev-a7.bln.gate5.de");
        parameters.insert("routing.proxy", "172.16.42.137");
        parameters.insert("routing.host", "172.24.32.155");
        parameters.insert("mapping.proxy", "172.16.42.40");
        parameters.insert("mapping.host", "maptile.svc.nokia.com.edgesuite.net");
    }

    if (m_serviceProvider)
        delete m_serviceProvider ;
    m_serviceProvider = new QGeoServiceProvider(providerId, parameters);
    if (m_serviceProvider->error() != QGeoServiceProvider::NoError) {
        QMessageBox::information(this, tr("MapViewer Example"), tr(
                                     "Unable to find the %1 geoservices plugin.").arg(providerId));
        qApp->quit();
        return;
    }

    m_mapManager = m_serviceProvider->mappingManager();
}

void MainWindow::resizeEvent(QResizeEvent* event)
{
    qgv->resize(event->size());
    qgv->setSceneRect(0, 0, event->size().width(), event->size().height());
    m_mapWidget->resize(event->size());
}

void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
        case QEvent::LanguageChange:
            ui->retranslateUi(this);
            break;
        default:
            break;
    }
}
<commit_msg>Fixed MapWidget::wheelEvent, test for zoom level limits was reversed<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QPointF>
#include <QNetworkProxy>
#include <QMessageBox>
#include <QTimer>

#include <QGeoCoordinate>

#ifdef Q_OS_SYMBIAN
#include <QMessageBox>
#include <qnetworksession.h>
#include <qnetworkconfigmanager.h>
#endif

QTM_USE_NAMESPACE

MapWidget::MapWidget(QGeoMappingManager *manager)
    : QGeoMapWidget(manager),
    panActive(false) {}

MapWidget::~MapWidget() {}

void MapWidget::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
    setFocus();
    if (event->button() == Qt::LeftButton)
        panActive = true;

    event->accept();
}

void MapWidget::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
{
    if (event->button() == Qt::LeftButton)
        panActive = false;

    event->accept();
}

void MapWidget::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
    if (panActive) {
        int deltaLeft = event->lastPos().x() - event->pos().x();
        int deltaTop  = event->lastPos().y() - event->pos().y();
        pan(deltaLeft, deltaTop);
    }

    event->accept();
}

void MapWidget::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
    setFocus();

    pan(event->lastPos().x() -  size().width() / 2.0, event->lastPos().y() - size().height() / 2.0);
    if (zoomLevel() < maximumZoomLevel())
        setZoomLevel(zoomLevel() + 1);

    event->accept();
}

void MapWidget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Minus) {
        if (zoomLevel() > minimumZoomLevel()) {
            setZoomLevel(zoomLevel() - 1);
        }
    } else if (event->key() == Qt::Key_Plus) {
        if (zoomLevel() < maximumZoomLevel()) {
            setZoomLevel(zoomLevel() + 1);
        }
    }

    event->accept();
}

void MapWidget::wheelEvent(QGraphicsSceneWheelEvent* event)
{
    if (event->delta() > 0) { //zoom in
        if (zoomLevel() < maximumZoomLevel()) {
            setZoomLevel(zoomLevel() + 1);
        }
    } else { //zoom out
        if (zoomLevel() > minimumZoomLevel()) {
            setZoomLevel(zoomLevel() - 1);
        }
    }
    event->accept();
}

MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow),
        m_serviceProvider(0)
{
    ui->setupUi(this);
    setProvider("nokia");

    qgv = new QGraphicsView(this);
    qgv->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    qgv->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    qgv->setVisible(true);
    qgv->setGeometry(QRect(0, 0, width(), height()));
    qgv->setInteractive(true);

    QGraphicsScene* scene = new QGraphicsScene(0, 0, width(), height());
    qgv->setScene(scene);

    m_mapWidget = new MapWidget(m_mapManager);
    qgv->scene()->addItem(m_mapWidget);
    m_mapWidget->setGeometry(0, 0, width(), height());
    //m_mapWidget->setZoomLevel(8);
    m_mapWidget->setCenter(QGeoCoordinate(52.5,13.0));

    setWindowTitle(tr("Map Viewer Demo"));

    //QTimer::singleShot(0, this, SLOT(delayedInit()));
}

MainWindow::~MainWindow()
{
    delete m_serviceProvider;
    delete ui;
}

void MainWindow::setProvider(QString providerId)
{
    QMap<QString, QString> parameters;
    if (providerId == "nokia") {
        parameters.insert("places.proxy", "172.16.42.137");
        parameters.insert("places.host", "dev-a7.bln.gate5.de");
        parameters.insert("routing.proxy", "172.16.42.137");
        parameters.insert("routing.host", "172.24.32.155");
        parameters.insert("mapping.proxy", "172.16.42.40");
        parameters.insert("mapping.host", "maptile.svc.nokia.com.edgesuite.net");
    }

    if (m_serviceProvider)
        delete m_serviceProvider ;
    m_serviceProvider = new QGeoServiceProvider(providerId, parameters);
    if (m_serviceProvider->error() != QGeoServiceProvider::NoError) {
        QMessageBox::information(this, tr("MapViewer Example"), tr(
                                     "Unable to find the %1 geoservices plugin.").arg(providerId));
        qApp->quit();
        return;
    }

    m_mapManager = m_serviceProvider->mappingManager();
}

void MainWindow::resizeEvent(QResizeEvent* event)
{
    qgv->resize(event->size());
    qgv->setSceneRect(0, 0, event->size().width(), event->size().height());
    m_mapWidget->resize(event->size());
}

void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
        case QEvent::LanguageChange:
            ui->retranslateUi(this);
            break;
        default:
            break;
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * 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: b2drange.cxx,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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basegfx.hxx"
#include <basegfx/range/b2drange.hxx>
#include <basegfx/range/b2irange.hxx>
#include <basegfx/numeric/ftools.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>

namespace basegfx
{
    B2DRange::B2DRange( const B2IRange& rRange ) :
        maRangeX(),
        maRangeY()
    {
        if( !rRange.isEmpty() )
        {
            maRangeX = rRange.getMinX();
            maRangeY = rRange.getMinY();

            maRangeX.expand(rRange.getMaxX());
            maRangeY.expand(rRange.getMaxY());
        }
    }

    void B2DRange::transform(const B2DHomMatrix& rMatrix)
    {
        if(!isEmpty() && !rMatrix.isIdentity())
        {
            const B2DRange aSource(*this);
            reset();
            expand(rMatrix * B2DPoint(aSource.getMinX(), aSource.getMinY()));
            expand(rMatrix * B2DPoint(aSource.getMaxX(), aSource.getMinY()));
            expand(rMatrix * B2DPoint(aSource.getMinX(), aSource.getMaxY()));
            expand(rMatrix * B2DPoint(aSource.getMaxX(), aSource.getMaxY()));
        }
    }

    B2IRange fround(const B2DRange& rRange)
    {
        return rRange.isEmpty() ?
            B2IRange() :
            B2IRange(fround(rRange.getMinimum()),
                     fround(rRange.getMaximum()));
    }

} // end of namespace basegfx

// eof
<commit_msg>INTEGRATION: CWS aw033 (1.6.2); FILE MERGED 2008/06/10 09:26:44 aw 1.6.2.5: #i39532# adapted missing tooling conversion 2008/05/14 14:41:17 aw 1.6.2.4: RESYNC: (1.9-1.10); FILE MERGED 2006/09/26 14:51:42 aw 1.6.2.3: RESYNC: (1.7-1.8); FILE MERGED 2006/05/12 14:36:32 aw 1.6.2.2: RESYNC: (1.6-1.7); FILE MERGED 2006/05/12 11:36:08 aw 1.6.2.1: code changes for primitive support<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: b2drange.cxx,v $
 * $Revision: 1.11 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <basegfx/range/b2drange.hxx>
#include <basegfx/range/b2irange.hxx>
#include <basegfx/numeric/ftools.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>

namespace basegfx
{
    B2DRange::B2DRange( const B2IRange& rRange ) :
        maRangeX(),
        maRangeY()
    {
        if( !rRange.isEmpty() )
        {
            maRangeX = rRange.getMinX();
            maRangeY = rRange.getMinY();

            maRangeX.expand(rRange.getMaxX());
            maRangeY.expand(rRange.getMaxY());
        }
    }

    void B2DRange::transform(const B2DHomMatrix& rMatrix)
    {
        if(!isEmpty() && !rMatrix.isIdentity())
        {
            const B2DRange aSource(*this);
            reset();
            expand(rMatrix * B2DPoint(aSource.getMinX(), aSource.getMinY()));
            expand(rMatrix * B2DPoint(aSource.getMaxX(), aSource.getMinY()));
            expand(rMatrix * B2DPoint(aSource.getMinX(), aSource.getMaxY()));
            expand(rMatrix * B2DPoint(aSource.getMaxX(), aSource.getMaxY()));
        }
    }

    B2IRange fround(const B2DRange& rRange)
    {
        return rRange.isEmpty() ?
            B2IRange() :
            B2IRange(fround(rRange.getMinimum()),
                     fround(rRange.getMaximum()));
    }
} // end of namespace basegfx

// eof
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: b2dtuple.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hjs $ $Date: 2004-06-25 17:18:36 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _BGFX_TUPLE_B2DTUPLE_HXX
#include <basegfx/tuple/b2dtuple.hxx>
#endif

#ifndef _BGFX_NUMERIC_FTOOLS_HXX
#include <basegfx/numeric/ftools.hxx>
#endif
#ifndef INCLUDED_RTL_INSTANCE_HXX
#include <rtl/instance.hxx>
#endif

namespace { struct EmptyTuple : public rtl::Static<basegfx::B2DTuple, EmptyTuple> {}; }

namespace basegfx
{
    const B2DTuple& B2DTuple::getEmptyTuple()
    {
        return EmptyTuple::get();
    }

    bool B2DTuple::equalZero() const
    {
        return (this == &getEmptyTuple() ||
                (::basegfx::fTools::equalZero(mfX) && ::basegfx::fTools::equalZero(mfY)));
    }

    bool B2DTuple::equalZero(const double& rfSmallValue) const
    {
        return (this == &getEmptyTuple() ||
                (::basegfx::fTools::equalZero(mfX, rfSmallValue) && ::basegfx::fTools::equalZero(mfY, rfSmallValue)));
    }

    bool B2DTuple::equal(const B2DTuple& rTup) const
    {
        return (
            ::basegfx::fTools::equal(mfX, rTup.mfX) &&
            ::basegfx::fTools::equal(mfY, rTup.mfY));
    }

    bool B2DTuple::equal(const B2DTuple& rTup, const double& rfSmallValue) const
    {
        return (
            ::basegfx::fTools::equal(mfX, rTup.mfX, rfSmallValue) &&
            ::basegfx::fTools::equal(mfY, rTup.mfY, rfSmallValue));
    }

    void B2DTuple::correctValues(const double fCompareValue)
    {
        if(0.0 == fCompareValue)
        {
            if(::basegfx::fTools::equalZero(mfX))
            {
                mfX = 0.0;
            }

            if(::basegfx::fTools::equalZero(mfY))
            {
                mfY = 0.0;
            }
        }
        else
        {
            if(::basegfx::fTools::equal(mfX, fCompareValue))
            {
                mfX = fCompareValue;
            }

            if(::basegfx::fTools::equal(mfY, fCompareValue))
            {
                mfY = fCompareValue;
            }
        }
    }
} // end of namespace basegfx

// eof
<commit_msg>INTEGRATION: CWS aw019 (1.7.14); FILE MERGED 2004/10/06 11:14:28 aw 1.7.14.1: #i34831#<commit_after>/*************************************************************************
 *
 *  $RCSfile: b2dtuple.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: pjunck $ $Date: 2004-11-03 08:39:28 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _BGFX_TUPLE_B2DTUPLE_HXX
#include <basegfx/tuple/b2dtuple.hxx>
#endif

#ifndef _BGFX_NUMERIC_FTOOLS_HXX
#include <basegfx/numeric/ftools.hxx>
#endif
#ifndef INCLUDED_RTL_INSTANCE_HXX
#include <rtl/instance.hxx>
#endif

namespace { struct EmptyTuple : public rtl::Static<basegfx::B2DTuple, EmptyTuple> {}; }

#ifndef _BGFX_TUPLE_B2ITUPLE_HXX
#include <basegfx/tuple/b2ituple.hxx>
#endif

namespace basegfx
{
    const B2DTuple& B2DTuple::getEmptyTuple()
    {
        return EmptyTuple::get();
    }

    B2DTuple::B2DTuple(const B2ITuple& rTup)
    :   mfX( rTup.getX() ),
        mfY( rTup.getY() )
    {}

    bool B2DTuple::equalZero() const
    {
        return (this == &getEmptyTuple() ||
                (::basegfx::fTools::equalZero(mfX) && ::basegfx::fTools::equalZero(mfY)));
    }

    bool B2DTuple::equalZero(const double& rfSmallValue) const
    {
        return (this == &getEmptyTuple() ||
                (::basegfx::fTools::equalZero(mfX, rfSmallValue) && ::basegfx::fTools::equalZero(mfY, rfSmallValue)));
    }

    bool B2DTuple::equal(const B2DTuple& rTup) const
    {
        return (
            ::basegfx::fTools::equal(mfX, rTup.mfX) &&
            ::basegfx::fTools::equal(mfY, rTup.mfY));
    }

    bool B2DTuple::equal(const B2DTuple& rTup, const double& rfSmallValue) const
    {
        return (
            ::basegfx::fTools::equal(mfX, rTup.mfX, rfSmallValue) &&
            ::basegfx::fTools::equal(mfY, rTup.mfY, rfSmallValue));
    }

    void B2DTuple::correctValues(const double fCompareValue)
    {
        if(0.0 == fCompareValue)
        {
            if(::basegfx::fTools::equalZero(mfX))
            {
                mfX = 0.0;
            }

            if(::basegfx::fTools::equalZero(mfY))
            {
                mfY = 0.0;
            }
        }
        else
        {
            if(::basegfx::fTools::equal(mfX, fCompareValue))
            {
                mfX = fCompareValue;
            }

            if(::basegfx::fTools::equal(mfY, fCompareValue))
            {
                mfY = fCompareValue;
            }
        }
    }

    B2ITuple fround(const B2DTuple& rTup)
    {
        return B2ITuple(fround(rTup.getX()), fround(rTup.getY()));
    }
} // end of namespace basegfx

// eof
<|endoftext|>


<commit_before>#include <libport/config.h>

#include <boost/lexical_cast.hpp>

#include <libport/cstring>
#include <libport/detect-win32.h>

#if defined LIBPORT_WIN32 || defined WIN32
# include <libport/windows.hh>
# include <libport/lockable.hh>
# include <iostream>
#else
# if not defined LIBPORT_URBI_ENV_AIBO
#  include <sys/select.h>
# endif
# include <errno.h>
#endif

#include <libport/compiler.hh>
#include <libport/read-stdin.hh>
#include <libport/exception.hh>

namespace libport
{

#if defined LIBPORT_WIN32 || defined WIN32

  /*----------.
  | Windows.  |
  `----------*/

  typedef std::pair<std::string, Lockable> data_type;
  static DWORD WINAPI
  readThread(void* d)
  {
    data_type&data = *reinterpret_cast<data_type*>(d);
    while (true)
    {
      static char buf[BUFSIZ];
      DWORD count = 0;
      ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, sizeof buf, &count, 0);
      BlockLock bl(data.second);
      data.first.append(buf, count);
    }
  }

  std::string
  read_stdin()
  {
    static bool started = false;
    static data_type data;
    if (!started)
    {
      started = true;
      unsigned long id;
      CreateThread(NULL, 0, &readThread, &data, 0, &id);
      return std::string();
    }
    BlockLock bl(data.second);
    std::string res = data.first;
    data.first.clear();
    return res;
  }

#elif defined LIBPORT_URBI_ENV_AIBO

  /*-------.
  | AIBO.  |
  `-------*/

  std::string
  read_stdin()
  {
    return std::string();
  }

#else

  /*-------.
  | Unix.  |
  `-------*/

  std::string
  read_stdin()
  {
    fd_set fd;
    FD_ZERO(&fd);
    FD_SET(0,&fd);
    struct timeval tv;
    tv.tv_sec = tv.tv_usec = 0;
    int r = select(1, &fd, 0, 0, &tv);
    if (r <= -1)
      throw exception::Exception(__PRETTY_FUNCTION__,
	  std::string("select error on stdin: ") + strerror(errno));
    else if (r>0)
    {
      char buf[BUFSIZ];
      r = read(0, buf, sizeof buf);
      if (r <= 0) // EOF counts as an 'error'.
        throw exception::Exception(__PRETTY_FUNCTION__,
                                   std::string("read error on stdin: ")
                                   + (r ? strerror(errno) : "EOF"));
      else
	return std::string(buf, r);
    }
    else
      return std::string();
  }

#endif

}
<commit_msg>Don't use "not" with cpp.<commit_after>#include <libport/config.h>

#include <boost/lexical_cast.hpp>

#include <libport/cstring>
#include <libport/detect-win32.h>

#if defined LIBPORT_WIN32 || defined WIN32
# include <libport/windows.hh>
# include <libport/lockable.hh>
# include <iostream>
#else
# if ! defined LIBPORT_URBI_ENV_AIBO
#  include <sys/select.h>
# endif
# include <errno.h>
#endif

#include <libport/compiler.hh>
#include <libport/read-stdin.hh>
#include <libport/exception.hh>

namespace libport
{

#if defined LIBPORT_WIN32 || defined WIN32

  /*----------.
  | Windows.  |
  `----------*/

  typedef std::pair<std::string, Lockable> data_type;
  static DWORD WINAPI
  readThread(void* d)
  {
    data_type&data = *reinterpret_cast<data_type*>(d);
    while (true)
    {
      static char buf[BUFSIZ];
      DWORD count = 0;
      ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, sizeof buf, &count, 0);
      BlockLock bl(data.second);
      data.first.append(buf, count);
    }
  }

  std::string
  read_stdin()
  {
    static bool started = false;
    static data_type data;
    if (!started)
    {
      started = true;
      unsigned long id;
      CreateThread(NULL, 0, &readThread, &data, 0, &id);
      return std::string();
    }
    BlockLock bl(data.second);
    std::string res = data.first;
    data.first.clear();
    return res;
  }

#elif defined LIBPORT_URBI_ENV_AIBO

  /*-------.
  | AIBO.  |
  `-------*/

  std::string
  read_stdin()
  {
    return std::string();
  }

#else

  /*-------.
  | Unix.  |
  `-------*/

  std::string
  read_stdin()
  {
    fd_set fd;
    FD_ZERO(&fd);
    FD_SET(0,&fd);
    struct timeval tv;
    tv.tv_sec = tv.tv_usec = 0;
    int r = select(1, &fd, 0, 0, &tv);
    if (r <= -1)
      throw exception::Exception(__PRETTY_FUNCTION__,
	  std::string("select error on stdin: ") + strerror(errno));
    else if (r>0)
    {
      char buf[BUFSIZ];
      r = read(0, buf, sizeof buf);
      if (r <= 0) // EOF counts as an 'error'.
        throw exception::Exception(__PRETTY_FUNCTION__,
                                   std::string("read error on stdin: ")
                                   + (r ? strerror(errno) : "EOF"));
      else
	return std::string(buf, r);
    }
    else
      return std::string();
  }

#endif

}
<|endoftext|>