<commit_before>#ifndef DUNE_STUFF_GRID_PROVIDER_CUBE_HH
#define DUNE_STUFF_GRID_PROVIDER_CUBE_HH

#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include <config.h>
#endif // ifdef HAVE_CMAKE_CONFIG

#if HAVE_DUNE_GRID

#include <sstream>
#include <type_traits>
#include <boost/assign/list_of.hpp>

#include <dune/common/parametertree.hh>
#include <dune/common/shared_ptr.hh>
#include <dune/common/exceptions.hh>
#include <dune/common/fvector.hh>
#include <dune/common/static_assert.hh>

#include <dune/grid/utility/structuredgridfactory.hh>
#include <dune/grid/yaspgrid.hh>
#ifdef HAVE_ALUGRID
  #include <dune/grid/alugrid.hh>
#endif
#include <dune/grid/sgrid.hh>

#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/color.hh>

#include "interface.hh"

namespace Dune {
namespace Stuff {
namespace Grid {
namespace Provider {

/**
 *  \brief  Creates a grid of a cube in various dimensions.
 *
 *          Default implementation using the Dune::StructuredGridFactory to create a grid of a cube in 1, 2 or 3
 *          dimensions. Tested with
 *

 \c YASPGRID, \c variant 1, dim = 1, 2, 3,
 *
 \c SGRID, \c variant 1, dim = 1, 2, 3,
 *
 \c ALUGRID_SIMPLEX, \c variant 2, dim = 2, 3,
 *
 \c ALUGRID_CONFORM, \c variant 2, dim = 2, 2 and
 *
 \c ALUGRID_CUBE, \c variant 1, dim = 2, 3.

 *  \tparam GridImp
 *          Type of the underlying grid.
 *  \tparam variant
 *          Type of the codim 0 elements:
 *

\c 1: cubes
 *
2: simplices

 **/
template< typename GridImp, int variant >
class GenericCube
  : public Interface< GridImp >
{
public:
  //! Type of the provided grid.
  typedef GridImp GridType;

  typedef Interface< GridType > BaseType;

  typedef GenericCube< GridType, variant > ThisType;

private:
  typedef typename GridType::LeafGridView GridViewType;

public:
  static const unsigned int dim = BaseType::dim;

  //! Type of the grids coordinates.
  typedef typename GridType::ctype ctype;
  typedef Dune::FieldVector< ctype, dim > CoordinateType;

  //! Unique identifier: \c stuff.grid.provider.cube
  static const std::string id()
  {
    return BaseType::id() + ".cube";
  }

  /**
   *  \brief      Creates a cube.
   *  \param[in]  lowerLeft
   *              A double that is used as a lower left corner in each dimension.
   *  \param[in]  upperRight
   *              A double that is used as a upper right corner in each dimension.
   *  \param[in]  numElements (optional)
   *              number of elements.
   **/
  GenericCube(const double _lowerLeft = 0.0, const double _upperRight = 1.0, const unsigned int numElements = 1u)
    : lowerLeft_(_lowerLeft),
      upperRight_(_upperRight)
  {
    Dune::array< unsigned int, dim > tmpNumElements;
    std::fill(tmpNumElements.begin(), tmpNumElements.end(), numElements);
    buildGrid(tmpNumElements);
  }

  /**
   *  \brief      Creates a cube.
   *  \param[in]  lowerLeft
   *              A vector that is used as a lower left corner.
   *  \param[in]  upperRight
   *              A vector that is used as a upper right corner.
   *  \param[in]  numElements (optional)
   *              number of elements.
   **/
  GenericCube(const CoordinateType& _lowerLeft, const CoordinateType& _upperRight, const unsigned int numElements = 1u)
    : lowerLeft_(_lowerLeft),
      upperRight_(_upperRight)
  {
    Dune::array< unsigned int, dim > tmpNumElements;
    std::fill(tmpNumElements.begin(), tmpNumElements.end(), numElements);
    buildGrid(tmpNumElements);
  }

  /**
    \brief      Creates a cube. This signature allows to prescribe anisotopic refinement
    \param[in]  lowerLeft
                A double that is used as a lower left corner in each dimension.
    \param[in]  upperRight
                A double that is used as a upper right corner in each dimension.
    \param[in]  numElements
                number of elements in each dimension.
                can contain 0 to dim elements (missing dimension are initialized to 1)
    \tparam Coord anything that CoordinateType allows to copy construct from
    \tparam ContainerType some sequence type that functions with std::begin/end
    \tparam T an unsigned integral Type
    **/
  template< class ContainerType  >
  GenericCube(const CoordinateType& _lowerLeft, const CoordinateType& _upperRight,
              const ContainerType numElements
                = boost::assign::list_of< typename ContainerType::value_type>().repeat(dim,
                                                                                typename ContainerType::value_type(1u)))
    : lowerLeft_(_lowerLeft),
      upperRight_(_upperRight)
  {
    Dune::array< unsigned int, dim > tmpNumElements;
    static_assert(std::is_unsigned< typename ContainerType::value_type >::value
                  && std::is_integral< typename ContainerType::value_type >::value,
                  "only unsigned integral number of elements per dimension allowed");
    //base init in case input is shorter
    std::fill(tmpNumElements.begin(), tmpNumElements.end(), 1u);
    std::copy(numElements.begin(), numElements.end(), tmpNumElements.begin());
    buildGrid(tmpNumElements);
  }

  GenericCube(ThisType& other)
    : lowerLeft_(other.lowerLeft_)
    , upperRight_(other.upperRight_)
    , grid_(other.grid_)
  {}

  GenericCube(const ThisType& other)
    : lowerLeft_(other.lowerLeft_)
    , upperRight_(other.upperRight_)
    , grid_(other.grid_)
  {}

  /**
   *  \brief      Creates a cube.
   *  \param[in]  paramTree
   *              A Dune::ParameterTree containing
   *

 the following keys directly or
   *
 a subtree named Cube::id, containing the following keys. If a subtree is present, it is always selected. Also it is solely selceted, so that all keys in the supertree are ignored.

   *              The actual keys are:
   *

 \c lowerLeft: \a double or a vector that is used as lower left corners.
   *
 \c upperRight: \a double or a vector that is used as upper right corners.
   *
 \c numElements: \a int or vector to denote the number of elements.
   *

   **/
  static ThisType createFromParamTree(const Dune::ParameterTree& paramTree, const std::string subName = id())
  {
    // get correct paramTree
    Dune::Stuff::Common::ParameterTreeX extendedParamTree;
    if (paramTree.hasSub(subName))
      extendedParamTree = paramTree.sub(subName);
    else
      extendedParamTree = paramTree;
    // get lower left
    std::vector< ctype > lowerLefts;
    if (extendedParamTree.hasVector("lowerLeft")) {
      lowerLefts = extendedParamTree.getVector("lowerLeft", ctype(0), dim);
      assert(lowerLefts.size() >= dim && "Given vector too short!");
    } else if (extendedParamTree.hasKey("lowerLeft")) {
        const ctype lowerLeft = extendedParamTree.get("lowerLeft", ctype(0));
        lowerLefts = std::vector< ctype >(dim, lowerLeft);
    } else {
      std::cout << "\n" << Dune::Stuff::Common::highlightString("WARNING in " + id() + ":", Dune::Stuff::Common::Colors::brown)
                << " neither vector nor key 'lowerLeft' given, defaulting to 0.0!" << std::flush;
      lowerLefts = std::vector< ctype >(dim, ctype(0));
    }
    // get upper right
    std::vector< ctype > upperRights;
    if (extendedParamTree.hasVector("upperRight")) {
      upperRights = extendedParamTree.getVector("upperRight", ctype(1), dim);
      assert(upperRights.size() >= dim && "Given vector too short!");
    } else if (extendedParamTree.hasKey("upperRight")) {
        const ctype upperRight = extendedParamTree.get("upperRight", ctype(1));
        upperRights = std::vector< ctype >(dim, upperRight);
    } else {
      std::cout << "\n" << Dune::Stuff::Common::highlightString("WARNING in " + id() + ":", Dune::Stuff::Common::Colors::brown)
                << " neither vector nor key 'upperRight' given, defaulting to 1.0!" << std::flush;
      upperRights = std::vector< ctype >(dim, ctype(1));
    }
    // get number of elements
    std::vector< unsigned int > tmpNumElements;
    if (extendedParamTree.hasVector("numElements")) {
      tmpNumElements = extendedParamTree.getVector("numElements", 1u, dim);
      assert(tmpNumElements.size() >= dim && "Given vector too short!");
    } else if (extendedParamTree.hasKey("numElements")) {
        const unsigned int numElement = extendedParamTree.get("numElements", 1u);
        tmpNumElements = std::vector< unsigned int >(dim, numElement);
    } else {
      std::cout << "\n" << Dune::Stuff::Common::highlightString("WARNING in " + id() + ":", Dune::Stuff::Common::Colors::brown)
                << " neither vector nor key 'numElements' given, defaulting to 1!" << std::flush;
      tmpNumElements = std::vector< unsigned int >(dim, 1u);
    }
    // check and save
    CoordinateType lowerLeft;
    CoordinateType upperRight;
    Dune::array< unsigned int, dim > numElements;
    for (unsigned int d = 0; d < dim; ++d) {
      assert(lowerLefts[d] < upperRights[d]
             && "Given 'upperRight' hast to be elementwise larger than given 'lowerLeft'!");
      lowerLeft[d] = lowerLefts[d];
      upperRight[d] = upperRights[d];
      assert(tmpNumElements[d] > 0 && "Given 'numElements' has to be elementwise positive!");
      numElements[d] = tmpNumElements[d];
    }
    return GenericCube(lowerLeft, upperRight, numElements);
  } // static ThisType createFromParamTree(const Dune::ParameterTree& paramTree, const std::string subName = id())

  ThisType& operator=(ThisType& other)
  {
    if (this != &other) {
      lowerLeft_ = other.lowerLeft();
      upperRight_ = other.upperRight();
      grid_ = other.grid();
    }
    return this;
  } // ThisType& operator=(ThisType& other)

  //! access to shared ptr
  virtual Dune::shared_ptr< GridType > grid()
  {
    return grid_;
  }

  virtual const Dune::shared_ptr< const GridType > grid() const
  {
    return grid_;
  }

  const CoordinateType& lowerLeft() const
  {
    return lowerLeft_;
  }

  const CoordinateType& upperRight() const
  {
    return upperRight_;
  }

  /**
   *  \brief      Visualizes the grid using Dune::VTKWriter.
   *  \param[in]  filename
   **/

private:
  void buildGrid(const Dune::array< unsigned int, dim >& numElements)
  {
    dune_static_assert(variant >= 1 && variant <= 2, "only variant 1 and 2 are valid");
    switch (variant) {
      case 1:
        grid_ = Dune::StructuredGridFactory< GridType >::createCubeGrid(lowerLeft_, upperRight_, numElements);
        break;
      case 2:
    default:
        grid_ = Dune::StructuredGridFactory< GridType >::createSimplexGrid(lowerLeft_, upperRight_, numElements);
        break;
    }
  } // void buildGrid(const CoordinateType& lowerLeft, const CoordinateType& upperRight)

  CoordinateType lowerLeft_;
  CoordinateType upperRight_;
  Dune::shared_ptr< GridType > grid_;
}; // class GenericCube

template< typename GridType >
struct ElementVariant {
  static const int id = 2;
};

template< int dim >
struct ElementVariant< Dune::YaspGrid< dim > > {
  static const int id = 1;
};

template< int dim >
struct ElementVariant< Dune::SGrid< dim, dim > > {
  static const int id = 1;
};

#if HAVE_ALUGRID
template< int dim >
struct ElementVariant< Dune::ALUCubeGrid< dim, dim > > {
  static const int id = 1;
};
#endif // HAVE_ALUGRID

// default implementation of a cube for any grid
// tested for
// dim = 2
//  ALUGRID_SIMPLEX, variant 2
//  ALUGRID_CONFORM, variant 2
// dim = 3
//  ALUGRID_SIMPLEX, variant 2
#if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridType = Dune::GridSelector::GridType >
#else // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridType = Dune::SGrid< 2, 2 > >
#endif // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
class Cube
  : public GenericCube< GridType, ElementVariant<GridType>::id >
{
public:
  typedef GenericCube< GridType, ElementVariant<GridType>::id > BaseType;

  typedef Cube< GridType > ThisType;

  typedef typename BaseType::CoordinateType CoordinateType;

  Cube(const double _lowerLeft = 0.0, const double _upperRight = 1.0, const unsigned int _numElements = 1)
    : BaseType(_lowerLeft, _upperRight, _numElements)
  {}

  Cube(const CoordinateType& _lowerLeft, const CoordinateType& _upperRight, const unsigned int _numElements = 1)
    : BaseType(_lowerLeft, _upperRight, _numElements)
  {}

  template< class ContainerType  >
  Cube(const CoordinateType& lowerLeft, const CoordinateType& upperRight,
       const ContainerType numElements
        = boost::assign::list_of< typename ContainerType::value_type>().repeat(GridType::dimensionworld,
                                                                               typename ContainerType::value_type(1u)))
    : BaseType(lowerLeft, upperRight, numElements)
  {}

  Cube(BaseType& other)
    : BaseType(other)
  {}

  static ThisType createFromParamTree(const Dune::ParameterTree& paramTree, const std::string subName = BaseType::id())
  {
    BaseType base = BaseType::createFromParamTree(paramTree, subName);
    return ThisType(base);
  }
}; // class Cube

} // namespace Provider
} // namespace Grid
} // namespace Stuff
} // namespace Dune

#endif // HAVE_DUNE_GRID

#endif // DUNE_STUFF_GRID_PROVIDER_CUBE_HH
<commit_msg>[grid.provider.cube] disabled warnings from core modules<commit_after>#ifndef DUNE_STUFF_GRID_PROVIDER_CUBE_HH
#define DUNE_STUFF_GRID_PROVIDER_CUBE_HH

#include <dune/stuff/common/header/disable_warnings.hh>
  #ifdef HAVE_CMAKE_CONFIG
    #include "cmake_config.h"
  #elif defined (HAVE_CONFIG_H)
    #include <config.h>
  #endif // ifdef HAVE_CMAKE_CONFIG
#include <dune/stuff/common/header/reenable_warnings.hh>

#if HAVE_DUNE_GRID

#include <dune/stuff/common/header/disable_warnings.hh>
  #include <sstream>
  #include <type_traits>
  #include <boost/assign/list_of.hpp>

  #include <dune/common/parametertree.hh>
  #include <dune/common/shared_ptr.hh>
  #include <dune/common/exceptions.hh>
  #include <dune/common/fvector.hh>
  #include <dune/common/static_assert.hh>

  #include <dune/grid/utility/structuredgridfactory.hh>
  #include <dune/grid/yaspgrid.hh>
  #ifdef HAVE_ALUGRID
    #include <dune/grid/alugrid.hh>
  #endif
  #include <dune/grid/sgrid.hh>
#include <dune/stuff/common/header/reenable_warnings.hh>

#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/color.hh>

#include "interface.hh"

namespace Dune {
namespace Stuff {
namespace Grid {
namespace Provider {

/**
 *  \brief  Creates a grid of a cube in various dimensions.
 *
 *          Default implementation using the Dune::StructuredGridFactory to create a grid of a cube in 1, 2 or 3
 *          dimensions. Tested with
 *

 \c YASPGRID, \c variant 1, dim = 1, 2, 3,
 *
 \c SGRID, \c variant 1, dim = 1, 2, 3,
 *
 \c ALUGRID_SIMPLEX, \c variant 2, dim = 2, 3,
 *
 \c ALUGRID_CONFORM, \c variant 2, dim = 2, 2 and
 *
 \c ALUGRID_CUBE, \c variant 1, dim = 2, 3.

 *  \tparam GridImp
 *          Type of the underlying grid.
 *  \tparam variant
 *          Type of the codim 0 elements:
 *

\c 1: cubes
 *
2: simplices

 **/
template< typename GridImp, int variant >
class GenericCube
  : public Interface< GridImp >
{
public:
  //! Type of the provided grid.
  typedef GridImp GridType;

  typedef Interface< GridType > BaseType;

  typedef GenericCube< GridType, variant > ThisType;

private:
  typedef typename GridType::LeafGridView GridViewType;

public:
  static const unsigned int dim = BaseType::dim;

  //! Type of the grids coordinates.
  typedef typename GridType::ctype ctype;
  typedef Dune::FieldVector< ctype, dim > CoordinateType;

  //! Unique identifier: \c stuff.grid.provider.cube
  static const std::string id()
  {
    return BaseType::id() + ".cube";
  }

  /**
   *  \brief      Creates a cube.
   *  \param[in]  lowerLeft
   *              A double that is used as a lower left corner in each dimension.
   *  \param[in]  upperRight
   *              A double that is used as a upper right corner in each dimension.
   *  \param[in]  numElements (optional)
   *              number of elements.
   **/
  GenericCube(const double _lowerLeft = 0.0, const double _upperRight = 1.0, const unsigned int numElements = 1u)
    : lowerLeft_(_lowerLeft),
      upperRight_(_upperRight)
  {
    Dune::array< unsigned int, dim > tmpNumElements;
    std::fill(tmpNumElements.begin(), tmpNumElements.end(), numElements);
    buildGrid(tmpNumElements);
  }

  /**
   *  \brief      Creates a cube.
   *  \param[in]  lowerLeft
   *              A vector that is used as a lower left corner.
   *  \param[in]  upperRight
   *              A vector that is used as a upper right corner.
   *  \param[in]  numElements (optional)
   *              number of elements.
   **/
  GenericCube(const CoordinateType& _lowerLeft, const CoordinateType& _upperRight, const unsigned int numElements = 1u)
    : lowerLeft_(_lowerLeft),
      upperRight_(_upperRight)
  {
    Dune::array< unsigned int, dim > tmpNumElements;
    std::fill(tmpNumElements.begin(), tmpNumElements.end(), numElements);
    buildGrid(tmpNumElements);
  }

  /**
    \brief      Creates a cube. This signature allows to prescribe anisotopic refinement
    \param[in]  lowerLeft
                A double that is used as a lower left corner in each dimension.
    \param[in]  upperRight
                A double that is used as a upper right corner in each dimension.
    \param[in]  numElements
                number of elements in each dimension.
                can contain 0 to dim elements (missing dimension are initialized to 1)
    \tparam Coord anything that CoordinateType allows to copy construct from
    \tparam ContainerType some sequence type that functions with std::begin/end
    \tparam T an unsigned integral Type
    **/
  template< class ContainerType  >
  GenericCube(const CoordinateType& _lowerLeft, const CoordinateType& _upperRight,
              const ContainerType numElements
                = boost::assign::list_of< typename ContainerType::value_type>().repeat(dim,
                                                                                typename ContainerType::value_type(1u)))
    : lowerLeft_(_lowerLeft),
      upperRight_(_upperRight)
  {
    Dune::array< unsigned int, dim > tmpNumElements;
    static_assert(std::is_unsigned< typename ContainerType::value_type >::value
                  && std::is_integral< typename ContainerType::value_type >::value,
                  "only unsigned integral number of elements per dimension allowed");
    //base init in case input is shorter
    std::fill(tmpNumElements.begin(), tmpNumElements.end(), 1u);
    std::copy(numElements.begin(), numElements.end(), tmpNumElements.begin());
    buildGrid(tmpNumElements);
  }

  GenericCube(ThisType& other)
    : lowerLeft_(other.lowerLeft_)
    , upperRight_(other.upperRight_)
    , grid_(other.grid_)
  {}

  GenericCube(const ThisType& other)
    : lowerLeft_(other.lowerLeft_)
    , upperRight_(other.upperRight_)
    , grid_(other.grid_)
  {}

  /**
   *  \brief      Creates a cube.
   *  \param[in]  paramTree
   *              A Dune::ParameterTree containing
   *

 the following keys directly or
   *
 a subtree named Cube::id, containing the following keys. If a subtree is present, it is always selected. Also it is solely selceted, so that all keys in the supertree are ignored.

   *              The actual keys are:
   *

 \c lowerLeft: \a double or a vector that is used as lower left corners.
   *
 \c upperRight: \a double or a vector that is used as upper right corners.
   *
 \c numElements: \a int or vector to denote the number of elements.
   *

   **/
  static ThisType createFromParamTree(const Dune::ParameterTree& paramTree, const std::string subName = id())
  {
    // get correct paramTree
    Dune::Stuff::Common::ParameterTreeX extendedParamTree;
    if (paramTree.hasSub(subName))
      extendedParamTree = paramTree.sub(subName);
    else
      extendedParamTree = paramTree;
    // get lower left
    std::vector< ctype > lowerLefts;
    if (extendedParamTree.hasVector("lowerLeft")) {
      lowerLefts = extendedParamTree.getVector("lowerLeft", ctype(0), dim);
      assert(lowerLefts.size() >= dim && "Given vector too short!");
    } else if (extendedParamTree.hasKey("lowerLeft")) {
        const ctype lowerLeft = extendedParamTree.get("lowerLeft", ctype(0));
        lowerLefts = std::vector< ctype >(dim, lowerLeft);
    } else {
      std::cout << "\n" << Dune::Stuff::Common::highlightString("WARNING in " + id() + ":", Dune::Stuff::Common::Colors::brown)
                << " neither vector nor key 'lowerLeft' given, defaulting to 0.0!" << std::flush;
      lowerLefts = std::vector< ctype >(dim, ctype(0));
    }
    // get upper right
    std::vector< ctype > upperRights;
    if (extendedParamTree.hasVector("upperRight")) {
      upperRights = extendedParamTree.getVector("upperRight", ctype(1), dim);
      assert(upperRights.size() >= dim && "Given vector too short!");
    } else if (extendedParamTree.hasKey("upperRight")) {
        const ctype upperRight = extendedParamTree.get("upperRight", ctype(1));
        upperRights = std::vector< ctype >(dim, upperRight);
    } else {
      std::cout << "\n" << Dune::Stuff::Common::highlightString("WARNING in " + id() + ":", Dune::Stuff::Common::Colors::brown)
                << " neither vector nor key 'upperRight' given, defaulting to 1.0!" << std::flush;
      upperRights = std::vector< ctype >(dim, ctype(1));
    }
    // get number of elements
    std::vector< unsigned int > tmpNumElements;
    if (extendedParamTree.hasVector("numElements")) {
      tmpNumElements = extendedParamTree.getVector("numElements", 1u, dim);
      assert(tmpNumElements.size() >= dim && "Given vector too short!");
    } else if (extendedParamTree.hasKey("numElements")) {
        const unsigned int numElement = extendedParamTree.get("numElements", 1u);
        tmpNumElements = std::vector< unsigned int >(dim, numElement);
    } else {
      std::cout << "\n" << Dune::Stuff::Common::highlightString("WARNING in " + id() + ":", Dune::Stuff::Common::Colors::brown)
                << " neither vector nor key 'numElements' given, defaulting to 1!" << std::flush;
      tmpNumElements = std::vector< unsigned int >(dim, 1u);
    }
    // check and save
    CoordinateType lowerLeft;
    CoordinateType upperRight;
    Dune::array< unsigned int, dim > numElements;
    for (unsigned int d = 0; d < dim; ++d) {
      assert(lowerLefts[d] < upperRights[d]
             && "Given 'upperRight' hast to be elementwise larger than given 'lowerLeft'!");
      lowerLeft[d] = lowerLefts[d];
      upperRight[d] = upperRights[d];
      assert(tmpNumElements[d] > 0 && "Given 'numElements' has to be elementwise positive!");
      numElements[d] = tmpNumElements[d];
    }
    return GenericCube(lowerLeft, upperRight, numElements);
  } // static ThisType createFromParamTree(const Dune::ParameterTree& paramTree, const std::string subName = id())

  ThisType& operator=(ThisType& other)
  {
    if (this != &other) {
      lowerLeft_ = other.lowerLeft();
      upperRight_ = other.upperRight();
      grid_ = other.grid();
    }
    return this;
  } // ThisType& operator=(ThisType& other)

  //! access to shared ptr
  virtual Dune::shared_ptr< GridType > grid()
  {
    return grid_;
  }

  virtual const Dune::shared_ptr< const GridType > grid() const
  {
    return grid_;
  }

  const CoordinateType& lowerLeft() const
  {
    return lowerLeft_;
  }

  const CoordinateType& upperRight() const
  {
    return upperRight_;
  }

  /**
   *  \brief      Visualizes the grid using Dune::VTKWriter.
   *  \param[in]  filename
   **/

private:
  void buildGrid(const Dune::array< unsigned int, dim >& numElements)
  {
    dune_static_assert(variant >= 1 && variant <= 2, "only variant 1 and 2 are valid");
    switch (variant) {
      case 1:
        grid_ = Dune::StructuredGridFactory< GridType >::createCubeGrid(lowerLeft_, upperRight_, numElements);
        break;
      case 2:
    default:
        grid_ = Dune::StructuredGridFactory< GridType >::createSimplexGrid(lowerLeft_, upperRight_, numElements);
        break;
    }
  } // void buildGrid(const CoordinateType& lowerLeft, const CoordinateType& upperRight)

  CoordinateType lowerLeft_;
  CoordinateType upperRight_;
  Dune::shared_ptr< GridType > grid_;
}; // class GenericCube

template< typename GridType >
struct ElementVariant {
  static const int id = 2;
};

template< int dim >
struct ElementVariant< Dune::YaspGrid< dim > > {
  static const int id = 1;
};

template< int dim >
struct ElementVariant< Dune::SGrid< dim, dim > > {
  static const int id = 1;
};

#if HAVE_ALUGRID
template< int dim >
struct ElementVariant< Dune::ALUCubeGrid< dim, dim > > {
  static const int id = 1;
};
#endif // HAVE_ALUGRID

// default implementation of a cube for any grid
// tested for
// dim = 2
//  ALUGRID_SIMPLEX, variant 2
//  ALUGRID_CONFORM, variant 2
// dim = 3
//  ALUGRID_SIMPLEX, variant 2
#if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridType = Dune::GridSelector::GridType >
#else // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridType = Dune::SGrid< 2, 2 > >
#endif // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
class Cube
  : public GenericCube< GridType, ElementVariant<GridType>::id >
{
public:
  typedef GenericCube< GridType, ElementVariant<GridType>::id > BaseType;

  typedef Cube< GridType > ThisType;

  typedef typename BaseType::CoordinateType CoordinateType;

  Cube(const double _lowerLeft = 0.0, const double _upperRight = 1.0, const unsigned int _numElements = 1)
    : BaseType(_lowerLeft, _upperRight, _numElements)
  {}

  Cube(const CoordinateType& _lowerLeft, const CoordinateType& _upperRight, const unsigned int _numElements = 1)
    : BaseType(_lowerLeft, _upperRight, _numElements)
  {}

  template< class ContainerType  >
  Cube(const CoordinateType& lowerLeft, const CoordinateType& upperRight,
       const ContainerType numElements
        = boost::assign::list_of< typename ContainerType::value_type>().repeat(GridType::dimensionworld,
                                                                               typename ContainerType::value_type(1u)))
    : BaseType(lowerLeft, upperRight, numElements)
  {}

  Cube(BaseType& other)
    : BaseType(other)
  {}

  static ThisType createFromParamTree(const Dune::ParameterTree& paramTree, const std::string subName = BaseType::id())
  {
    BaseType base = BaseType::createFromParamTree(paramTree, subName);
    return ThisType(base);
  }
}; // class Cube

} // namespace Provider
} // namespace Grid
} // namespace Stuff
} // namespace Dune

#endif // HAVE_DUNE_GRID

#endif // DUNE_STUFF_GRID_PROVIDER_CUBE_HH
<|endoftext|>


<commit_before>#ifndef DUNE_STUFF_GRID_PROVIDER_CUBE_HH
#define DUNE_STUFF_GRID_PROVIDER_CUBE_HH

// system
#include <sstream>

// dune-common
#include <dune/common/parametertree.hh>
#include <dune/common/shared_ptr.hh>
#include <dune/common/exceptions.hh>
#include <dune/common/fvector.hh>

// dune-grid
#include <dune/grid/utility/structuredgridfactory.hh>
#include <dune/grid/yaspgrid.hh>
#include <dune/grid/alugrid.hh>
#include <dune/grid/sgrid.hh>
#include <dune/grid/common/mcmgmapper.hh>
#include <dune/grid/io/file/vtk/vtkwriter.hh>

namespace Dune
{

namespace Stuff
{

namespace Grid
{

namespace Provider
{

/**
 *  \brief  Creates a grid of a cube in various dimensions.
 *
 *          Default implementation using the Dune::StructuredGridFactory to create a grid of a cube in 1, 2 or 3
 *          dimensions. Tested with
 *

 \c YASPGRID, \c variant 1, dim = 1, 2, 3,
 *
 \c SGRID, \c variant 1, dim = 1, 2, 3,
 *
 \c ALUGRID_SIMPLEX, \c variant 2, dim = 2, 3,
 *
 \c ALUGRID_CONFORM, \c variant 2, dim = 2, 2 and
 *
 \c ALUGRID_CUBE, \c variant 1, dim = 2, 3.

 *  \tparam GridImp
 *          Type of the underlying grid.
 *  \tparam variant
 *          Type of the codim 0 elements:
 *

\c 1: cubes
 *
2: simplices

 **/
template< typename GridImp, int variant >
class GenericCube
{
public:
  //! Type of the provided grid.
  typedef GridImp GridType;

  //! Dimension of the provided grid.
  static const unsigned int dim = GridType::dimension;

  //! Type of the grids coordinates.
  typedef Dune::FieldVector< typename GridType::ctype, dim > CoordinateType;

  //! Unique identifier: \c stuff.grid.provider.cube
  static const std::string id;

  /**
   *  \brief      Creates a cube.
   *  \param[in]  paramTree
   *              A Dune::ParameterTree containing
   *

 the following keys directly or
   *
 a subtree named Cube::id, containing the following keys. If a subtree is present, it is always selected. Also it is solely selceted, so that all keys in the supertree are ignored.

   *              The actual keys are:
   *

 \c lowerLeft: \a double that is used as a lower left corner in each dimension.
   *
 \c upperRight: \a double that is used as an upper right corner in each dimension.
   *
 \c numElements.D \a int to denote the number of elements in direction of dimension D (has to be given for each dimension seperately).
   *
 \c level: \a int level of refinement. If given, overrides numElements and creates \f$ 2^level \f$ elements per dimension.
   *

   **/
  GenericCube(const Dune::ParameterTree paramTree)
    : lowerLeft_(0.0),
      upperRight_(1.0)
  {
    // select subtree (if necessary)
    Dune::ParameterTree paramTree_ = paramTree;
    if (paramTree.hasSub(id))
      paramTree_ = paramTree.sub(id);
    // get outer bounds
    const double lowerLeft = paramTree_.get("lowerLeft", 0.0);
    const double upperRight = paramTree_.get("upperRight", 1.0);
    assert(lowerLeft < upperRight);
    lowerLeft_ = lowerLeft;
    upperRight_ = upperRight;
    // get number of elements per dim
    if (paramTree.hasKey("level"))
      std::fill(numElements_.begin(), numElements_.end(), std::pow(2, paramTree_.get("level", 1)));
    else {
      for (unsigned int d = 0; d < dim; ++d) {
        std::stringstream s;
        s << "numElements." << d;
        numElements_[d] = paramTree.get(s.str(), 1);
      }
    }
    buildGrid();
  } // Cube(const Dune::ParameterTree& paramTree)

  /**
   *  \brief      Creates a cube.
   *  \param[in]  lowerLeft
   *              A vector that is used as a lower left corner.
   *  \param[in]  upperRight
   *              A vector that is used as a upper right corner.
   *  \param[in]  level (optional)
   *              Level of refinement (see constructor for details).
   **/
  GenericCube(const CoordinateType& lowerLeft, const CoordinateType& upperRight, const int level = 1)
    : lowerLeft_(lowerLeft),
      upperRight_(upperRight)
  {
    std::fill(numElements_.begin(), numElements_.end(), std::pow(2, level));
    buildGrid();
  }

  /**
   *  \brief      Creates a cube.
   *  \param[in]  lowerLeft
   *              A double that is used as a lower left corner in each dimension.
   *  \param[in]  upperRight
   *              A double that is used as a upper right corner in each dimension.
   *  \param[in]  level (optional)
   *              Level of refinement (see constructor for details).
   **/
  GenericCube(const double lowerLeft, const double upperRight, const int level = 1)
    : lowerLeft_(lowerLeft),
      upperRight_(upperRight)
  {
    std::fill(numElements_.begin(), numElements_.end(), std::pow(2, level));
    buildGrid();
  }

  /**
   *  \brief  Provides access to the created grid.
   *  \return Reference to the grid.
   **/
  GridType& grid()
  {
    return *grid_;
  }

  /**
   *  \brief  Provides const access to the created grid.
   *  \return Reference to the grid.
   **/
  const GridType& grid() const
  {
    return *grid_;
  }

  const CoordinateType& lowerLeft() const
  {
    return lowerLeft_;
  }

  const CoordinateType& upperRight() const
  {
    return upperRight_;
  }

private:
  template< int dim >
  struct P0Layout
  {
    bool DUNE_DEPRECATED_MSG("geometries should be passed by value") contains(Dune::GeometryType& geometry)
    {
      return geometry.dim() == dim;
    }
    bool contains(const Dune::GeometryType geometry)
    {
      return geometry.dim() == dim;
    }
  }; // layout class for codim 0 mapper

public:
  /**
   *  \brief      Visualizes the grid using Dune::VTKWriter.
   *  \param[in]  filename
   **/
  void visualize(const std::string filename = id + ".grid") const
  {
    // grid view
    typedef typename GridType::LeafGridView GridView;
    GridView gridView = grid().leafView();
    // mapper
    Dune::LeafMultipleCodimMultipleGeomTypeMapper< GridType, P0Layout > mapper(grid());
    std::vector< double > data(mapper.size());
    // walk the grid
    typedef typename GridView::template Codim<0>::Iterator ElementIterator;
    typedef typename GridView::template Codim<0>::Entity ElementType;
    typedef typename ElementType::LeafIntersectionIterator FacetIteratorType;
    for (ElementIterator it = gridView.template begin<0>(); it != gridView.template end<0>(); ++it) {
      ElementType& element = *it;
      data[mapper.map(element)] = 0.0;
      int numberOfBoundarySegments = 0;
      bool isOnBoundary = false;
      // walk the intersections
      for (FacetIteratorType facet = element.ileafbegin();
           facet != element.ileafend();
           ++facet) {
        if (!facet->neighbor() && facet->boundary()){
          isOnBoundary = true;
          numberOfBoundarySegments += 1;
          data[mapper.map(element)] += double(facet->boundaryId());
        }
      } // walk the intersections
      if (isOnBoundary) {
        data[mapper.map(element)] /= double(numberOfBoundarySegments);
      }
    } // walk the grid
    // write to vtk
    Dune::VTKWriter< GridView > vtkwriter(gridView);
    vtkwriter.addCellData(data, "boundaryId");
    vtkwriter.write(filename, Dune::VTK::ascii);
  } // void visualize(const std::string filename = id + ".grid") const

private:
  void buildGrid()
  {
    switch (variant) {
      case 1:
        grid_ = Dune::StructuredGridFactory< GridType >::createCubeGrid(lowerLeft_, upperRight_, numElements_);
        break;
      case 2:
        grid_ = Dune::StructuredGridFactory< GridType >::createSimplexGrid(lowerLeft_, upperRight_, numElements_);
        break;
      default:
        DUNE_THROW(Dune::NotImplemented, "Variant " << variant << " not valid (only 1 and 2 are).");
    }
    return;
  } // void buildGrid(const CoordinateType& lowerLeft, const CoordinateType& upperRight)

  CoordinateType lowerLeft_;
  CoordinateType upperRight_;
  Dune::array< unsigned int, dim > numElements_;
  Dune::shared_ptr< GridType > grid_;
}; // class GenericCube

template< typename GridImp, int variant >
const std::string GenericCube< GridImp, variant >::id = "stuff.grid.provider.cube";

template< typename GridType >
struct ElementVariant {
  static const int id = 2;
};

template< int dim >
struct ElementVariant< Dune::YaspGrid< dim > > {
  static const int id = 1;
};

template< int dim >
struct ElementVariant< Dune::SGrid< dim, dim > > {
  static const int id = 1;
};

#ifdef HAVE_ALUGRID
template< int dim >
struct ElementVariant< Dune::ALUCubeGrid< dim, dim > > {
  static const int id = 1;
};
#endif

// default implementation of a cube for any grid
// tested for
// dim = 2
//  ALUGRID_SIMPLEX, variant 2
//  ALUGRID_CONFORM, variant 2
// dim = 3
//  ALUGRID_SIMPLEX, variant 2
template< typename GridType >
class Cube
  : public GenericCube< GridType, ElementVariant<GridType>::id >
{
private:
  typedef GenericCube< GridType, ElementVariant<GridType>::id > BaseType;

public:
  typedef typename BaseType::CoordinateType CoordinateType;

  Cube(const Dune::ParameterTree& paramTree)
    : BaseType(paramTree)
  {}

  Cube(const CoordinateType& lowerLeft, const CoordinateType& upperRight, const int level = 1)
    : BaseType(lowerLeft, upperRight, level)
  {}

  Cube(const double lowerLeft, const double upperRight, const int level = 1)
    : BaseType(lowerLeft, upperRight, level)
  {}
}; // class Cube

template< typename GridType >
class UnitCube
  : public Cube< GridType >
{
private:
  typedef Cube< GridType > BaseType;

public:
  UnitCube(const Dune::ParameterTree& paramTree)
    : BaseType(0.0, 1.0, paramTree.get("level", 1))
  {}

  UnitCube(const int level = 1)
    : BaseType(0.0, 1.0, level)
  {}
}; // class UnitCube

} // namespace Provider

} // namespace Grid

} // namespace Stuff

} // namespace Dune

#endif // DUNE_STUFF_GRID_PROVIDER_CUBE_HH
<commit_msg>[grid.provider] adds a new a new ctor signature for anisotropic gird gen.<commit_after>#ifndef DUNE_STUFF_GRID_PROVIDER_CUBE_HH
#define DUNE_STUFF_GRID_PROVIDER_CUBE_HH

// system
#include <sstream>
#include <boost/assign/list_of.hpp>

// dune-common
#include <dune/common/parametertree.hh>
#include <dune/common/shared_ptr.hh>
#include <dune/common/exceptions.hh>
#include <dune/common/fvector.hh>

// dune-grid
#include <dune/grid/utility/structuredgridfactory.hh>
#include <dune/grid/yaspgrid.hh>
#include <dune/grid/alugrid.hh>
#include <dune/grid/sgrid.hh>
#include <dune/grid/common/mcmgmapper.hh>
#include <dune/grid/io/file/vtk/vtkwriter.hh>

namespace Dune {
namespace Stuff {
namespace Grid {
namespace Provider {

/**
 *  \brief  Creates a grid of a cube in various dimensions.
 *
 *          Default implementation using the Dune::StructuredGridFactory to create a grid of a cube in 1, 2 or 3
 *          dimensions. Tested with
 *

 \c YASPGRID, \c variant 1, dim = 1, 2, 3,
 *
 \c SGRID, \c variant 1, dim = 1, 2, 3,
 *
 \c ALUGRID_SIMPLEX, \c variant 2, dim = 2, 3,
 *
 \c ALUGRID_CONFORM, \c variant 2, dim = 2, 2 and
 *
 \c ALUGRID_CUBE, \c variant 1, dim = 2, 3.

 *  \tparam GridImp
 *          Type of the underlying grid.
 *  \tparam variant
 *          Type of the codim 0 elements:
 *

\c 1: cubes
 *
2: simplices

 **/
template< typename GridImp, int variant >
class GenericCube
{
public:
  //! Type of the provided grid.
  typedef GridImp GridType;

  //! Dimension of the provided grid.
  static const unsigned int dim = GridType::dimension;

  //! Type of the grids coordinates.
  typedef Dune::FieldVector< typename GridType::ctype, dim > CoordinateType;

  //! Unique identifier: \c stuff.grid.provider.cube
  static const std::string id;

  /**
   *  \brief      Creates a cube.
   *  \param[in]  paramTree
   *              A Dune::ParameterTree containing
   *

 the following keys directly or
   *
 a subtree named Cube::id, containing the following keys. If a subtree is present, it is always selected. Also it is solely selceted, so that all keys in the supertree are ignored.

   *              The actual keys are:
   *

 \c lowerLeft: \a double that is used as a lower left corner in each dimension.
   *
 \c upperRight: \a double that is used as an upper right corner in each dimension.
   *
 \c numElements.D \a int to denote the number of elements in direction of dimension D (has to be given for each dimension seperately).
   *
 \c level: \a int level of refinement. If given, overrides numElements and creates \f$ 2^level \f$ elements per dimension.
   *

   **/
  GenericCube(const Dune::ParameterTree paramTree)
    : lowerLeft_(0.0),
      upperRight_(1.0)
  {
    // select subtree (if necessary)
    Dune::ParameterTree paramTree_ = paramTree;
    if (paramTree.hasSub(id))
      paramTree_ = paramTree.sub(id);
    // get outer bounds
    const double lowerLeft = paramTree_.get("lowerLeft", 0.0);
    const double upperRight = paramTree_.get("upperRight", 1.0);
    assert(lowerLeft < upperRight);
    lowerLeft_ = lowerLeft;
    upperRight_ = upperRight;
    // get number of elements per dim
    if (paramTree.hasKey("level"))
      std::fill(std::begin(numElements_), std::end(numElements_), std::pow(2, paramTree.get("level", 1)));
    else {
      for (unsigned int d = 0; d < dim; ++d) {
        std::stringstream s;
        s << "numElements." << d;
        numElements_[d] = paramTree.get(s.str(), 1);
      }
    }
    buildGrid();
  } // Cube(const Dune::ParameterTree& paramTree)

  /**
   *  \brief      Creates a cube.
   *  \param[in]  lowerLeft
   *              A vector that is used as a lower left corner.
   *  \param[in]  upperRight
   *              A vector that is used as a upper right corner.
   *  \param[in]  level (optional)
   *              Level of refinement (see constructor for details).
   **/
  GenericCube(const CoordinateType& lowerLeft, const CoordinateType& upperRight, const int level = 1)
    : lowerLeft_(lowerLeft),
      upperRight_(upperRight)
  {
    std::fill(numElements_.begin(), numElements_.end(), std::pow(2, level));
    buildGrid();
  }

  /**
   *  \brief      Creates a cube.
   *  \param[in]  lowerLeft
   *              A double that is used as a lower left corner in each dimension.
   *  \param[in]  upperRight
   *              A double that is used as a upper right corner in each dimension.
   *  \param[in]  level (optional)
   *              Level of refinement (see constructor for details).
   **/
  GenericCube(const double lowerLeft, const double upperRight, const int level = 1)
    : lowerLeft_(lowerLeft),
      upperRight_(upperRight)
  {
    std::fill(std::begin(numElements_), std::end(numElements_), std::pow(2, level));
    buildGrid();
  }

  /**
    \brief      Creates a cube. This signature allows to prescribe anisotopic refinement
    \param[in]  lowerLeft
                A double that is used as a lower left corner in each dimension.
    \param[in]  upperRight
                A double that is used as a upper right corner in each dimension.
    \param[in]  elements_per_dim number of elements in each dimension.
                can contain 0 to dim elements (missing dimension are initialized to 1)
    \tparam Coord anything that CoordinateType allows to copy construct from
    \tparam ContainerType some sequence type that functions with std::begin/end
    \tparam T an unsigned integral Type
    **/
  template < class Coord, class ContainerType  >
  GenericCube(const Coord lowerLeft, const Coord upperRight,
       const ContainerType elements_per_dim = boost::assign::list_of<typename ContainerType::value_type>().repeat(GridType::dimensionworld,typename ContainerType::value_type(1)) )
    : lowerLeft_(lowerLeft),
      upperRight_(upperRight)
  {
    static_assert(std::is_unsigned<typename ContainerType::value_type>::value
        && std::is_integral<typename ContainerType::value_type>::value,
        "only unsigned integral number of elements per dimension allowed");
    //base init in case input is shorter
    std::fill(std::begin(numElements_), std::end(numElements_), 1);
    std::copy(std::begin(elements_per_dim), std::end(elements_per_dim), std::begin(numElements_));
    buildGrid();
  }

  /**
    \brief  Provides access to the created grid.
    \return Reference to the grid.
    **/
  GridType& grid()
  {
    return *grid_;
  }

  /**
   *  \brief  Provides const access to the created grid.
   *  \return Reference to the grid.
   **/
  const GridType& grid() const
  {
    return *grid_;
  }

  const CoordinateType& lowerLeft() const
  {
    return lowerLeft_;
  }

  const CoordinateType& upperRight() const
  {
    return upperRight_;
  }

private:
  template< int dim >
  struct P0Layout
  {
    bool DUNE_DEPRECATED_MSG("geometries should be passed by value") contains(Dune::GeometryType& geometry)
    {
      return geometry.dim() == dim;
    }
    bool contains(const Dune::GeometryType geometry)
    {
      return geometry.dim() == dim;
    }
  }; // layout class for codim 0 mapper

public:
  /**
   *  \brief      Visualizes the grid using Dune::VTKWriter.
   *  \param[in]  filename
   **/
  void visualize(const std::string filename = id + ".grid") const
  {
    // grid view
    typedef typename GridType::LeafGridView GridView;
    GridView gridView = grid().leafView();
    // mapper
    Dune::LeafMultipleCodimMultipleGeomTypeMapper< GridType, P0Layout > mapper(grid());
    std::vector< double > data(mapper.size());
    // walk the grid
    typedef typename GridView::template Codim<0>::Iterator ElementIterator;
    typedef typename GridView::template Codim<0>::Entity ElementType;
    typedef typename ElementType::LeafIntersectionIterator FacetIteratorType;
    for (ElementIterator it = gridView.template begin<0>(); it != gridView.template end<0>(); ++it) {
      ElementType& element = *it;
      data[mapper.map(element)] = 0.0;
      int numberOfBoundarySegments = 0;
      bool isOnBoundary = false;
      // walk the intersections
      for (FacetIteratorType facet = element.ileafbegin();
           facet != element.ileafend();
           ++facet) {
        if (!facet->neighbor() && facet->boundary()){
          isOnBoundary = true;
          numberOfBoundarySegments += 1;
          data[mapper.map(element)] += double(facet->boundaryId());
        }
      } // walk the intersections
      if (isOnBoundary) {
        data[mapper.map(element)] /= double(numberOfBoundarySegments);
      }
    } // walk the grid
    // write to vtk
    Dune::VTKWriter< GridView > vtkwriter(gridView);
    vtkwriter.addCellData(data, "boundaryId");
    vtkwriter.write(filename, Dune::VTK::ascii);
  } // void visualize(const std::string filename = id + ".grid") const

private:
  void buildGrid()
  {
    switch (variant) {
      case 1:
        grid_ = Dune::StructuredGridFactory< GridType >::createCubeGrid(lowerLeft_, upperRight_, numElements_);
        break;
      case 2:
        grid_ = Dune::StructuredGridFactory< GridType >::createSimplexGrid(lowerLeft_, upperRight_, numElements_);
        break;
      default:
        DUNE_THROW(Dune::NotImplemented, "Variant " << variant << " not valid (only 1 and 2 are).");
    }
    return;
  } // void buildGrid(const CoordinateType& lowerLeft, const CoordinateType& upperRight)

  CoordinateType lowerLeft_;
  CoordinateType upperRight_;
  Dune::array< unsigned int, dim > numElements_;
  Dune::shared_ptr< GridType > grid_;
}; // class GenericCube

template< typename GridImp, int variant >
const std::string GenericCube< GridImp, variant >::id = "stuff.grid.provider.cube";

template< typename GridType >
struct ElementVariant {
  static const int id = 2;
};

template< int dim >
struct ElementVariant< Dune::YaspGrid< dim > > {
  static const int id = 1;
};

template< int dim >
struct ElementVariant< Dune::SGrid< dim, dim > > {
  static const int id = 1;
};

#ifdef HAVE_ALUGRID
template< int dim >
struct ElementVariant< Dune::ALUCubeGrid< dim, dim > > {
  static const int id = 1;
};
#endif

// default implementation of a cube for any grid
// tested for
// dim = 2
//  ALUGRID_SIMPLEX, variant 2
//  ALUGRID_CONFORM, variant 2
// dim = 3
//  ALUGRID_SIMPLEX, variant 2
template< typename GridType >
class Cube
  : public GenericCube< GridType, ElementVariant<GridType>::id >
{
private:
  typedef GenericCube< GridType, ElementVariant<GridType>::id > BaseType;

public:
  typedef typename BaseType::CoordinateType CoordinateType;

  Cube(const Dune::ParameterTree& paramTree)
    : BaseType(paramTree)
  {}

  Cube(const CoordinateType& lowerLeft, const CoordinateType& upperRight, const int level = 1)
    : BaseType(lowerLeft, upperRight, level)
  {}

  Cube(const double lowerLeft, const double upperRight, const int level = 1)
    : BaseType(lowerLeft, upperRight, level)
  {}

  template < class Coord, class ContainerType  >
  Cube(const Coord lowerLeft, const Coord upperRight,
       const ContainerType elements_per_dim = boost::assign::list_of<typename ContainerType::value_type>().repeat(GridType::dimensionworld,typename ContainerType::value_type(1)) )
    : BaseType(lowerLeft, upperRight, elements_per_dim)
  {}
}; // class Cube

template< typename GridType >
class UnitCube
  : public Cube< GridType >
{
private:
  typedef Cube< GridType > BaseType;

public:
  UnitCube(const Dune::ParameterTree& paramTree)
    : BaseType(0.0, 1.0, paramTree.get("level", 1))
  {}

  UnitCube(const int level = 1)
    : BaseType(0.0, 1.0, level)
  {}
}; // class UnitCube

} // namespace Provider
} // namespace Grid
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_GRID_PROVIDER_CUBE_HH
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xtextedt.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 21:32:31 $
 *
 *  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
 *
 ************************************************************************/

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

#include <svtools/xtextedt.hxx>
#include <vcl/svapp.hxx>  // International
#include <unotools/textsearch.hxx>
#ifndef _COM_SUN_STAR_UTIL_SEARCHOPTIONS_HPP_
#include <com/sun/star/util/SearchOptions.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SEARCHFLAGS_HPP_
#include <com/sun/star/util/SearchFlags.hpp>
#endif

using namespace ::com::sun::star;

// -------------------------------------------------------------------------
// class ExtTextEngine
// -------------------------------------------------------------------------
ExtTextEngine::ExtTextEngine() : maGroupChars( String::CreateFromAscii( "(){}[]", 6 ) )
{
}

ExtTextEngine::~ExtTextEngine()
{
}

TextSelection ExtTextEngine::MatchGroup( const TextPaM& rCursor ) const
{
    TextSelection aSel( rCursor );
    USHORT nPos = rCursor.GetIndex();
    ULONG nPara = rCursor.GetPara();
    ULONG nParas = GetParagraphCount();
    if ( ( nPara < nParas ) && ( nPos < GetTextLen( nPara ) ) )
    {
        USHORT nMatchChar = maGroupChars.Search( GetText( rCursor.GetPara() ).GetChar( nPos ) );
        if ( nMatchChar != STRING_NOTFOUND )
        {
            if ( ( nMatchChar % 2 ) == 0 )
            {
                // Vorwaerts suchen...
                sal_Unicode nSC = maGroupChars.GetChar( nMatchChar );
                sal_Unicode nEC = maGroupChars.GetChar( nMatchChar+1 );

                USHORT nCur = nPos+1;
                USHORT nLevel = 1;
                while ( nLevel && ( nPara < nParas ) )
                {
                    XubString aStr = GetText( nPara );
                    while ( nCur < aStr.Len() )
                    {
                        if ( aStr.GetChar( nCur ) == nSC )
                            nLevel++;
                        else if ( aStr.GetChar( nCur ) == nEC )
                        {
                            nLevel--;
                            if ( !nLevel )
                                break;  // while nCur...
                        }
                        nCur++;
                    }

                    if ( nLevel )
                    {
                        nPara++;
                        nCur = 0;
                    }
                }
                if ( nLevel == 0 )  // gefunden
                {
                    aSel.GetStart() = rCursor;
                    aSel.GetEnd() = TextPaM( nPara, nCur+1 );
                }
            }
            else
            {
                // Rueckwaerts suchen...
                xub_Unicode nEC = maGroupChars.GetChar( nMatchChar );
                xub_Unicode nSC = maGroupChars.GetChar( nMatchChar-1 );

                USHORT nCur = rCursor.GetIndex()-1;
                USHORT nLevel = 1;
                while ( nLevel )
                {
                    if ( GetTextLen( nPara ) )
                    {
                        XubString aStr = GetText( nPara );
                        while ( nCur )
                        {
                            if ( aStr.GetChar( nCur ) == nSC )
                            {
                                nLevel--;
                                if ( !nLevel )
                                    break;  // while nCur...
                            }
                            else if ( aStr.GetChar( nCur ) == nEC )
                                nLevel++;

                            nCur--;
                        }
                    }

                    if ( nLevel )
                    {
                        if ( nPara )
                        {
                            nPara--;
                            nCur = GetTextLen( nPara )-1;   // egal ob negativ, weil if Len()
                        }
                        else
                            break;
                    }
                }

                if ( nLevel == 0 )  // gefunden
                {
                    aSel.GetStart() = rCursor;
                    aSel.GetStart().GetIndex()++;   // hinter das Zeichen
                    aSel.GetEnd() = TextPaM( nPara, nCur );
                }
            }
        }
    }
    return aSel;
}

BOOL ExtTextEngine::Search( TextSelection& rSel, const util::SearchOptions& rSearchOptions, BOOL bForward )
{
    TextSelection aSel( rSel );
    aSel.Justify();

    BOOL bSearchInSelection = (0 != (rSearchOptions.searchFlag & util::SearchFlags::REG_NOT_BEGINOFLINE) );

    TextPaM aStartPaM( aSel.GetEnd() );
    if ( aSel.HasRange() && ( ( bSearchInSelection && bForward ) || ( !bSearchInSelection && !bForward ) ) )
    {
        aStartPaM = aSel.GetStart();
    }

    bool bFound = false;
    ULONG nStartNode, nEndNode;

    if ( bSearchInSelection )
        nEndNode = bForward ? aSel.GetEnd().GetPara() : aSel.GetStart().GetPara();
    else
        nEndNode = bForward ? (GetParagraphCount()-1) : 0;

    nStartNode = aStartPaM.GetPara();

    util::SearchOptions aOptions( rSearchOptions );
    aOptions.Locale = Application::GetSettings().GetLocale();
    utl::TextSearch aSearcher( rSearchOptions );

    // ueber die Absaetze iterieren...
    for ( ULONG nNode = nStartNode;
            bForward ?  ( nNode <= nEndNode) : ( nNode >= nEndNode );
            bForward ? nNode++ : nNode-- )
    {
        String aText = GetText( nNode );
        USHORT nStartPos = 0;
        USHORT nEndPos = aText.Len();
        if ( nNode == nStartNode )
        {
            if ( bForward )
                nStartPos = aStartPaM.GetIndex();
            else
                nEndPos = aStartPaM.GetIndex();
        }
        if ( ( nNode == nEndNode ) && bSearchInSelection )
        {
            if ( bForward )
                nEndPos = aSel.GetEnd().GetIndex();
            else
                nStartPos = aSel.GetStart().GetIndex();
        }

        if ( bForward )
            bFound = aSearcher.SearchFrwrd( aText, &nStartPos, &nEndPos );
        else
            bFound = aSearcher.SearchBkwrd( aText, &nEndPos, &nStartPos );

        if ( bFound )
        {
            rSel.GetStart().GetPara() = nNode;
            rSel.GetStart().GetIndex() = nStartPos;
            rSel.GetEnd().GetPara() = nNode;
            rSel.GetEnd().GetIndex() = nEndPos;
            // Ueber den Absatz selektieren?
            // Select over the paragraph?
            // FIXME  This should be max long...
            if( nEndPos == sal::static_int_cast<USHORT>(-1) ) // USHORT for 0 and -1 !
            {
                if ( (rSel.GetEnd().GetPara()+1) < GetParagraphCount() )
                {
                    rSel.GetEnd().GetPara()++;
                    rSel.GetEnd().GetIndex() = 0;
                }
                else
                {
                    rSel.GetEnd().GetIndex() = nStartPos;
                    bFound = false;
                }
            }

            break;
        }

        if ( !bForward && !nNode )  // Bei rueckwaertsuche, wenn nEndNode = 0:
            break;
    }

    return bFound;
}

// -------------------------------------------------------------------------
// class ExtTextView
// -------------------------------------------------------------------------
ExtTextView::ExtTextView( ExtTextEngine* pEng, Window* pWindow )
    : TextView( pEng, pWindow )
{
}

ExtTextView::~ExtTextView()
{
}

BOOL ExtTextView::MatchGroup()
{
    TextSelection aTmpSel( GetSelection() );
    aTmpSel.Justify();
    if ( ( aTmpSel.GetStart().GetPara() != aTmpSel.GetEnd().GetPara() ) ||
         ( ( aTmpSel.GetEnd().GetIndex() - aTmpSel.GetStart().GetIndex() ) > 1 ) )
    {
        return FALSE;
    }

    TextSelection aMatchSel = ((ExtTextEngine*)GetTextEngine())->MatchGroup( aTmpSel.GetStart() );
    if ( aMatchSel.HasRange() )
        SetSelection( aMatchSel );

    return aMatchSel.HasRange() ? TRUE : FALSE;
}

BOOL ExtTextView::Search( const util::SearchOptions& rSearchOptions, BOOL bForward )
{
    BOOL bFound = FALSE;
    TextSelection aSel( GetSelection() );
    if ( ((ExtTextEngine*)GetTextEngine())->Search( aSel, rSearchOptions, bForward ) )
    {
        bFound = TRUE;
        // Erstmal den Anfang des Wortes als Selektion einstellen,
        // damit das ganze Wort in den sichtbaren Bereich kommt.
        SetSelection( aSel.GetStart() );
        ShowCursor( TRUE, FALSE );
    }
    else
    {
        aSel = GetSelection().GetEnd();
    }

    SetSelection( aSel );
    ShowCursor();

    return bFound;
}

USHORT ExtTextView::Replace( const util::SearchOptions& rSearchOptions, BOOL bAll, BOOL bForward )
{
    USHORT nFound = 0;

    if ( !bAll )
    {
        if ( GetSelection().HasRange() )
        {
            InsertText( rSearchOptions.replaceString );
            nFound = 1;
            Search( rSearchOptions, bForward ); // gleich zum naechsten
        }
        else
        {
            if( Search( rSearchOptions, bForward ) )
                nFound = 1;
        }
    }
    else
    {
        // Der Writer ersetzt alle, vom Anfang bis Ende...

        ExtTextEngine* pTextEngine = (ExtTextEngine*)GetTextEngine();

        // HideSelection();
        TextSelection aSel;

        BOOL bSearchInSelection = (0 != (rSearchOptions.searchFlag & util::SearchFlags::REG_NOT_BEGINOFLINE) );
        if ( bSearchInSelection )
        {
            aSel = GetSelection();
            aSel.Justify();
        }

        TextSelection aSearchSel( aSel );

        BOOL bFound = pTextEngine->Search( aSel, rSearchOptions, TRUE );
        if ( bFound )
            pTextEngine->UndoActionStart( XTEXTUNDO_REPLACEALL );
        while ( bFound )
        {
            nFound++;

            TextPaM aNewStart = pTextEngine->ImpInsertText( aSel, rSearchOptions.replaceString );
            aSel = aSearchSel;
            aSel.GetStart() = aNewStart;
            bFound = pTextEngine->Search( aSel, rSearchOptions, TRUE );
        }
        if ( nFound )
        {
            SetSelection( aSel.GetStart() );
            pTextEngine->FormatAndUpdate( this );
            pTextEngine->UndoActionEnd( XTEXTUNDO_REPLACEALL );
        }
    }
    return nFound;
}

BOOL ExtTextView::ImpIndentBlock( BOOL bRight )
{
    BOOL bDone = FALSE;

    TextSelection aSel = GetSelection();
    aSel.Justify();

    HideSelection();
    GetTextEngine()->UndoActionStart( bRight ? XTEXTUNDO_INDENTBLOCK : XTEXTUNDO_UNINDENTBLOCK );

    ULONG nStartPara = aSel.GetStart().GetPara();
    ULONG nEndPara = aSel.GetEnd().GetPara();
    if ( aSel.HasRange() && !aSel.GetEnd().GetIndex() )
    {
        nEndPara--; // den dann nicht einruecken...
    }

    for ( ULONG nPara = nStartPara; nPara <= nEndPara; nPara++ )
    {
        if ( bRight )
        {
            // Tabs hinzufuegen
            GetTextEngine()->ImpInsertText( TextPaM( nPara, 0 ), '\t' );
            bDone = TRUE;
        }
        else
        {
            // Tabs/Blanks entfernen
            String aText = GetTextEngine()->GetText( nPara );
            if ( aText.Len() && (
                    ( aText.GetChar( 0 ) == '\t' ) ||
                    ( aText.GetChar( 0 ) == ' ' ) ) )
            {
                GetTextEngine()->ImpDeleteText( TextSelection( TextPaM( nPara, 0 ), TextPaM( nPara, 1 ) ) );
                bDone = TRUE;
            }
        }
    }

    GetTextEngine()->UndoActionEnd( bRight ? XTEXTUNDO_INDENTBLOCK : XTEXTUNDO_UNINDENTBLOCK );

    BOOL bRange = aSel.HasRange();
    if ( bRight )
    {
        aSel.GetStart().GetIndex()++;
        if ( bRange && ( aSel.GetEnd().GetPara() == nEndPara ) )
            aSel.GetEnd().GetIndex()++;
    }
    else
    {
        if ( aSel.GetStart().GetIndex() )
            aSel.GetStart().GetIndex()--;
        if ( bRange && aSel.GetEnd().GetIndex() )
            aSel.GetEnd().GetIndex()--;
    }

    ImpSetSelection( aSel );
    GetTextEngine()->FormatAndUpdate( this );

    return bDone;
}

BOOL ExtTextView::IndentBlock()
{
    return ImpIndentBlock( TRUE );
}

BOOL ExtTextView::UnindentBlock()
{
    return ImpIndentBlock( FALSE );
}

<commit_msg>INTEGRATION: CWS changefileheader (1.14.246); FILE MERGED 2008/04/01 12:43:32 thb 1.14.246.2: #i85898# Stripping all external header guards 2008/03/31 13:01:52 rt 1.14.246.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: xtextedt.cxx,v $
 * $Revision: 1.15 $
 *
 * 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_svtools.hxx"

#include <svtools/xtextedt.hxx>
#include <vcl/svapp.hxx>  // International
#include <unotools/textsearch.hxx>
#include <com/sun/star/util/SearchOptions.hpp>
#include <com/sun/star/util/SearchFlags.hpp>

using namespace ::com::sun::star;

// -------------------------------------------------------------------------
// class ExtTextEngine
// -------------------------------------------------------------------------
ExtTextEngine::ExtTextEngine() : maGroupChars( String::CreateFromAscii( "(){}[]", 6 ) )
{
}

ExtTextEngine::~ExtTextEngine()
{
}

TextSelection ExtTextEngine::MatchGroup( const TextPaM& rCursor ) const
{
    TextSelection aSel( rCursor );
    USHORT nPos = rCursor.GetIndex();
    ULONG nPara = rCursor.GetPara();
    ULONG nParas = GetParagraphCount();
    if ( ( nPara < nParas ) && ( nPos < GetTextLen( nPara ) ) )
    {
        USHORT nMatchChar = maGroupChars.Search( GetText( rCursor.GetPara() ).GetChar( nPos ) );
        if ( nMatchChar != STRING_NOTFOUND )
        {
            if ( ( nMatchChar % 2 ) == 0 )
            {
                // Vorwaerts suchen...
                sal_Unicode nSC = maGroupChars.GetChar( nMatchChar );
                sal_Unicode nEC = maGroupChars.GetChar( nMatchChar+1 );

                USHORT nCur = nPos+1;
                USHORT nLevel = 1;
                while ( nLevel && ( nPara < nParas ) )
                {
                    XubString aStr = GetText( nPara );
                    while ( nCur < aStr.Len() )
                    {
                        if ( aStr.GetChar( nCur ) == nSC )
                            nLevel++;
                        else if ( aStr.GetChar( nCur ) == nEC )
                        {
                            nLevel--;
                            if ( !nLevel )
                                break;  // while nCur...
                        }
                        nCur++;
                    }

                    if ( nLevel )
                    {
                        nPara++;
                        nCur = 0;
                    }
                }
                if ( nLevel == 0 )  // gefunden
                {
                    aSel.GetStart() = rCursor;
                    aSel.GetEnd() = TextPaM( nPara, nCur+1 );
                }
            }
            else
            {
                // Rueckwaerts suchen...
                xub_Unicode nEC = maGroupChars.GetChar( nMatchChar );
                xub_Unicode nSC = maGroupChars.GetChar( nMatchChar-1 );

                USHORT nCur = rCursor.GetIndex()-1;
                USHORT nLevel = 1;
                while ( nLevel )
                {
                    if ( GetTextLen( nPara ) )
                    {
                        XubString aStr = GetText( nPara );
                        while ( nCur )
                        {
                            if ( aStr.GetChar( nCur ) == nSC )
                            {
                                nLevel--;
                                if ( !nLevel )
                                    break;  // while nCur...
                            }
                            else if ( aStr.GetChar( nCur ) == nEC )
                                nLevel++;

                            nCur--;
                        }
                    }

                    if ( nLevel )
                    {
                        if ( nPara )
                        {
                            nPara--;
                            nCur = GetTextLen( nPara )-1;   // egal ob negativ, weil if Len()
                        }
                        else
                            break;
                    }
                }

                if ( nLevel == 0 )  // gefunden
                {
                    aSel.GetStart() = rCursor;
                    aSel.GetStart().GetIndex()++;   // hinter das Zeichen
                    aSel.GetEnd() = TextPaM( nPara, nCur );
                }
            }
        }
    }
    return aSel;
}

BOOL ExtTextEngine::Search( TextSelection& rSel, const util::SearchOptions& rSearchOptions, BOOL bForward )
{
    TextSelection aSel( rSel );
    aSel.Justify();

    BOOL bSearchInSelection = (0 != (rSearchOptions.searchFlag & util::SearchFlags::REG_NOT_BEGINOFLINE) );

    TextPaM aStartPaM( aSel.GetEnd() );
    if ( aSel.HasRange() && ( ( bSearchInSelection && bForward ) || ( !bSearchInSelection && !bForward ) ) )
    {
        aStartPaM = aSel.GetStart();
    }

    bool bFound = false;
    ULONG nStartNode, nEndNode;

    if ( bSearchInSelection )
        nEndNode = bForward ? aSel.GetEnd().GetPara() : aSel.GetStart().GetPara();
    else
        nEndNode = bForward ? (GetParagraphCount()-1) : 0;

    nStartNode = aStartPaM.GetPara();

    util::SearchOptions aOptions( rSearchOptions );
    aOptions.Locale = Application::GetSettings().GetLocale();
    utl::TextSearch aSearcher( rSearchOptions );

    // ueber die Absaetze iterieren...
    for ( ULONG nNode = nStartNode;
            bForward ?  ( nNode <= nEndNode) : ( nNode >= nEndNode );
            bForward ? nNode++ : nNode-- )
    {
        String aText = GetText( nNode );
        USHORT nStartPos = 0;
        USHORT nEndPos = aText.Len();
        if ( nNode == nStartNode )
        {
            if ( bForward )
                nStartPos = aStartPaM.GetIndex();
            else
                nEndPos = aStartPaM.GetIndex();
        }
        if ( ( nNode == nEndNode ) && bSearchInSelection )
        {
            if ( bForward )
                nEndPos = aSel.GetEnd().GetIndex();
            else
                nStartPos = aSel.GetStart().GetIndex();
        }

        if ( bForward )
            bFound = aSearcher.SearchFrwrd( aText, &nStartPos, &nEndPos );
        else
            bFound = aSearcher.SearchBkwrd( aText, &nEndPos, &nStartPos );

        if ( bFound )
        {
            rSel.GetStart().GetPara() = nNode;
            rSel.GetStart().GetIndex() = nStartPos;
            rSel.GetEnd().GetPara() = nNode;
            rSel.GetEnd().GetIndex() = nEndPos;
            // Ueber den Absatz selektieren?
            // Select over the paragraph?
            // FIXME  This should be max long...
            if( nEndPos == sal::static_int_cast<USHORT>(-1) ) // USHORT for 0 and -1 !
            {
                if ( (rSel.GetEnd().GetPara()+1) < GetParagraphCount() )
                {
                    rSel.GetEnd().GetPara()++;
                    rSel.GetEnd().GetIndex() = 0;
                }
                else
                {
                    rSel.GetEnd().GetIndex() = nStartPos;
                    bFound = false;
                }
            }

            break;
        }

        if ( !bForward && !nNode )  // Bei rueckwaertsuche, wenn nEndNode = 0:
            break;
    }

    return bFound;
}

// -------------------------------------------------------------------------
// class ExtTextView
// -------------------------------------------------------------------------
ExtTextView::ExtTextView( ExtTextEngine* pEng, Window* pWindow )
    : TextView( pEng, pWindow )
{
}

ExtTextView::~ExtTextView()
{
}

BOOL ExtTextView::MatchGroup()
{
    TextSelection aTmpSel( GetSelection() );
    aTmpSel.Justify();
    if ( ( aTmpSel.GetStart().GetPara() != aTmpSel.GetEnd().GetPara() ) ||
         ( ( aTmpSel.GetEnd().GetIndex() - aTmpSel.GetStart().GetIndex() ) > 1 ) )
    {
        return FALSE;
    }

    TextSelection aMatchSel = ((ExtTextEngine*)GetTextEngine())->MatchGroup( aTmpSel.GetStart() );
    if ( aMatchSel.HasRange() )
        SetSelection( aMatchSel );

    return aMatchSel.HasRange() ? TRUE : FALSE;
}

BOOL ExtTextView::Search( const util::SearchOptions& rSearchOptions, BOOL bForward )
{
    BOOL bFound = FALSE;
    TextSelection aSel( GetSelection() );
    if ( ((ExtTextEngine*)GetTextEngine())->Search( aSel, rSearchOptions, bForward ) )
    {
        bFound = TRUE;
        // Erstmal den Anfang des Wortes als Selektion einstellen,
        // damit das ganze Wort in den sichtbaren Bereich kommt.
        SetSelection( aSel.GetStart() );
        ShowCursor( TRUE, FALSE );
    }
    else
    {
        aSel = GetSelection().GetEnd();
    }

    SetSelection( aSel );
    ShowCursor();

    return bFound;
}

USHORT ExtTextView::Replace( const util::SearchOptions& rSearchOptions, BOOL bAll, BOOL bForward )
{
    USHORT nFound = 0;

    if ( !bAll )
    {
        if ( GetSelection().HasRange() )
        {
            InsertText( rSearchOptions.replaceString );
            nFound = 1;
            Search( rSearchOptions, bForward ); // gleich zum naechsten
        }
        else
        {
            if( Search( rSearchOptions, bForward ) )
                nFound = 1;
        }
    }
    else
    {
        // Der Writer ersetzt alle, vom Anfang bis Ende...

        ExtTextEngine* pTextEngine = (ExtTextEngine*)GetTextEngine();

        // HideSelection();
        TextSelection aSel;

        BOOL bSearchInSelection = (0 != (rSearchOptions.searchFlag & util::SearchFlags::REG_NOT_BEGINOFLINE) );
        if ( bSearchInSelection )
        {
            aSel = GetSelection();
            aSel.Justify();
        }

        TextSelection aSearchSel( aSel );

        BOOL bFound = pTextEngine->Search( aSel, rSearchOptions, TRUE );
        if ( bFound )
            pTextEngine->UndoActionStart( XTEXTUNDO_REPLACEALL );
        while ( bFound )
        {
            nFound++;

            TextPaM aNewStart = pTextEngine->ImpInsertText( aSel, rSearchOptions.replaceString );
            aSel = aSearchSel;
            aSel.GetStart() = aNewStart;
            bFound = pTextEngine->Search( aSel, rSearchOptions, TRUE );
        }
        if ( nFound )
        {
            SetSelection( aSel.GetStart() );
            pTextEngine->FormatAndUpdate( this );
            pTextEngine->UndoActionEnd( XTEXTUNDO_REPLACEALL );
        }
    }
    return nFound;
}

BOOL ExtTextView::ImpIndentBlock( BOOL bRight )
{
    BOOL bDone = FALSE;

    TextSelection aSel = GetSelection();
    aSel.Justify();

    HideSelection();
    GetTextEngine()->UndoActionStart( bRight ? XTEXTUNDO_INDENTBLOCK : XTEXTUNDO_UNINDENTBLOCK );

    ULONG nStartPara = aSel.GetStart().GetPara();
    ULONG nEndPara = aSel.GetEnd().GetPara();
    if ( aSel.HasRange() && !aSel.GetEnd().GetIndex() )
    {
        nEndPara--; // den dann nicht einruecken...
    }

    for ( ULONG nPara = nStartPara; nPara <= nEndPara; nPara++ )
    {
        if ( bRight )
        {
            // Tabs hinzufuegen
            GetTextEngine()->ImpInsertText( TextPaM( nPara, 0 ), '\t' );
            bDone = TRUE;
        }
        else
        {
            // Tabs/Blanks entfernen
            String aText = GetTextEngine()->GetText( nPara );
            if ( aText.Len() && (
                    ( aText.GetChar( 0 ) == '\t' ) ||
                    ( aText.GetChar( 0 ) == ' ' ) ) )
            {
                GetTextEngine()->ImpDeleteText( TextSelection( TextPaM( nPara, 0 ), TextPaM( nPara, 1 ) ) );
                bDone = TRUE;
            }
        }
    }

    GetTextEngine()->UndoActionEnd( bRight ? XTEXTUNDO_INDENTBLOCK : XTEXTUNDO_UNINDENTBLOCK );

    BOOL bRange = aSel.HasRange();
    if ( bRight )
    {
        aSel.GetStart().GetIndex()++;
        if ( bRange && ( aSel.GetEnd().GetPara() == nEndPara ) )
            aSel.GetEnd().GetIndex()++;
    }
    else
    {
        if ( aSel.GetStart().GetIndex() )
            aSel.GetStart().GetIndex()--;
        if ( bRange && aSel.GetEnd().GetIndex() )
            aSel.GetEnd().GetIndex()--;
    }

    ImpSetSelection( aSel );
    GetTextEngine()->FormatAndUpdate( this );

    return bDone;
}

BOOL ExtTextView::IndentBlock()
{
    return ImpIndentBlock( TRUE );
}

BOOL ExtTextView::UnindentBlock()
{
    return ImpIndentBlock( FALSE );
}

<|endoftext|>


<commit_before>//
// Copyright (c) 2014-2016 Ian Godin
// All rights reserved.
// Copyrights licensed under the MIT License.
// See the accompanying LICENSE.txt file for terms
//

#include "geometry.h"
#include <tuple>
#include <cmath>

namespace
{

template<int n, typename T>
inline const draw::polyline::point &pt( const T &t )
{
	return std::get<n>( t );
}

}

namespace draw
{

////////////////////////////////////////

size_t circle_precision( dim r )
{
	size_t n = 3;
	dim error = dim( 0 );
	do
	{
		n = n * 2;
		error = r * ( 1.F - std::cos( static_cast<float>( M_PI ) / static_cast<float>( n ) ) );
	} while ( error > dim( 0.01F ) );

	return n;
}

////////////////////////////////////////

void add_quadratic( const polyline::point &p1, const polyline::point &p2, const polyline::point &p3, polyline &line )
{
	using pp = polyline::point;
	typedef std::tuple<pp,pp,pp> curve;
	std::vector<curve> stack;
	stack.reserve( 16 );
	stack.emplace_back( p1, p2, p3 );
	pp c0, c1, c2, c3;

	while ( !stack.empty() )
	{
		curve &c = stack.back();
		pp mid = ( pt<0>( c ) + pt<2>( c ) ) * 0.5F;

		if ( distance_squared( mid, pt<1>( c ) ) <= dim( 0.01F ) )
		{
			line.push_back( pt<2>( c ) );
			stack.pop_back();
		}
		else
		{
			c0 = pt<0>( c );
			c1 = ( c0 + pt<1>( c ) ) * 0.5F;
			c3 = ( pt<1>( c ) + pt<2>( c ) ) * 0.5F;
			c2 = ( c1 + c3 ) * 0.5F;

			c = std::make_tuple( c2, c3, pt<2>( c ) ); // right side
			stack.emplace_back( c0, c1, c2 );
		}
	}
}

////////////////////////////////////////

void add_cubic( const polyline::point &p1, const polyline::point &p2, const polyline::point &p3, const polyline::point &p4, polyline &line )
{
#if 0
	using pp = polyline::point;
	typedef std::tuple<pp,pp,pp,pp> curve;
	std::vector<curve> stack;
	stack.reserve( 16 );
	stack.emplace_back( p1, p2, p3, p4 );
	pp p0, p01, p12, p23, p012, p123, p0123, d, d13, d23;
	bool first = true;

	while ( !stack.empty() )
	{
		curve &c = stack.back();
		p01 = ( pt<0>( c ) + pt<1>( c ) ) * 0.5F;
		p12 = ( pt<1>( c ) + pt<2>( c ) ) * 0.5F;
		p23 = ( pt<2>( c ) + pt<3>( c ) ) * 0.5F;
		p012 = ( p01 + p12 ) * 0.5F;
		p123 = ( p12 + p23 ) * 0.5F;
		p0123 = ( p012 + p123 ) * 0.5F;

		d = pt<0>( c ) - pt<3>( c );
		d13 = pt<1>( c ) - pt<3>( c );
		d23 = pt<2>( c ) - pt<3>( c );

		dim d2 = d13[0] * d[1] - d13[1] * d[0];
		dim d3 = d23[0] * d[1] - d23[1] * d[0];

		if ( ( d2 + d3 ) * ( d2 + d3 ) < 0.1F * ( d[0] * d[0] + d[1] * d[1] ) && !first )
		{
			line.push_back( pt<3>( c ) );
			stack.pop_back();
		}
		else
		{
			p0 = pt<0>( c );
			c = std::make_tuple( p0123, p123, p23, pt<3>( c ) ); // right side
			stack.emplace_back( p0, p01, p012, p0123 );
		}
		first = false;
	}
#endif
}

////////////////////////////////////////

void add_arc( const polyline::point &center, dim radius, float a1, float a2, polyline &line )
{
	using pp = polyline::point;

	size_t n = circle_precision( radius );

	float span = std::abs( std::fmod( ( a1 - a2 + float( M_PI ) ), float( 2.0 * M_PI ) ) - float( M_PI ) );
	n = size_t( std::ceil( n * span / float( 2.0 * M_PI ) ) );

	point bp = base::polar( radius, a1 );
	polyline::point p = polyline::point( bp[0], bp[1], dim(0) ) + center;
	if ( line.empty() || distance_squared( p, line.back() ) > dim( 0.1F ) )
		line.push_back( p );

	for ( size_t i = 1; i <= n; ++i )
	{
		float m = float(i) / float(n);
		float a = a1 * ( 1.0F - m ) + a2 * m;
		bp = base::polar( radius, a );
		line.push_back( polyline::point( bp[0], bp[1], dim(0) ) + center );
	}
}

////////////////////////////////////////

}
<commit_msg>re-enable code after fix for unit type conversion<commit_after>//
// Copyright (c) 2014-2016 Ian Godin
// All rights reserved.
// Copyrights licensed under the MIT License.
// See the accompanying LICENSE.txt file for terms
//

#include "geometry.h"
#include <tuple>
#include <cmath>

namespace
{

template<int n, typename T>
inline const draw::polyline::point &pt( const T &t )
{
	return std::get<n>( t );
}

}

namespace draw
{

////////////////////////////////////////

size_t circle_precision( dim r )
{
	size_t n = 3;
	dim error = dim( 0 );
	do
	{
		n = n * 2;
		error = r * ( 1.F - std::cos( static_cast<float>( M_PI ) / static_cast<float>( n ) ) );
	} while ( error > dim( 0.01F ) );

	return n;
}

////////////////////////////////////////

void add_quadratic( const polyline::point &p1, const polyline::point &p2, const polyline::point &p3, polyline &line )
{
	using pp = polyline::point;
	typedef std::tuple<pp,pp,pp> curve;
	std::vector<curve> stack;
	stack.reserve( 16 );
	stack.emplace_back( p1, p2, p3 );
	pp c0, c1, c2, c3;

	while ( !stack.empty() )
	{
		curve &c = stack.back();
		pp mid = ( pt<0>( c ) + pt<2>( c ) ) * 0.5F;

		if ( distance_squared( mid, pt<1>( c ) ) <= dim( 0.01F ) )
		{
			line.push_back( pt<2>( c ) );
			stack.pop_back();
		}
		else
		{
			c0 = pt<0>( c );
			c1 = ( c0 + pt<1>( c ) ) * 0.5F;
			c3 = ( pt<1>( c ) + pt<2>( c ) ) * 0.5F;
			c2 = ( c1 + c3 ) * 0.5F;

			c = std::make_tuple( c2, c3, pt<2>( c ) ); // right side
			stack.emplace_back( c0, c1, c2 );
		}
	}
}

////////////////////////////////////////

void add_cubic( const polyline::point &p1, const polyline::point &p2, const polyline::point &p3, const polyline::point &p4, polyline &line )
{
	using pp = polyline::point;
	typedef std::tuple<pp,pp,pp,pp> curve;
	std::vector<curve> stack;
	stack.reserve( 16 );
	stack.emplace_back( p1, p2, p3, p4 );
	pp p0, p01, p12, p23, p012, p123, p0123, d, d13, d23;
	bool first = true;

	while ( !stack.empty() )
	{
		curve &c = stack.back();
		p01 = ( pt<0>( c ) + pt<1>( c ) ) * 0.5F;
		p12 = ( pt<1>( c ) + pt<2>( c ) ) * 0.5F;
		p23 = ( pt<2>( c ) + pt<3>( c ) ) * 0.5F;
		p012 = ( p01 + p12 ) * 0.5F;
		p123 = ( p12 + p23 ) * 0.5F;
		p0123 = ( p012 + p123 ) * 0.5F;

		d = pt<0>( c ) - pt<3>( c );
		d13 = pt<1>( c ) - pt<3>( c );
		d23 = pt<2>( c ) - pt<3>( c );

		dim d2 = d13[0] * d[1] - d13[1] * d[0];
		dim d3 = d23[0] * d[1] - d23[1] * d[0];

		if ( ( d2 + d3 ) * ( d2 + d3 ) < 0.1F * ( d[0] * d[0] + d[1] * d[1] ) && !first )
		{
			line.push_back( pt<3>( c ) );
			stack.pop_back();
		}
		else
		{
			p0 = pt<0>( c );
			c = std::make_tuple( p0123, p123, p23, pt<3>( c ) ); // right side
			stack.emplace_back( p0, p01, p012, p0123 );
		}
		first = false;
	}
}

////////////////////////////////////////

void add_arc( const polyline::point &center, dim radius, float a1, float a2, polyline &line )
{
	size_t n = circle_precision( radius );

	float span = std::abs( std::fmod( ( a1 - a2 + float( M_PI ) ), float( 2.0 * M_PI ) ) - float( M_PI ) );
	n = size_t( std::ceil( n * span / float( 2.0 * M_PI ) ) );

	point bp = base::polar( radius, a1 );
	polyline::point p = polyline::point( bp[0], bp[1], dim(0) ) + center;
	if ( line.empty() || distance_squared( p, line.back() ) > dim( 0.1F ) )
		line.push_back( p );

	for ( size_t i = 1; i <= n; ++i )
	{
		float m = float(i) / float(n);
		float a = a1 * ( 1.0F - m ) + a2 * m;
		bp = base::polar( radius, a );
		line.push_back( polyline::point( bp[0], bp[1], dim(0) ) + center );
	}
}

////////////////////////////////////////

}
<|endoftext|>


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

#pragma hdrstop

#ifndef _EDITSH_HXX
#include <editsh.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>      // fuer aNodes
#endif
#ifndef _PAM_HXX
#include <pam.hxx>      // fuer SwPaM
#endif
#ifndef _EDIMP_HXX
#include <edimp.hxx>    // fuer MACROS
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx>   // fuer die UndoIds
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>    // fuer Get-/ChgFmt Set-/GetAttrXXX
#endif

/*************************************
 * harte Formatierung (Attribute)
 *************************************/

void SwEditShell::ResetAttr()
{
    SET_CURR_SHELL( this );
    StartAllAction();
    BOOL bUndoGroup = GetCrsr()->GetNext() != GetCrsr();
    if( bUndoGroup )
        GetDoc()->StartUndo(UNDO_RESETATTR);

        FOREACHPAM_START(this)
            // if ( PCURCRSR->HasMark() )
                GetDoc()->ResetAttr(*PCURCRSR);
        FOREACHPAM_END()

    if( bUndoGroup )
        GetDoc()->EndUndo(UNDO_RESETATTR);
    CallChgLnk();
    EndAllAction();
}

void SwEditShell::GCAttr()
{
//JP 04.02.97: wozu eine Action-Klammerung - ein Formatierung sollte nicht
//              ausgeloest werden, so dass es hier ueberfluessig ist.
//              Sonst Probleme im MouseBut.DownHdl - Bug 35562
//  StartAllAction();
    FOREACHPAM_START(this)
        SwTxtNode *pTxtNode;
        if ( !PCURCRSR->HasMark() )
        {
            if( 0 != (pTxtNode = GetDoc()->GetNodes()[
                                PCURCRSR->GetPoint()->nNode]->GetTxtNode()))
                pTxtNode->GCAttr();
        }
        else
        {
            const SwNodeIndex& rEnd = PCURCRSR->End()->nNode;
            SwNodeIndex aIdx( PCURCRSR->Start()->nNode );
            SwNode* pNd = &aIdx.GetNode();
            do {
                if( pNd->IsTxtNode() )
                    ((SwTxtNode*)pNd)->GCAttr();
            }
            while( 0 != ( pNd = GetDoc()->GetNodes().GoNext( &aIdx )) &&
                    aIdx <= rEnd );
        }
    FOREACHPAM_END()
//  EndAllAction();
}

// Setze das Attribut als neues default Attribut im Dokument.

void SwEditShell::SetDefault( const SfxPoolItem& rFmtHint )
{
    // 7502: Action-Klammerung
    StartAllAction();
    GetDoc()->SetDefault( rFmtHint );
    EndAllAction();
}

/*

void SwEditShell::SetDefault( const SfxItemSet& rSet )
{
    // 7502: Action-Klammerung
    StartAllAction();
    GetDoc()->SetDefault( rSet );
    EndAllAction();
}
*/

// Erfrage das Default Attribut in diesem Dokument.

const SfxPoolItem& SwEditShell::GetDefault( USHORT nFmtHint ) const
{
    return GetDoc()->GetDefault( nFmtHint );

}

void SwEditShell::SetAttr( const SfxPoolItem& rHint, USHORT nFlags )
{
    SET_CURR_SHELL( this );
    StartAllAction();
    SwPaM* pCrsr = GetCrsr();
    if( pCrsr->GetNext() != pCrsr )     // Ring von Cursorn
    {
        FASTBOOL bIsTblMode = IsTableMode();
        GetDoc()->StartUndo(UNDO_INSATTR);

        FOREACHPAM_START(this)
            if( PCURCRSR->HasMark() && ( bIsTblMode ||
                *PCURCRSR->GetPoint() != *PCURCRSR->GetMark() ))
                GetDoc()->Insert(*PCURCRSR, rHint, nFlags );
        FOREACHPAM_END()

        GetDoc()->EndUndo(UNDO_INSATTR);
    }
    else
    {
        if( !HasSelection() )
            UpdateAttr();
        GetDoc()->Insert( *pCrsr, rHint, nFlags );
    }
    EndAllAction();
}

void SwEditShell::SetAttr( const SfxItemSet& rSet, USHORT nFlags )
{
    SET_CURR_SHELL( this );
    StartAllAction();
    SwPaM* pCrsr = GetCrsr();
    if( pCrsr->GetNext() != pCrsr )     // Ring von Cursorn
    {
        FASTBOOL bIsTblMode = IsTableMode();
        GetDoc()->StartUndo(UNDO_INSATTR);

        FOREACHPAM_START(this)
            if( PCURCRSR->HasMark() && ( bIsTblMode ||
                *PCURCRSR->GetPoint() != *PCURCRSR->GetMark() ))
                GetDoc()->Insert(*PCURCRSR, rSet, nFlags );
        FOREACHPAM_END()

        GetDoc()->EndUndo(UNDO_INSATTR);
    }
    else
    {
        if( !HasSelection() )
            UpdateAttr();
        GetDoc()->Insert( *pCrsr, rSet, nFlags );
    }
    EndAllAction();
}

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

#pragma hdrstop

#ifndef _EDITSH_HXX
#include <editsh.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>      // fuer aNodes
#endif
#ifndef _PAM_HXX
#include <pam.hxx>      // fuer SwPaM
#endif
#ifndef _EDIMP_HXX
#include <edimp.hxx>    // fuer MACROS
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx>   // fuer die UndoIds
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>    // fuer Get-/ChgFmt Set-/GetAttrXXX
#endif

/*************************************
 * harte Formatierung (Attribute)
 *************************************/

void SwEditShell::ResetAttr()
{
    SET_CURR_SHELL( this );
    StartAllAction();
    BOOL bUndoGroup = GetCrsr()->GetNext() != GetCrsr();
    if( bUndoGroup )
        GetDoc()->StartUndo(UNDO_RESETATTR, NULL);

        FOREACHPAM_START(this)
            // if ( PCURCRSR->HasMark() )
                GetDoc()->ResetAttr(*PCURCRSR);
        FOREACHPAM_END()

    if( bUndoGroup )
        GetDoc()->EndUndo(UNDO_RESETATTR, NULL);
    CallChgLnk();
    EndAllAction();
}

void SwEditShell::GCAttr()
{
//JP 04.02.97: wozu eine Action-Klammerung - ein Formatierung sollte nicht
//              ausgeloest werden, so dass es hier ueberfluessig ist.
//              Sonst Probleme im MouseBut.DownHdl - Bug 35562
//  StartAllAction();
    FOREACHPAM_START(this)
        SwTxtNode *pTxtNode;
        if ( !PCURCRSR->HasMark() )
        {
            if( 0 != (pTxtNode = GetDoc()->GetNodes()[
                                PCURCRSR->GetPoint()->nNode]->GetTxtNode()))
                pTxtNode->GCAttr();
        }
        else
        {
            const SwNodeIndex& rEnd = PCURCRSR->End()->nNode;
            SwNodeIndex aIdx( PCURCRSR->Start()->nNode );
            SwNode* pNd = &aIdx.GetNode();
            do {
                if( pNd->IsTxtNode() )
                    ((SwTxtNode*)pNd)->GCAttr();
            }
            while( 0 != ( pNd = GetDoc()->GetNodes().GoNext( &aIdx )) &&
                    aIdx <= rEnd );
        }
    FOREACHPAM_END()
//  EndAllAction();
}

// Setze das Attribut als neues default Attribut im Dokument.

void SwEditShell::SetDefault( const SfxPoolItem& rFmtHint )
{
    // 7502: Action-Klammerung
    StartAllAction();
    GetDoc()->SetDefault( rFmtHint );
    EndAllAction();
}

/*

void SwEditShell::SetDefault( const SfxItemSet& rSet )
{
    // 7502: Action-Klammerung
    StartAllAction();
    GetDoc()->SetDefault( rSet );
    EndAllAction();
}
*/

// Erfrage das Default Attribut in diesem Dokument.

const SfxPoolItem& SwEditShell::GetDefault( USHORT nFmtHint ) const
{
    return GetDoc()->GetDefault( nFmtHint );

}

void SwEditShell::SetAttr( const SfxPoolItem& rHint, USHORT nFlags )
{
    SET_CURR_SHELL( this );
    StartAllAction();
    SwPaM* pCrsr = GetCrsr();
    if( pCrsr->GetNext() != pCrsr )     // Ring von Cursorn
    {
        FASTBOOL bIsTblMode = IsTableMode();
        GetDoc()->StartUndo(UNDO_INSATTR, NULL);

        FOREACHPAM_START(this)
            if( PCURCRSR->HasMark() && ( bIsTblMode ||
                *PCURCRSR->GetPoint() != *PCURCRSR->GetMark() ))
                GetDoc()->Insert(*PCURCRSR, rHint, nFlags );
        FOREACHPAM_END()

        GetDoc()->EndUndo(UNDO_INSATTR, NULL);
    }
    else
    {
        if( !HasSelection() )
            UpdateAttr();
        GetDoc()->Insert( *pCrsr, rHint, nFlags );
    }
    EndAllAction();
}

void SwEditShell::SetAttr( const SfxItemSet& rSet, USHORT nFlags )
{
    SET_CURR_SHELL( this );
    StartAllAction();
    SwPaM* pCrsr = GetCrsr();
    if( pCrsr->GetNext() != pCrsr )     // Ring von Cursorn
    {
        FASTBOOL bIsTblMode = IsTableMode();
        GetDoc()->StartUndo(UNDO_INSATTR, NULL);

        FOREACHPAM_START(this)
            if( PCURCRSR->HasMark() && ( bIsTblMode ||
                *PCURCRSR->GetPoint() != *PCURCRSR->GetMark() ))
                GetDoc()->Insert(*PCURCRSR, rSet, nFlags );
        FOREACHPAM_END()

        GetDoc()->EndUndo(UNDO_INSATTR, NULL);
    }
    else
    {
        if( !HasSelection() )
            UpdateAttr();
        GetDoc()->Insert( *pCrsr, rSet, nFlags );
    }
    EndAllAction();
}

<|endoftext|>