<commit_before>#ifndef ANY_HPP
# define ANY_HPP
# pragma once

#include <cassert>

#include <cstdint>

#include <stdexcept>

#include <typeinfo>

#include <type_traits>

#include <utility>

namespace generic
{

class any
{
public:
  template <typename T>
  using remove_cvr = ::std::remove_cv<
    typename ::std::remove_reference<T>::type
  >;

  using typeid_t = void const*;

  template <typename T>
  static typeid_t type_id() noexcept
  {
    static char const type_id{};

    return &type_id;
  }

  any() = default;

  any(any const& other) :
    content(other.content ? other.content->cloner_(other.content) : nullptr)
  {
  }

  any(any&& other) noexcept { *this = ::std::move(other); }

  template<typename ValueType,
    typename = typename ::std::enable_if<
      !::std::is_same<any, typename ::std::decay<ValueType>::type>{}
    >::type
  >
  any(ValueType&& value) :
    content(new holder<typename remove_cvr<ValueType>::type>(
      ::std::forward<ValueType>(value)))
  {
  }

  ~any() { delete content; }

public: // modifiers
  void clear() { swap(any()); }

  bool empty() const noexcept { return !*this; }

  void swap(any& other) noexcept { ::std::swap(content, other.content); }

  void swap(any&& other) noexcept { ::std::swap(content, other.content); }

  any& operator=(any const& rhs) { return *this = any(rhs); }

  any& operator=(any&& rhs) noexcept { swap(rhs); return *this; }

  template<typename ValueType,
    typename = typename ::std::enable_if<
      !::std::is_same<any, typename remove_cvr<ValueType>::type>{}
    >::type
  >
  any& operator=(ValueType&& rhs)
  {
    return *this = any(::std::forward<ValueType>(rhs));
  }

public: // queries

  explicit operator bool() const noexcept { return content; }

  typeid_t type() const noexcept { return type_id(); }

  typeid_t type_id() const noexcept
  {
    return content ? content->type_id_ : type_id<void>();
  }

public: // get

  template <typename ValueType>
  ValueType cget() const
  {
    return get<ValueType>();
  }

  template <typename ValueType>
  ValueType get() const
  {
    using nonref = typename ::std::remove_reference<ValueType>::type;

    return const_cast<any*>(this)->get<nonref const&>();
  }

  template <typename ValueType>
  ValueType get()
  {
    using nonref = typename ::std::remove_reference<ValueType>::type;

#ifndef NDEBUG
    if (content && (type_id() ==
      any::type_id<typename any::remove_cvr<ValueType>::type>()))
    {
      return static_cast<any::holder<nonref>*>(content)->held;
    }
    else
    {
      throw ::std::bad_typeid();
    }
#else
    return static_cast<any::holder<nonref>*>(content)->held;
#endif // NDEBUG
  }

private: // types

  template <typename T>
  static constexpr T* begin(T& value) noexcept
  {
    return &value;
  }

  template <typename T, ::std::size_t N>
  static constexpr typename ::std::remove_all_extents<T>::type*
  begin(T (&array)[N]) noexcept
  {
    return begin(*array);
  }

  template <typename T>
  static constexpr T* end(T& value) noexcept
  {
    return &value + 1;
  }

  template <typename T, ::std::size_t N>
  static constexpr typename ::std::remove_all_extents<T>::type*
  end(T (&array)[N]) noexcept
  {
    return end(array[N - 1]);
  }

  struct placeholder
  {
    typeid_t const type_id_;

    placeholder* (* const cloner_)(placeholder*);

    virtual ~placeholder() = default;

  protected:

    placeholder(typeid_t const ti, decltype(cloner_) const c) noexcept :
      type_id_(ti),
      cloner_(c)
    {
    }
  };

  template <typename ValueType>
  struct holder : public placeholder
  {
  public: // constructor
    template <class T, typename U = ValueType>
    holder(T&& value,
      typename ::std::enable_if<
        !::std::is_array<U>{} &&
        !::std::is_copy_constructible<U>{}
      >::type* = nullptr) :
      placeholder(type_id<ValueType>(), throwing_cloner),
      held(::std::forward<T>(value))
    {
    }

    template <class T, typename U = ValueType>
    holder(T&& value,
      typename ::std::enable_if<
        !::std::is_array<U>{} &&
        ::std::is_copy_constructible<U>{}
      >::type* = nullptr) :
      placeholder(type_id<ValueType>(), cloner),
      held(::std::forward<T>(value))
    {
    }

    template <class T, typename U = ValueType>
    holder(T&& value,
      typename ::std::enable_if<
        ::std::is_array<U>{} &&
        !::std::is_copy_assignable<
          typename ::std::remove_all_extents<U>::type
        >{} &&
        ::std::is_move_assignable<
          typename ::std::remove_all_extents<U>::type
        >{}
      >::type* = nullptr) :
      placeholder(type_id<ValueType>(), throwing_cloner)
    {
      ::std::copy(::std::make_move_iterator(begin(value)),
        ::std::make_move_iterator(end(value)),
        begin(held));
    }

    template <class T, typename U = ValueType>
    holder(T&& value,
      typename ::std::enable_if<
        ::std::is_array<U>{} &&
        ::std::is_copy_assignable<
          typename ::std::remove_all_extents<U>::type
        >{}
      >::type* = nullptr) :
      placeholder(type_id<ValueType>(), cloner)
    {
      ::std::copy(begin(value), end(value), begin(held));
    }

    holder& operator=(holder const&) = delete;

    static placeholder* cloner(placeholder* const base)
    {
      return new holder<ValueType>(static_cast<holder*>(base)->held);
    }

    static placeholder* throwing_cloner(placeholder* const)
    {
      throw ::std::logic_error("");
    }

  public:
    ValueType held;
  };

private: // representation

  template<typename ValueType>
  friend ValueType* any_cast(any*) noexcept;

  template<typename ValueType>
  friend ValueType* unsafe_any_cast(any*) noexcept;

  placeholder* content{};
};

template<typename ValueType>
inline ValueType* unsafe_any_cast(any* const operand) noexcept
{
  return &static_cast<any::holder<ValueType>*>(operand->content)->held;
}

template<typename ValueType>
inline ValueType const* unsafe_any_cast(any const* const operand) noexcept
{
  return unsafe_any_cast<ValueType>(const_cast<any*>(operand));
}

template<typename ValueType>
inline ValueType* any_cast(any* const operand) noexcept
{
  return operand &&
    (operand->type_id() ==
      any::type_id<typename any::remove_cvr<ValueType>::type>()) ?
    &static_cast<any::holder<ValueType>*>(operand->content)->held :
    nullptr;
}

template<typename ValueType>
inline ValueType const* any_cast(any const* const operand) noexcept
{
  return any_cast<ValueType>(const_cast<any*>(operand));
}

template<typename ValueType>
inline ValueType any_cast(any& operand)
{
  using nonref = typename ::std::remove_reference<ValueType>::type;

#ifndef NDEBUG
  auto const result(any_cast<nonref>(&operand));

  if (result)
  {
    return *result;
  }
  else
  {
    throw ::std::bad_cast();
  }
#else
  return *unsafe_any_cast<nonref>(&operand);
#endif // NDEBUG
}

template<typename ValueType>
inline ValueType any_cast(any const& operand)
{
  using nonref = typename ::std::remove_reference<ValueType>::type;

  return any_cast<nonref const&>(const_cast<any&>(operand));
}

}

#endif // ANY_HPP
<commit_msg>some fixes<commit_after>#ifndef ANY_HPP
# define ANY_HPP
# pragma once

#include <cassert>

#include <cstdint>

#include <stdexcept>

#include <typeinfo>

#include <type_traits>

#include <utility>

namespace generic
{

class any
{
public:
  template <typename T>
  using remove_cvr = ::std::remove_cv<
    typename ::std::remove_reference<T>::type
  >;

  using typeid_t = void const*;

  template <typename T>
  static typeid_t type_id() noexcept
  {
    static char const type_id{};

    return &type_id;
  }

  any() = default;

  any(any const& other) :
    content(other.content ? other.content->cloner_(other.content) : nullptr)
  {
  }

  any(any&& other) noexcept { *this = ::std::move(other); }

  template<typename ValueType,
    typename = typename ::std::enable_if<
      !::std::is_same<any, typename ::std::decay<ValueType>::type>{}
    >::type
  >
  any(ValueType&& value) :
    content(new holder<typename remove_cvr<ValueType>::type>(
      ::std::forward<ValueType>(value)))
  {
  }

  ~any() { delete content; }

public: // modifiers
  void clear() { swap(any()); }

  bool empty() const noexcept { return !*this; }

  void swap(any& other) noexcept { ::std::swap(content, other.content); }

  void swap(any&& other) noexcept { ::std::swap(content, other.content); }

  any& operator=(any const& rhs) { return content == rhs.content ? *this : *this = any(rhs); }

  any& operator=(any&& rhs) noexcept { swap(rhs); return *this; }

  template<typename ValueType,
    typename = typename ::std::enable_if<
      !::std::is_same<any, typename remove_cvr<ValueType>::type>{}
    >::type
  >
  any& operator=(ValueType&& rhs)
  {
    return *this = any(::std::forward<ValueType>(rhs));
  }

public: // queries

  explicit operator bool() const noexcept { return content; }

  typeid_t type() const noexcept { return type_id(); }

  typeid_t type_id() const noexcept
  {
    return content ? content->type_id_ : type_id<void>();
  }

public: // get

  template <typename ValueType>
  ValueType cget() const
  {
    return get<ValueType>();
  }

  template <typename ValueType>
  ValueType get() const
  {
    using nonref = typename ::std::remove_reference<ValueType>::type;

    return const_cast<any*>(this)->get<nonref const&>();
  }

  template <typename ValueType>
  ValueType get()
  {
    using nonref = typename ::std::remove_reference<ValueType>::type;

#ifndef NDEBUG
    if (content && (type_id() ==
      any::type_id<typename any::remove_cvr<ValueType>::type>()))
    {
      return static_cast<any::holder<nonref>*>(content)->held;
    }
    else
    {
      throw ::std::bad_typeid();
    }
#else
    return static_cast<any::holder<nonref>*>(content)->held;
#endif // NDEBUG
  }

private: // types

  template <typename T>
  static constexpr T* begin(T& value) noexcept
  {
    return &value;
  }

  template <typename T, ::std::size_t N>
  static constexpr typename ::std::remove_all_extents<T>::type*
  begin(T (&array)[N]) noexcept
  {
    return begin(*array);
  }

  template <typename T>
  static constexpr T* end(T& value) noexcept
  {
    return &value + 1;
  }

  template <typename T, ::std::size_t N>
  static constexpr typename ::std::remove_all_extents<T>::type*
  end(T (&array)[N]) noexcept
  {
    return end(array[N - 1]);
  }

  struct placeholder
  {
    typeid_t const type_id_;

    placeholder* (* const cloner_)(placeholder*);

    virtual ~placeholder() = default;

  protected:

    placeholder(typeid_t const ti, decltype(cloner_) const c) noexcept :
      type_id_(ti),
      cloner_(c)
    {
    }
  };

  template <typename ValueType>
  struct holder : public placeholder
  {
  public: // constructor
    template <class T, typename U = ValueType>
    holder(T&& value,
      typename ::std::enable_if<
        !::std::is_array<U>{} &&
        !::std::is_copy_constructible<U>{}
      >::type* = nullptr) :
      placeholder(type_id<ValueType>(), throwing_cloner),
      held(::std::forward<T>(value))
    {
    }

    template <class T, typename U = ValueType>
    holder(T&& value,
      typename ::std::enable_if<
        !::std::is_array<U>{} &&
        ::std::is_copy_constructible<U>{}
      >::type* = nullptr) :
      placeholder(type_id<ValueType>(), cloner),
      held(::std::forward<T>(value))
    {
    }

    template <class T, typename U = ValueType>
    holder(T&& value,
      typename ::std::enable_if<
        ::std::is_array<U>{} &&
        !::std::is_copy_assignable<
          typename ::std::remove_all_extents<U>::type
        >{} &&
        ::std::is_move_assignable<
          typename ::std::remove_all_extents<U>::type
        >{}
      >::type* = nullptr) :
      placeholder(type_id<ValueType>(), throwing_cloner)
    {
      ::std::copy(::std::make_move_iterator(begin(value)),
        ::std::make_move_iterator(end(value)),
        begin(held));
    }

    template <class T, typename U = ValueType>
    holder(T&& value,
      typename ::std::enable_if<
        ::std::is_array<U>{} &&
        ::std::is_copy_assignable<
          typename ::std::remove_all_extents<U>::type
        >{}
      >::type* = nullptr) :
      placeholder(type_id<ValueType>(), cloner)
    {
      ::std::copy(begin(value), end(value), begin(held));
    }

    holder& operator=(holder const&) = delete;

    static placeholder* cloner(placeholder* const base)
    {
      return new holder<ValueType>(static_cast<holder*>(base)->held);
    }

    static placeholder* throwing_cloner(placeholder* const)
    {
      throw ::std::logic_error("");
    }

  public:
    ValueType held;
  };

private: // representation

  template<typename ValueType>
  friend ValueType* any_cast(any*) noexcept;

  template<typename ValueType>
  friend ValueType* unsafe_any_cast(any*) noexcept;

  placeholder* content{};
};

template<typename ValueType>
inline ValueType* unsafe_any_cast(any* const operand) noexcept
{
  return &static_cast<any::holder<ValueType>*>(operand->content)->held;
}

template<typename ValueType>
inline ValueType const* unsafe_any_cast(any const* const operand) noexcept
{
  return unsafe_any_cast<ValueType>(const_cast<any*>(operand));
}

template<typename ValueType>
inline ValueType* any_cast(any* const operand) noexcept
{
  return operand &&
    (operand->type_id() ==
      any::type_id<typename any::remove_cvr<ValueType>::type>()) ?
    &static_cast<any::holder<ValueType>*>(operand->content)->held :
    nullptr;
}

template<typename ValueType>
inline ValueType const* any_cast(any const* const operand) noexcept
{
  return any_cast<ValueType>(const_cast<any*>(operand));
}

template<typename ValueType>
inline ValueType any_cast(any& operand)
{
  using nonref = typename ::std::remove_reference<ValueType>::type;

#ifndef NDEBUG
  auto const result(any_cast<nonref>(&operand));

  if (result)
  {
    return *result;
  }
  else
  {
    throw ::std::bad_cast();
  }
#else
  return *unsafe_any_cast<nonref>(&operand);
#endif // NDEBUG
}

template<typename ValueType>
inline ValueType any_cast(any const& operand)
{
  using nonref = typename ::std::remove_reference<ValueType>::type;

  return any_cast<nonref const&>(const_cast<any&>(operand));
}

}

#endif // ANY_HPP
<|endoftext|>


<commit_before>namespace bmi {

  const int BMI_SUCCESS = 0;
  const int BMI_FAILURE = 1;

  const int MAX_COMPONENT_NAME = 2048;
  const int MAX_VAR_NAME = 2048;
  const int MAX_UNITS_NAME = 2048;
  const int MAX_TYPE_NAME = 2048;

  class Bmi {
    public:
      // Model control functions.
      virtual void Initialize(std::string config_file) = 0;
      virtual void Update() = 0;
      virtual void UpdateUntil(double time) = 0;
      virtual void Finalize() = 0;

      // Model information functions.
      virtual std::string GetComponentName() = 0;
      virtual int GetInputItemCount() = 0;
      virtual int GetOutputItemCount() = 0;
      virtual void GetInputVarNames(std::vector<std::string>&) = 0;
      virtual void GetOutputVarNames(std::vector<std::string>&) = 0;

      // Variable information functions
      virtual int GetVarGrid(std::string name) = 0;
      virtual std::string GetVarType(std::string name) = 0;
      virtual std::string GetVarUnits(std::string name) = 0;
      virtual int GetVarItemsize(std::string name) = 0;
      virtual int GetVarNbytes(std::string name) = 0;
      virtual std::string GetVarLocation(std::string name) = 0;

      virtual double GetCurrentTime() = 0;
      virtual double GetStartTime() = 0;
      virtual double GetEndTime() = 0;
      virtual std::string GetTimeUnits() = 0;
      virtual double GetTimeStep() = 0;

      // Variable getters
      virtual void GetValue(std::string name, void *dest) = 0;
      virtual void *GetValuePtr(std::string name) = 0;
      virtual void GetValueAtIndices(std::string name, void *dest, int *inds, int count) = 0;

      // Variable setters
      virtual void SetValue(std::string name, void *src) = 0;
      virtual void SetValueAtIndices(std::string name, int *inds, int count, void *src) = 0;

      // Grid information functions
      virtual int GetGridRank(const int grid) = 0;
      virtual int GetGridSize(const int grid) = 0;
      virtual std::string GetGridType(const int grid) = 0;

      virtual void GetGridShape(const int grid, int *shape) = 0;
      virtual void GetGridSpacing(const int grid, double *spacing) = 0;
      virtual void GetGridOrigin(const int grid, double *origin) = 0;

      virtual void GetGridX(const int grid, double *x) = 0;
      virtual void GetGridY(const int grid, double *y) = 0;
      virtual void GetGridZ(const int grid, double *z) = 0;

      virtual int GetGridNodeCount(const int grid) = 0;
      virtual int GetGridEdgeCount(const int grid) = 0;
      virtual int GetGridFaceCount(const int grid) = 0;

      virtual void GetGridEdgeNodes(const int grid, int *edge_nodes) = 0;
      virtual void GetGridFaceEdges(const int grid, int *face_edges) = 0;
      virtual void GetGridFaceNodes(const int grid, int *face_nodes) = 0;
      virtual void GetGridNodesPerFace(const int grid, int *nodes_per_face) = 0;
  };
}
<commit_msg>Eliminate parameter, instead returning vector of strings<commit_after>namespace bmi {

  const int BMI_SUCCESS = 0;
  const int BMI_FAILURE = 1;

  const int MAX_COMPONENT_NAME = 2048;
  const int MAX_VAR_NAME = 2048;
  const int MAX_UNITS_NAME = 2048;
  const int MAX_TYPE_NAME = 2048;

  class Bmi {
    public:
      // Model control functions.
      virtual void Initialize(std::string config_file) = 0;
      virtual void Update() = 0;
      virtual void UpdateUntil(double time) = 0;
      virtual void Finalize() = 0;

      // Model information functions.
      virtual std::string GetComponentName() = 0;
      virtual int GetInputItemCount() = 0;
      virtual int GetOutputItemCount() = 0;
      virtual std::vector<std::string> GetInputVarNames() = 0;
      virtual std::vector<std::string> GetOutputVarNames() = 0;

      // Variable information functions
      virtual int GetVarGrid(std::string name) = 0;
      virtual std::string GetVarType(std::string name) = 0;
      virtual std::string GetVarUnits(std::string name) = 0;
      virtual int GetVarItemsize(std::string name) = 0;
      virtual int GetVarNbytes(std::string name) = 0;
      virtual std::string GetVarLocation(std::string name) = 0;

      virtual double GetCurrentTime() = 0;
      virtual double GetStartTime() = 0;
      virtual double GetEndTime() = 0;
      virtual std::string GetTimeUnits() = 0;
      virtual double GetTimeStep() = 0;

      // Variable getters
      virtual void GetValue(std::string name, void *dest) = 0;
      virtual void *GetValuePtr(std::string name) = 0;
      virtual void GetValueAtIndices(std::string name, void *dest, int *inds, int count) = 0;

      // Variable setters
      virtual void SetValue(std::string name, void *src) = 0;
      virtual void SetValueAtIndices(std::string name, int *inds, int count, void *src) = 0;

      // Grid information functions
      virtual int GetGridRank(const int grid) = 0;
      virtual int GetGridSize(const int grid) = 0;
      virtual std::string GetGridType(const int grid) = 0;

      virtual void GetGridShape(const int grid, int *shape) = 0;
      virtual void GetGridSpacing(const int grid, double *spacing) = 0;
      virtual void GetGridOrigin(const int grid, double *origin) = 0;

      virtual void GetGridX(const int grid, double *x) = 0;
      virtual void GetGridY(const int grid, double *y) = 0;
      virtual void GetGridZ(const int grid, double *z) = 0;

      virtual int GetGridNodeCount(const int grid) = 0;
      virtual int GetGridEdgeCount(const int grid) = 0;
      virtual int GetGridFaceCount(const int grid) = 0;

      virtual void GetGridEdgeNodes(const int grid, int *edge_nodes) = 0;
      virtual void GetGridFaceEdges(const int grid, int *face_edges) = 0;
      virtual void GetGridFaceNodes(const int grid, int *face_nodes) = 0;
      virtual void GetGridNodesPerFace(const int grid, int *nodes_per_face) = 0;
  };
}
<|endoftext|>


<commit_before>// Calculates the size of a C-style array
int a[5];
std::cout << "Size: " << sizeof(a)/sizeof(*a) << std::endl;
<commit_msg>-Fast sigmoid is added<commit_after>// Calculates the size of a C-style array
int a[5];
std::cout << "Size: " << sizeof(a)/sizeof(*a) << std::endl;

// Fast sigmoid f(x) = x / (1 + abs(x))
double fastSigmoid(double in){
  return in / (1.0 + (in < 0.0 ? -in : in));
}
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (c) 2013 Jan Rheinländer                                    *
 *                                   <jrheinlaender@users.sourceforge.net> *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   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 Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <sstream>
# include <QRegExp>
# include <QTextStream>
# include <Precision.hxx>
#endif

#include <Base/Console.h>
#include <App/Application.h>
#include <App/Document.h>
#include <App/Origin.h>
#include <App/OriginFeature.h>
#include <Gui/Application.h>
#include <Gui/Document.h>
#include <Gui/BitmapFactory.h>
#include <Gui/ViewProvider.h>
#include <Gui/WaitCursor.h>
#include <Gui/Selection.h>
#include <Gui/Command.h>

#include <Mod/Part/App/DatumFeature.h>
#include <Mod/PartDesign/App/FeatureSketchBased.h>
#include <Mod/Sketcher/App/SketchObject.h>
#include <Mod/PartDesign/App/Body.h>

#include "Utils.h"
#include "ReferenceSelection.h"

#include "TaskSketchBasedParameters.h"

using namespace PartDesignGui;
using namespace Gui;

/* TRANSLATOR PartDesignGui::TaskSketchBasedParameters */

TaskSketchBasedParameters::TaskSketchBasedParameters(PartDesignGui::ViewProvider *vp, QWidget *parent,
                                                     const std::string& pixmapname, const QString& parname)
    : TaskFeatureParameters(vp, parent, pixmapname, parname)
{

}

const QString TaskSketchBasedParameters::onAddSelection(const Gui::SelectionChanges& msg)
{
    // Note: The validity checking has already been done in ReferenceSelection.cpp
    PartDesign::ProfileBased* pcSketchBased = static_cast<PartDesign::ProfileBased*>(vp->getObject());
    App::DocumentObject* selObj = pcSketchBased->getDocument()->getObject(msg.pObjectName);
    if (selObj == pcSketchBased)
        return QString();
    std::string subname = msg.pSubName;
    QString refStr;

    // Remove subname for planes and datum features
    if (PartDesign::Feature::isDatum(selObj)) {
        subname = "";
        refStr = QString::fromLatin1(selObj->getNameInDocument());
    } else if (subname.size() > 4) {
        int faceId = std::atoi(&subname[4]);
        refStr = QString::fromLatin1(selObj->getNameInDocument()) + QString::fromLatin1(":") + QObject::tr("Face") + QString::number(faceId);
    }

    std::vector<std::string> upToFaces(1,subname);
    pcSketchBased->UpToFace.setValue(selObj, upToFaces);
    recomputeFeature();

    return refStr;
}

void TaskSketchBasedParameters::onSelectReference(const bool pressed, const bool edge, const bool face, const bool planar) {
    // Note: Even if there is no solid, App::Plane and Part::Datum can still be selected

    PartDesign::ProfileBased* pcSketchBased = dynamic_cast<PartDesign::ProfileBased*>(vp->getObject());
    if (pcSketchBased) {
        // The solid this feature will be fused to
        App::DocumentObject* prevSolid = pcSketchBased->getBaseObject( /* silent =*/ true );

        if (pressed) {
            Gui::Document* doc = vp->getDocument();
            if (doc) {
                doc->setHide(pcSketchBased->getNameInDocument());
                if (prevSolid)
                    doc->setShow(prevSolid->getNameInDocument());
            }
            Gui::Selection().clearSelection();
            Gui::Selection().addSelectionGate
                (new ReferenceSelection(prevSolid, edge, face, planar));
        } else {
            Gui::Selection().rmvSelectionGate();
            Gui::Document* doc = vp->getDocument();
            if (doc) {
                doc->setShow(pcSketchBased->getNameInDocument());
                if (prevSolid)
                    doc->setHide(prevSolid->getNameInDocument());
            }
        }
    }
}

void TaskSketchBasedParameters::exitSelectionMode()
{
    onSelectReference(false, false, false, false);
}

QVariant TaskSketchBasedParameters::setUpToFace(const QString& text)
{
    if (text.isEmpty())
        return QVariant();

    QStringList parts = text.split(QChar::fromLatin1(':'));
    if (parts.length() < 2)
        parts.push_back(QString::fromLatin1(""));

    // Check whether this is the name of an App::Plane or Part::Datum feature
    App::DocumentObject* obj = vp->getObject()->getDocument()->getObject(parts[0].toLatin1());
    if (obj == NULL)
        return QVariant();

    if (obj->getTypeId().isDerivedFrom(App::Plane::getClassTypeId())) {
        // everything is OK (we assume a Part can only have exactly 3 App::Plane objects located at the base of the feature tree)
        return QVariant();
    }
    else if (obj->getTypeId().isDerivedFrom(Part::Datum::getClassTypeId())) {
        // it's up to the document to check that the datum plane is in the same body
        return QVariant();
    }
    else {
        // We must expect that "parts[1]" is the translation of "Face" followed by an ID.
        QString name;
        QTextStream str(&name);
        str << "^" << tr("Face") << "(\\d+)$";
        QRegExp rx(name);
        if (parts[1].indexOf(rx) < 0) {
            return QVariant();
        }

        int faceId = rx.cap(1).toInt();
        std::stringstream ss;
        ss << "Face" << faceId;

        std::vector<std::string> upToFaces(1,ss.str());
        PartDesign::ProfileBased* pcSketchBased = static_cast<PartDesign::ProfileBased*>(vp->getObject());
        pcSketchBased->UpToFace.setValue(obj, upToFaces);
        recomputeFeature();

        return QByteArray(ss.str().c_str());
    }
}

QVariant TaskSketchBasedParameters::objectNameByLabel(const QString& label,
                                                      const QVariant& suggest) const
{
    // search for an object with the given label
    App::Document* doc = this->vp->getObject()->getDocument();
    // for faster access try the suggestion
    if (suggest.isValid()) {
        App::DocumentObject* obj = doc->getObject(suggest.toByteArray());
        if (obj && QString::fromUtf8(obj->Label.getValue()) == label) {
            return QVariant(QByteArray(obj->getNameInDocument()));
        }
    }

    // go through all objects and check the labels
    std::string name = label.toUtf8().data();
    std::vector<App::DocumentObject*> objs = doc->getObjects();
    for (std::vector<App::DocumentObject*>::iterator it = objs.begin(); it != objs.end(); ++it) {
        if (name == (*it)->Label.getValue()) {
            return QVariant(QByteArray((*it)->getNameInDocument()));
        }
    }

    return QVariant(); // no such feature found
}

QString TaskSketchBasedParameters::getFaceReference(const QString& obj, const QString& sub) const
{
    App::Document* doc = this->vp->getObject()->getDocument();
    QString o = obj.left(obj.indexOf(QString::fromLatin1(":")));

    if (o.isEmpty())
        return QString();

    return QString::fromLatin1("(App.getDocument(\"%1\").%2, [\"%3\"])")
            .arg(QString::fromLatin1(doc->getName()), o, sub);
}

TaskSketchBasedParameters::~TaskSketchBasedParameters()
{
}

//**************************************************************************
//**************************************************************************
// TaskDialog
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

TaskDlgSketchBasedParameters::TaskDlgSketchBasedParameters(PartDesignGui::ViewProvider *vp)
    : TaskDlgFeatureParameters(vp)
{
}

TaskDlgSketchBasedParameters::~TaskDlgSketchBasedParameters()
{

}

//==== calls from the TaskView ===============================================================

bool TaskDlgSketchBasedParameters::accept() {
    App::DocumentObject* feature = vp->getObject();

    // Make sure the feature is what we are expecting
    // Should be fine but you never know...
    if ( !feature->getTypeId().isDerivedFrom(PartDesign::ProfileBased::getClassTypeId()) ) {
        throw Base::TypeError("Bad object processed in the sketch based dialog.");
    }

    App::DocumentObject* sketch = static_cast<PartDesign::ProfileBased*>(feature)->Profile.getValue();

    FCMD_OBJ_HIDE(sketch);

    return TaskDlgFeatureParameters::accept();
}

bool TaskDlgSketchBasedParameters::reject()
{
    PartDesign::ProfileBased* pcSketchBased = static_cast<PartDesign::ProfileBased*>(vp->getObject());
    // get the Sketch
    Sketcher::SketchObject *pcSketch = static_cast<Sketcher::SketchObject*>(pcSketchBased->Profile.getValue());
    bool rv;

    // rv should be true anyway but to be on the safe side due to further changes better respect it.
    rv = TaskDlgFeatureParameters::reject();

    // if abort command deleted the object the sketch is visible again.
    // The previous one feature already should be made visible
    if (!Gui::Application::Instance->getViewProvider(pcSketchBased)) {
        // Make the sketch visible
        if (pcSketch && Gui::Application::Instance->getViewProvider(pcSketch))
            Gui::Application::Instance->getViewProvider(pcSketch)->show();
    }

    return rv;
}

#include "moc_TaskSketchBasedParameters.cpp"
<commit_msg>PartDesign: make sure to remove selection gate when closing task panel<commit_after>/***************************************************************************
 *   Copyright (c) 2013 Jan Rheinländer                                    *
 *                                   <jrheinlaender@users.sourceforge.net> *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   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 Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <sstream>
# include <QRegExp>
# include <QTextStream>
# include <Precision.hxx>
#endif

#include <Base/Console.h>
#include <App/Application.h>
#include <App/Document.h>
#include <App/Origin.h>
#include <App/OriginFeature.h>
#include <Gui/Application.h>
#include <Gui/Document.h>
#include <Gui/BitmapFactory.h>
#include <Gui/ViewProvider.h>
#include <Gui/WaitCursor.h>
#include <Gui/Selection.h>
#include <Gui/Command.h>

#include <Mod/Part/App/DatumFeature.h>
#include <Mod/PartDesign/App/FeatureSketchBased.h>
#include <Mod/Sketcher/App/SketchObject.h>
#include <Mod/PartDesign/App/Body.h>

#include "Utils.h"
#include "ReferenceSelection.h"

#include "TaskSketchBasedParameters.h"

using namespace PartDesignGui;
using namespace Gui;

/* TRANSLATOR PartDesignGui::TaskSketchBasedParameters */

TaskSketchBasedParameters::TaskSketchBasedParameters(PartDesignGui::ViewProvider *vp, QWidget *parent,
                                                     const std::string& pixmapname, const QString& parname)
    : TaskFeatureParameters(vp, parent, pixmapname, parname)
{

}

const QString TaskSketchBasedParameters::onAddSelection(const Gui::SelectionChanges& msg)
{
    // Note: The validity checking has already been done in ReferenceSelection.cpp
    PartDesign::ProfileBased* pcSketchBased = static_cast<PartDesign::ProfileBased*>(vp->getObject());
    App::DocumentObject* selObj = pcSketchBased->getDocument()->getObject(msg.pObjectName);
    if (selObj == pcSketchBased)
        return QString();
    std::string subname = msg.pSubName;
    QString refStr;

    // Remove subname for planes and datum features
    if (PartDesign::Feature::isDatum(selObj)) {
        subname = "";
        refStr = QString::fromLatin1(selObj->getNameInDocument());
    } else if (subname.size() > 4) {
        int faceId = std::atoi(&subname[4]);
        refStr = QString::fromLatin1(selObj->getNameInDocument()) + QString::fromLatin1(":") + QObject::tr("Face") + QString::number(faceId);
    }

    std::vector<std::string> upToFaces(1,subname);
    pcSketchBased->UpToFace.setValue(selObj, upToFaces);
    recomputeFeature();

    return refStr;
}

void TaskSketchBasedParameters::onSelectReference(const bool pressed, const bool edge, const bool face, const bool planar) {
    // Note: Even if there is no solid, App::Plane and Part::Datum can still be selected

    PartDesign::ProfileBased* pcSketchBased = dynamic_cast<PartDesign::ProfileBased*>(vp->getObject());
    if (pcSketchBased) {
        // The solid this feature will be fused to
        App::DocumentObject* prevSolid = pcSketchBased->getBaseObject( /* silent =*/ true );

        if (pressed) {
            Gui::Document* doc = vp->getDocument();
            if (doc) {
                doc->setHide(pcSketchBased->getNameInDocument());
                if (prevSolid)
                    doc->setShow(prevSolid->getNameInDocument());
            }
            Gui::Selection().clearSelection();
            Gui::Selection().addSelectionGate
                (new ReferenceSelection(prevSolid, edge, face, planar));
        } else {
            Gui::Selection().rmvSelectionGate();
            Gui::Document* doc = vp->getDocument();
            if (doc) {
                doc->setShow(pcSketchBased->getNameInDocument());
                if (prevSolid)
                    doc->setHide(prevSolid->getNameInDocument());
            }
        }
    }
}

void TaskSketchBasedParameters::exitSelectionMode()
{
    onSelectReference(false, false, false, false);
}

QVariant TaskSketchBasedParameters::setUpToFace(const QString& text)
{
    if (text.isEmpty())
        return QVariant();

    QStringList parts = text.split(QChar::fromLatin1(':'));
    if (parts.length() < 2)
        parts.push_back(QString::fromLatin1(""));

    // Check whether this is the name of an App::Plane or Part::Datum feature
    App::DocumentObject* obj = vp->getObject()->getDocument()->getObject(parts[0].toLatin1());
    if (obj == NULL)
        return QVariant();

    if (obj->getTypeId().isDerivedFrom(App::Plane::getClassTypeId())) {
        // everything is OK (we assume a Part can only have exactly 3 App::Plane objects located at the base of the feature tree)
        return QVariant();
    }
    else if (obj->getTypeId().isDerivedFrom(Part::Datum::getClassTypeId())) {
        // it's up to the document to check that the datum plane is in the same body
        return QVariant();
    }
    else {
        // We must expect that "parts[1]" is the translation of "Face" followed by an ID.
        QString name;
        QTextStream str(&name);
        str << "^" << tr("Face") << "(\\d+)$";
        QRegExp rx(name);
        if (parts[1].indexOf(rx) < 0) {
            return QVariant();
        }

        int faceId = rx.cap(1).toInt();
        std::stringstream ss;
        ss << "Face" << faceId;

        std::vector<std::string> upToFaces(1,ss.str());
        PartDesign::ProfileBased* pcSketchBased = static_cast<PartDesign::ProfileBased*>(vp->getObject());
        pcSketchBased->UpToFace.setValue(obj, upToFaces);
        recomputeFeature();

        return QByteArray(ss.str().c_str());
    }
}

QVariant TaskSketchBasedParameters::objectNameByLabel(const QString& label,
                                                      const QVariant& suggest) const
{
    // search for an object with the given label
    App::Document* doc = this->vp->getObject()->getDocument();
    // for faster access try the suggestion
    if (suggest.isValid()) {
        App::DocumentObject* obj = doc->getObject(suggest.toByteArray());
        if (obj && QString::fromUtf8(obj->Label.getValue()) == label) {
            return QVariant(QByteArray(obj->getNameInDocument()));
        }
    }

    // go through all objects and check the labels
    std::string name = label.toUtf8().data();
    std::vector<App::DocumentObject*> objs = doc->getObjects();
    for (std::vector<App::DocumentObject*>::iterator it = objs.begin(); it != objs.end(); ++it) {
        if (name == (*it)->Label.getValue()) {
            return QVariant(QByteArray((*it)->getNameInDocument()));
        }
    }

    return QVariant(); // no such feature found
}

QString TaskSketchBasedParameters::getFaceReference(const QString& obj, const QString& sub) const
{
    App::Document* doc = this->vp->getObject()->getDocument();
    QString o = obj.left(obj.indexOf(QString::fromLatin1(":")));

    if (o.isEmpty())
        return QString();

    return QString::fromLatin1("(App.getDocument(\"%1\").%2, [\"%3\"])")
            .arg(QString::fromLatin1(doc->getName()), o, sub);
}

TaskSketchBasedParameters::~TaskSketchBasedParameters()
{
    Gui::Selection().rmvSelectionGate();
}

//**************************************************************************
//**************************************************************************
// TaskDialog
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

TaskDlgSketchBasedParameters::TaskDlgSketchBasedParameters(PartDesignGui::ViewProvider *vp)
    : TaskDlgFeatureParameters(vp)
{
}

TaskDlgSketchBasedParameters::~TaskDlgSketchBasedParameters()
{

}

//==== calls from the TaskView ===============================================================

bool TaskDlgSketchBasedParameters::accept() {
    App::DocumentObject* feature = vp->getObject();

    // Make sure the feature is what we are expecting
    // Should be fine but you never know...
    if ( !feature->getTypeId().isDerivedFrom(PartDesign::ProfileBased::getClassTypeId()) ) {
        throw Base::TypeError("Bad object processed in the sketch based dialog.");
    }

    App::DocumentObject* sketch = static_cast<PartDesign::ProfileBased*>(feature)->Profile.getValue();

    FCMD_OBJ_HIDE(sketch);

    return TaskDlgFeatureParameters::accept();
}

bool TaskDlgSketchBasedParameters::reject()
{
    PartDesign::ProfileBased* pcSketchBased = static_cast<PartDesign::ProfileBased*>(vp->getObject());
    // get the Sketch
    Sketcher::SketchObject *pcSketch = static_cast<Sketcher::SketchObject*>(pcSketchBased->Profile.getValue());
    bool rv;

    // rv should be true anyway but to be on the safe side due to further changes better respect it.
    rv = TaskDlgFeatureParameters::reject();

    // if abort command deleted the object the sketch is visible again.
    // The previous one feature already should be made visible
    if (!Gui::Application::Instance->getViewProvider(pcSketchBased)) {
        // Make the sketch visible
        if (pcSketch && Gui::Application::Instance->getViewProvider(pcSketch))
            Gui::Application::Instance->getViewProvider(pcSketch)->show();
    }

    return rv;
}

#include "moc_TaskSketchBasedParameters.cpp"
<|endoftext|>


<commit_before>// returns success if stdin or the argument is a complete datafile
#include "rdb.hpp"
#include "../utils/utils.hpp"
#include <cerrno>

// from datafile.cc
extern const char *start4;
extern const char *end4;

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

	FILE *in = stdin;
	if (argc == 2) {
		if (!fileexists(argv[1]))
			return 1;

		in = fopen(argv[1], "r");
		if (!in)
			fatalx(errno, "failed to open %s for reading", argv[1]);
	}

	boost::optional<std::string> l = readline(in);
	if (l && *l != start4)
		return 1;

	std::string prev;
	while (l) {
		prev = *l;
		l = readline(in);
	}

	if (prev != end4)
		return 1;

	return 0;
}<commit_msg>rdb: fix bug in dfcmplt.<commit_after>// returns success if stdin or the argument is a complete datafile
#include "rdb.hpp"
#include "../utils/utils.hpp"
#include <cerrno>

// from datafile.cc
extern const char *start4;
extern const char *end4;

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

	FILE *in = stdin;
	if (argc == 2) {
		if (!fileexists(argv[1]))
			return 1;

		in = fopen(argv[1], "r");
		if (!in)
			fatalx(errno, "failed to open %s for reading", argv[1]);
	}

	boost::optional<std::string> l = readline(in);
	if (!l)
		return 1;
	l->push_back('\n');
	if (*l != start4)
		return 1;

	std::string prev;
	while (l) {
		prev = *l;
		l = readline(in);
	}

	prev.push_back('\n');
	if (prev != end4)
		return 1;

	return 0;
}<|endoftext|>


<commit_before>#include "stdafx.h"

#include "Formula.h"
#include "Actions.h"
#include "Parser.h"
#include "PropertyBag.h"
#include "TokenPool.h"
#include "EventHandler.h"
#include "Scriptable.h"
#include "ScriptWorld.h"
#include "DeserializerFactory.h"

#include "../GameEngine/Map.h"
#include "../GameEngine/Unit.h"
#include "../GameEngine/SubMap.h"

namespace Simulation {

void SimulationRunKingdomWar() {
	const unsigned worldWidth = 20;
	const unsigned worldHeight = 20;

	const unsigned cellWidth = 20;
	const unsigned cellHeight = 20;

	Map worldMap(worldWidth, worldHeight);
	for(unsigned x = 0; x < worldWidth; ++x) {
		for(unsigned y = 0; y < worldHeight; ++y) {
			SubMap * cell = new SubMap(cellWidth, cellHeight, x, y);
			worldMap.AddUnit(cell);
		}
	}

	ScriptWorld world;
	DeserializerFactory factory;

	factory.LoadFileIntoScriptWorld("Data\\KingdomWar.json", &world);

	world.QueueBroadcastEvent("OnCreate");

	while(world.DispatchEvents());

	world.DumpOverview();
}

}

<commit_msg>Fix build break<commit_after>#include "stdafx.h"

#include "Formula.h"
#include "Actions.h"
#include "Parser.h"
#include "PropertyBag.h"
#include "TokenPool.h"
#include "EventHandler.h"
#include "Scriptable.h"
#include "ScriptWorld.h"
#include "DeserializerFactory.h"

#include "../GameEngine/Map.h"
#include "../GameEngine/Unit.h"
#include "../GameEngine/SubMap.h"

namespace Simulation {

void RunKingdomWar() {
	const unsigned worldWidth = 20;
	const unsigned worldHeight = 20;

	const unsigned cellWidth = 20;
	const unsigned cellHeight = 20;

	Map worldMap(worldWidth, worldHeight);
	for(unsigned x = 0; x < worldWidth; ++x) {
		for(unsigned y = 0; y < worldHeight; ++y) {
			SubMap * cell = new SubMap(cellWidth, cellHeight, x, y);
			worldMap.AddUnit(cell);
		}
	}

	ScriptWorld world;
	DeserializerFactory factory;

	factory.LoadFileIntoScriptWorld("Data\\KingdomWar.json", &world);

	world.QueueBroadcastEvent("OnCreate");

	while(world.DispatchEvents());

	world.DumpOverview();
}

}

<|endoftext|>


<commit_before>#include "cartrige.h"

struct rom_header
{
	u8 start_vector[4];
	u8 nintendo_logo[48];
	u8 game_title[11];
	u8 manufacturer_code[4];
	u8 cgb_flag;
	u8 new_license_code[2];
	u8 sgb_flag;
	u8 cartrige_type;
	u8 rom_size;
	u8 ram_size;
	u8 destination_code;
	u8 old_license_code;
	u8 rom_version;
	u8 checksum;
	u8 global_checksum[2];
};

bool in_range(u32 value, u32 begin, u32 end)
{
	return (value >= begin) && (value <= end);
}

void Cartrige::attach_rom(const u8* rom_ptr, u32 size)
{
	rom2 = std::make_pair(rom_ptr, size);
}

void Cartrige::attach_ram(u8* ram_ptr, u32 size)
{
	ram2 = std::make_pair(ram_ptr, size);
}

void Cartrige::attach_rtc(u8* rtc_ptr, u32 size)
{
	rtc2 = std::make_pair(rtc_ptr, size);
}

bool Cartrige::has_battery_ram() const
{
	if (std::get<0>(rom2) == nullptr)
		return false;

	const rom_header* header = reinterpret_cast<const rom_header*>(&std::get<0>(rom2)[0x100]);

	switch (header->cartrige_type)
	{
		case 0x03:
		case 0x06:
		case 0x09:
		case 0x0D:
		case 0x0F:
		case 0x10:
		case 0x13:
		case 0x1B:
		case 0x1E:
			return true;

		default:
			return false;
	}
}

u32 Cartrige::get_declared_ram_size() const
{
	static const u32 sizes[] = { 0, 0x800, 0x2000, 0x8000, 0x20000, 0x10000 };

	if (std::get<0>(rom2) == nullptr)
		return 0;

	const rom_header* header = reinterpret_cast<const rom_header*>(&std::get<0>(rom2)[0x100]);

	//MBC2 has always header->ram_size == 0, but it has 512 bytes actually!
	if (in_range(header->cartrige_type, 0x05, 0x06))
		return 512;

	else
		return (header->ram_size > 5) ? 0 : sizes[header->ram_size];
}

bool Cartrige::has_rtc() const
{
	if (std::get<0>(rom2) == nullptr)
		return false;

	const rom_header* header = reinterpret_cast<const rom_header*>(&std::get<0>(rom2)[0x100]);
	return in_range(header->cartrige_type, 0xF, 0x10);
}

Cartrige::~Cartrige()
{
	const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);

	if (battery_ram)
		save_ram_callback(ram.get(), ram_size);

	if (in_range(header->cartrige_type, 0x0F, 0x10))
	{
		memory_interface.reset(); //make sure that MBC3 update rtc_regs

		auto epoch = std::chrono::system_clock::now().time_since_epoch();
		auto cur_timestamp = std::chrono::duration_cast<std::chrono::seconds>(epoch);

		save_rtc_callback(cur_timestamp, rtc_regs, 5);
	}
}

bool Cartrige::load_cartrige(std::ifstream& cart, std::ifstream& ram, std::ifstream& rtc)
{
	if (!cart.is_open())
		return false;

	cart.seekg(0, std::ios_base::end);
	size_t size = cart.tellg();
	cart.seekg(0, std::ios_base::beg);

	rom = std::make_unique<u8[]>(size);
	cart.read(reinterpret_cast<char*>(rom.get()), size);

	attach_rom(rom.get(), size);

	load_or_create_ram(ram);
	load_rtc(rtc);

	dispatch();

	return true;
}

std::string Cartrige::get_name() const
{
    const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);
    return std::string(std::begin(header->game_title), std::end(header->game_title));
}

void Cartrige::attach_endpoints(function<void(const u8*, u32)> ram_save, function<void(std::chrono::seconds, const u8*, u32)> rtc_save)
{
	save_ram_callback = ram_save;
	save_rtc_callback = rtc_save;
}

void Cartrige::load_or_create_ram(std::ifstream& ram_file)
{
	ram_size = get_declared_ram_size();
	ram = ram_size ? std::make_unique<u8[]>(ram_size) : nullptr;

	battery_ram = has_battery_ram();

	if (battery_ram && ram_file.is_open())
		ram_file.read(reinterpret_cast<char*>(ram.get()), ram_size);
}

void Cartrige::load_rtc(std::ifstream& rtc_file)
{
	if (has_rtc() && rtc_file.is_open())
	{
		i64 saved_timestamp;
		rtc_file >> saved_timestamp;
		rtc_file.read(reinterpret_cast<char*>(rtc_regs), sizeof(u8) * 5);

		auto epoch = std::chrono::system_clock::now().time_since_epoch();
		auto cur_timestamp = std::chrono::duration_cast<std::chrono::seconds>(epoch);
		auto delta = cur_timestamp.count() - saved_timestamp;

		if (delta <= 0 || check_bit(rtc_regs[4], 6))
			return;

		auto ns = rtc_regs[0] + delta;
		auto nm = rtc_regs[1] + ns / 60;
		auto nh = rtc_regs[2] + nm / 60;
		auto nd = (((rtc_regs[4] & 1) << 8) | rtc_regs[3]) + nh / 24;

		rtc_regs[0] = ns % 60;
		rtc_regs[1] = nm % 60;
		rtc_regs[2] = nh % 24;
		rtc_regs[3] = (nd % 512) & 0xFF;
		rtc_regs[4] = change_bit(rtc_regs[4], (nd % 512) > 255, 0);
		rtc_regs[4] = change_bit(rtc_regs[4], nd > 511, 7);
	}
}

IMemory* Cartrige::get_memory_controller() const
{
	return memory_interface.get();
}

IDmaMemory* Cartrige::get_dma_controller() const
{
	return dma_interface;
}

bool Cartrige::is_cgb_ready() const
{
	const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);

	return (header->cgb_flag == 0x80) || (header->cgb_flag == 0xC0);
}

void Cartrige::serialize(std::ostream& stream)
{
	//TODO: update rtc regs before serialization
	stream << battery_ram << ram_size;
	stream.write(reinterpret_cast<char*>(ram.get()), sizeof(u8) * ram_size);
	stream.write(reinterpret_cast<char*>(rtc_regs), sizeof(u8) * 5);
}

void Cartrige::deserialize(std::istream & stream)
{
	stream >> battery_ram >> ram_size;
	stream.read(reinterpret_cast<char*>(ram.get()), sizeof(u8) * ram_size);
	stream.read(reinterpret_cast<char*>(rtc_regs), sizeof(u8) * 5);
}

void Cartrige::dispatch()
{
	rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);
	const u8 type = header->cartrige_type;
	const u32 rom_banks = 2 << header->rom_size;

	if (type == 0x00 || type == 0x08 || type == 0x09)
	{
		auto tmp = std::make_unique<NoMBC>(NoMBC(rom.get(), ram.get(), ram_size));
		dma_interface = tmp.get();
		memory_interface = std::move(tmp);
	}

	else if (in_range(type, 0x01, 0x03))
	{
		auto tmp = std::make_unique<MBC1>(MBC1(rom.get(), ram.get(), rom_banks, ram_size));
		dma_interface = tmp.get();
		memory_interface = std::move(tmp);
	}

	else if (in_range(type, 0x05, 0x06))
	{
		auto tmp = std::make_unique<MBC2>(MBC2(rom.get(), ram.get(), rom_banks, ram_size));
		dma_interface = tmp.get();
		memory_interface = std::move(tmp);
	}

	else if (in_range(type, 0x0F, 0x13))
	{
		auto tmp = std::make_unique<MBC3>(MBC3(rom.get(), ram.get(), (type <= 0x10 ? rtc_regs : nullptr), rom_banks, ram_size));
		dma_interface = tmp.get();
		memory_interface = std::move(tmp);
	}

	else if (in_range(type, 0x19, 0x1E))
	{
		auto tmp = std::make_unique<MBC5>(MBC5(rom.get(), ram.get(), rom_banks, ram_size));
		dma_interface = tmp.get();
		memory_interface = std::move(tmp);
	}

	else
		memory_interface = nullptr;
		//TODO: inform somehow that there is some unknown MBC
}
<commit_msg>changed mbc dispatching<commit_after>#include "cartrige.h"

struct rom_header
{
	u8 start_vector[4];
	u8 nintendo_logo[48];
	u8 game_title[11];
	u8 manufacturer_code[4];
	u8 cgb_flag;
	u8 new_license_code[2];
	u8 sgb_flag;
	u8 cartrige_type;
	u8 rom_size;
	u8 ram_size;
	u8 destination_code;
	u8 old_license_code;
	u8 rom_version;
	u8 checksum;
	u8 global_checksum[2];
};

bool in_range(u32 value, u32 begin, u32 end)
{
	return (value >= begin) && (value <= end);
}

void Cartrige::attach_rom(const u8* rom_ptr, u32 size)
{
	rom2 = std::make_pair(rom_ptr, size);
}

void Cartrige::attach_ram(u8* ram_ptr, u32 size)
{
	ram2 = std::make_pair(ram_ptr, size);
}

void Cartrige::attach_rtc(u8* rtc_ptr, u32 size)
{
	rtc2 = std::make_pair(rtc_ptr, size);
}

bool Cartrige::has_battery_ram() const
{
	if (std::get<0>(rom2) == nullptr)
		return false;

	const rom_header* header = reinterpret_cast<const rom_header*>(&std::get<0>(rom2)[0x100]);

	switch (header->cartrige_type)
	{
		case 0x03:
		case 0x06:
		case 0x09:
		case 0x0D:
		case 0x0F:
		case 0x10:
		case 0x13:
		case 0x1B:
		case 0x1E:
			return true;

		default:
			return false;
	}
}

u32 Cartrige::get_declared_ram_size() const
{
	static const u32 sizes[] = { 0, 0x800, 0x2000, 0x8000, 0x20000, 0x10000 };

	if (std::get<0>(rom2) == nullptr)
		return 0;

	const rom_header* header = reinterpret_cast<const rom_header*>(&std::get<0>(rom2)[0x100]);

	//MBC2 has always header->ram_size == 0, but it has 512 bytes actually!
	if (in_range(header->cartrige_type, 0x05, 0x06))
		return 512;

	else
		return (header->ram_size > 5) ? 0 : sizes[header->ram_size];
}

bool Cartrige::has_rtc() const
{
	if (std::get<0>(rom2) == nullptr)
		return false;

	const rom_header* header = reinterpret_cast<const rom_header*>(&std::get<0>(rom2)[0x100]);
	return in_range(header->cartrige_type, 0xF, 0x10);
}

Cartrige::~Cartrige()
{
	const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);

	if (battery_ram)
		save_ram_callback(ram.get(), ram_size);

	if (in_range(header->cartrige_type, 0x0F, 0x10))
	{
		memory_interface.reset(); //make sure that MBC3 update rtc_regs

		auto epoch = std::chrono::system_clock::now().time_since_epoch();
		auto cur_timestamp = std::chrono::duration_cast<std::chrono::seconds>(epoch);

		save_rtc_callback(cur_timestamp, rtc_regs, 5);
	}
}

bool Cartrige::load_cartrige(std::ifstream& cart, std::ifstream& ram, std::ifstream& rtc)
{
	if (!cart.is_open())
		return false;

	cart.seekg(0, std::ios_base::end);
	size_t size = cart.tellg();
	cart.seekg(0, std::ios_base::beg);

	rom = std::make_unique<u8[]>(size);
	cart.read(reinterpret_cast<char*>(rom.get()), size);

	attach_rom(rom.get(), size);

	load_or_create_ram(ram);
	load_rtc(rtc);

	dispatch();

	return true;
}

std::string Cartrige::get_name() const
{
    const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);
    return std::string(std::begin(header->game_title), std::end(header->game_title));
}

void Cartrige::attach_endpoints(function<void(const u8*, u32)> ram_save, function<void(std::chrono::seconds, const u8*, u32)> rtc_save)
{
	save_ram_callback = ram_save;
	save_rtc_callback = rtc_save;
}

void Cartrige::load_or_create_ram(std::ifstream& ram_file)
{
	ram_size = get_declared_ram_size();
	ram = ram_size ? std::make_unique<u8[]>(ram_size) : nullptr;

	battery_ram = has_battery_ram();

	if (battery_ram && ram_file.is_open())
		ram_file.read(reinterpret_cast<char*>(ram.get()), ram_size);
}

void Cartrige::load_rtc(std::ifstream& rtc_file)
{
	if (has_rtc() && rtc_file.is_open())
	{
		i64 saved_timestamp;
		rtc_file >> saved_timestamp;
		rtc_file.read(reinterpret_cast<char*>(rtc_regs), sizeof(u8) * 5);

		auto epoch = std::chrono::system_clock::now().time_since_epoch();
		auto cur_timestamp = std::chrono::duration_cast<std::chrono::seconds>(epoch);
		auto delta = cur_timestamp.count() - saved_timestamp;

		if (delta <= 0 || check_bit(rtc_regs[4], 6))
			return;

		auto ns = rtc_regs[0] + delta;
		auto nm = rtc_regs[1] + ns / 60;
		auto nh = rtc_regs[2] + nm / 60;
		auto nd = (((rtc_regs[4] & 1) << 8) | rtc_regs[3]) + nh / 24;

		rtc_regs[0] = ns % 60;
		rtc_regs[1] = nm % 60;
		rtc_regs[2] = nh % 24;
		rtc_regs[3] = (nd % 512) & 0xFF;
		rtc_regs[4] = change_bit(rtc_regs[4], (nd % 512) > 255, 0);
		rtc_regs[4] = change_bit(rtc_regs[4], nd > 511, 7);
	}
}

IMemory* Cartrige::get_memory_controller() const
{
	return memory_interface.get();
}

IDmaMemory* Cartrige::get_dma_controller() const
{
	return dma_interface;
}

bool Cartrige::is_cgb_ready() const
{
	const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);

	return (header->cgb_flag == 0x80) || (header->cgb_flag == 0xC0);
}

void Cartrige::serialize(std::ostream& stream)
{
	//TODO: update rtc regs before serialization
	stream << battery_ram << ram_size;
	stream.write(reinterpret_cast<char*>(ram.get()), sizeof(u8) * ram_size);
	stream.write(reinterpret_cast<char*>(rtc_regs), sizeof(u8) * 5);
}

void Cartrige::deserialize(std::istream & stream)
{
	stream >> battery_ram >> ram_size;
	stream.read(reinterpret_cast<char*>(ram.get()), sizeof(u8) * ram_size);
	stream.read(reinterpret_cast<char*>(rtc_regs), sizeof(u8) * 5);
}

void Cartrige::dispatch()
{
	const u8* rom_ptr = std::get<0>(rom2);
	const rom_header* header = reinterpret_cast<const rom_header*>(&rom_ptr[0x100]);
	const u8 type = header->cartrige_type;
	const u32 rom_banks = 2 << header->rom_size;

	if (type == 0x00 || type == 0x08 || type == 0x09)
	{
		auto tmp = std::make_unique<NoMBC>(NoMBC(rom_ptr, ram.get(), ram_size));
		dma_interface = tmp.get();
		memory_interface = std::move(tmp);
	}

	else if (in_range(type, 0x01, 0x03))
	{
		auto tmp = std::make_unique<MBC1>(MBC1(rom_ptr, ram.get(), rom_banks, ram_size));
		dma_interface = tmp.get();
		memory_interface = std::move(tmp);
	}

	else if (in_range(type, 0x05, 0x06))
	{
		auto tmp = std::make_unique<MBC2>(MBC2(rom_ptr, ram.get(), rom_banks, ram_size));
		dma_interface = tmp.get();
		memory_interface = std::move(tmp);
	}

	else if (in_range(type, 0x0F, 0x13))
	{
		auto tmp = std::make_unique<MBC3>(MBC3(rom_ptr, ram.get(), (type <= 0x10 ? rtc_regs : nullptr), rom_banks, ram_size));
		dma_interface = tmp.get();
		memory_interface = std::move(tmp);
	}

	else if (in_range(type, 0x19, 0x1E))
	{
		auto tmp = std::make_unique<MBC5>(MBC5(rom_ptr, ram.get(), rom_banks, ram_size));
		dma_interface = tmp.get();
		memory_interface = std::move(tmp);
	}

	else
		memory_interface = nullptr;
		//TODO: inform somehow that there is some unknown MBC
}
<|endoftext|>


<commit_before><commit_msg>Added _absoluteRotation attribute<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: fumeasur.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2004-08-04 08:54:17 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#include "fumeasur.hxx"

//CHINA001 #include <svx/measure.hxx>
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif

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

namespace sd {

TYPEINIT1( FuMeasureDlg, FuPoor );

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

FuMeasureDlg::FuMeasureDlg (
    ViewShell* pViewSh,
    ::sd::Window* pWin,
    ::sd::View* pView,
    SdDrawDocument* pDoc,
    SfxRequest& rReq)
    : FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
    SfxItemSet aNewAttr( pDoc->GetPool() );
    pView->GetAttributes( aNewAttr );

    const SfxItemSet* pArgs = rReq.GetArgs();

    ::std::auto_ptr<AbstractSfxSingleTabDialog> pDlg (NULL);
    if( !pArgs )
    {
        //CHINA001 SvxMeasureDialog* pDlg = new SvxMeasureDialog( NULL, aNewAttr, pView );
        SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
        DBG_ASSERT(pFact, "Dialogdiet Factory fail!");//CHINA001
        pDlg.reset (pFact->CreateSfxSingleTabDialog( NULL,
                aNewAttr,
                pView,
                ResId(RID_SVXPAGE_MEASURE)));
        DBG_ASSERT(pDlg.get()!=NULL, "Dialogdiet fail!");//CHINA001

        USHORT nResult = pDlg->Execute();

        switch( nResult )
        {
            case RET_OK:
            {
                pArgs = pDlg->GetOutputItemSet();
                rReq.Done( *pArgs );
            }
            break;

            default:
                return; // Abbruch
        }
    }
    pView->SetAttributes( *pArgs );
}

} // end of namespace sd
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.394); FILE MERGED 2005/09/05 13:22:18 rt 1.4.394.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fumeasur.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 04:44:37 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#pragma hdrstop

#include "fumeasur.hxx"

//CHINA001 #include <svx/measure.hxx>
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif

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

namespace sd {

TYPEINIT1( FuMeasureDlg, FuPoor );

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

FuMeasureDlg::FuMeasureDlg (
    ViewShell* pViewSh,
    ::sd::Window* pWin,
    ::sd::View* pView,
    SdDrawDocument* pDoc,
    SfxRequest& rReq)
    : FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
    SfxItemSet aNewAttr( pDoc->GetPool() );
    pView->GetAttributes( aNewAttr );

    const SfxItemSet* pArgs = rReq.GetArgs();

    ::std::auto_ptr<AbstractSfxSingleTabDialog> pDlg (NULL);
    if( !pArgs )
    {
        //CHINA001 SvxMeasureDialog* pDlg = new SvxMeasureDialog( NULL, aNewAttr, pView );
        SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
        DBG_ASSERT(pFact, "Dialogdiet Factory fail!");//CHINA001
        pDlg.reset (pFact->CreateSfxSingleTabDialog( NULL,
                aNewAttr,
                pView,
                ResId(RID_SVXPAGE_MEASURE)));
        DBG_ASSERT(pDlg.get()!=NULL, "Dialogdiet fail!");//CHINA001

        USHORT nResult = pDlg->Execute();

        switch( nResult )
        {
            case RET_OK:
            {
                pArgs = pDlg->GetOutputItemSet();
                rReq.Done( *pArgs );
            }
            break;

            default:
                return; // Abbruch
        }
    }
    pView->SetAttributes( *pArgs );
}

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


<commit_before>/*************************************************************************
 *
 *  $RCSfile: fuprlout.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: kz $ $Date: 2004-10-04 18:33:21 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#include "fuprlout.hxx"

#ifndef _SV_WRKWIN_HXX
#include <vcl/wrkwin.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFXSMPLHINT_HXX //autogen
#include <svtools/smplhint.hxx>
#endif
#ifndef _SFXITEMPOOL_HXX //autogen
#include <svtools/itempool.hxx>
#endif
#include <sot/storage.hxx>
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVDUNDO_HXX //autogen
#include <svx/svdundo.hxx>
#endif

#include <sfx2/viewfrm.hxx>

#include "drawdoc.hxx"
#include "sdpage.hxx"
#include "pres.hxx"
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif
#ifndef SD_FRAMW_VIEW_HXX
#include "FrameView.hxx"
#endif
#include "stlpool.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#include "glob.hrc"
#include "glob.hxx"
#include "strings.hrc"
#include "strmname.h"
#include "app.hrc"
#include "DrawDocShell.hxx"
#include "unprlout.hxx"
#include "unchss.hxx"
#include "unmovss.hxx"
#include "sdattr.hxx"
#include "sdresid.hxx"
//CHINA001 #include "sdpreslt.hxx"
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
#include "eetext.hxx"
#include <svx/editdata.hxx>
#include "sdabstdlg.hxx" //CHINA001
#include "sdpreslt.hrc" //CHINA001
namespace sd {

#ifndef SO2_DECL_SVSTORAGE_DEFINED
#define SO2_DECL_SVSTORAGE_DEFINED
SO2_DECL_REF(SvStorage)
#endif

TYPEINIT1( FuPresentationLayout, FuPoor );

#define POOL_BUFFER_SIZE        (USHORT)32768
#define DOCUMENT_BUFFER_SIZE    (USHORT)32768
#define DOCUMENT_TOKEN (sal_Unicode('#'))

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

FuPresentationLayout::FuPresentationLayout (
    ViewShell* pViewSh,
    ::sd::Window* pWin,
    ::sd::View* pView,
    SdDrawDocument* pDoc,
    SfxRequest& rReq)
    : FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
    // damit nicht Objekte, die gerade editiert werden oder selektiert
    // sind , verschwinden
    pView->EndTextEdit();

    USHORT nPgViewCount = pView->GetPageViewCount();
    for (USHORT nPgView = 0; nPgView < nPgViewCount; nPgView++)
    {
        pView->UnmarkAll();
    }

    BOOL bError = FALSE;

    // die aktive Seite ermitteln
    USHORT nSelectedPage = SDRPAGE_NOTFOUND;
    for (USHORT nPage = 0; nPage < pDoc->GetSdPageCount(PK_STANDARD); nPage++)
    {
        if (pDoc->GetSdPage(nPage, PK_STANDARD)->IsSelected())
        {
            nSelectedPage = nPage;
            break;
        }
    }

    DBG_ASSERT(nSelectedPage != SDRPAGE_NOTFOUND, "keine selektierte Seite");
    SdPage* pSelectedPage = pDoc->GetSdPage(nSelectedPage, PK_STANDARD);
    String aOldPageLayoutName(pSelectedPage->GetLayoutName());
    String aOldLayoutName(aOldPageLayoutName);
    aOldLayoutName.Erase(aOldLayoutName.SearchAscii(SD_LT_SEPARATOR));

    // wenn wir auf einer Masterpage sind, gelten die Aenderungen fuer alle
    // Seiten und Notizseiten, die das betreffende Layout benutzen
    BOOL bOnMaster = FALSE;
    if (pViewSh->ISA(DrawViewShell))
    {
        EditMode eEditMode =
            static_cast<DrawViewShell*>(pViewSh)->GetEditMode();
        if (eEditMode == EM_MASTERPAGE)
            bOnMaster = TRUE;
    }
    BOOL bMasterPage = bOnMaster;
    BOOL bCheckMasters = FALSE;

    // Dialog aufrufen
    BOOL   bLoad = FALSE;           // tauchen neue Masterpages auf?
    String aFile;
    SfxItemSet aSet(pDoc->GetPool(), ATTR_PRESLAYOUT_START, ATTR_PRESLAYOUT_END);

    aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_LOAD, bLoad));
    aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_MASTER_PAGE, bMasterPage ) );
    aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_CHECK_MASTERS, bCheckMasters ) );
    aSet.Put( SfxStringItem( ATTR_PRESLAYOUT_NAME, aOldLayoutName));

    //CHINA001 SdPresLayoutDlg* pDlg = new SdPresLayoutDlg( pDocSh, pViewSh, NULL, aSet);
    SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();//CHINA001
    DBG_ASSERT(pFact, "SdAbstractDialogFactory fail!");//CHINA001
    AbstractSdPresLayoutDlg* pDlg = pFact->CreateSdPresLayoutDlg(ResId( DLG_PRESLT ), pDocSh, pViewSh, NULL, aSet );
    DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
    USHORT nResult = pDlg->Execute();

    switch (nResult)
    {
        case RET_OK:
        {
            pDlg->GetAttr(aSet);
            if (aSet.GetItemState(ATTR_PRESLAYOUT_LOAD) == SFX_ITEM_SET)
                bLoad = ((SfxBoolItem&)aSet.Get(ATTR_PRESLAYOUT_LOAD)).GetValue();
            if( aSet.GetItemState( ATTR_PRESLAYOUT_MASTER_PAGE ) == SFX_ITEM_SET )
                bMasterPage = ( (SfxBoolItem&) aSet.Get( ATTR_PRESLAYOUT_MASTER_PAGE ) ).GetValue();
            if( aSet.GetItemState( ATTR_PRESLAYOUT_CHECK_MASTERS ) == SFX_ITEM_SET )
                bCheckMasters = ( (SfxBoolItem&) aSet.Get( ATTR_PRESLAYOUT_CHECK_MASTERS ) ).GetValue();
            if (aSet.GetItemState(ATTR_PRESLAYOUT_NAME) == SFX_ITEM_SET)
                aFile = ((SfxStringItem&)aSet.Get(ATTR_PRESLAYOUT_NAME)).GetValue();
        }
        break;

        default:
            bError = TRUE;
    }
    delete pDlg;

    if (!bError)
    {
        pDocSh->SetWaitCursor( TRUE );

        // Hier werden nur Masterpages ausgewechselt, d.h. die aktuelle Seite
        // bleibt aktuell. Damit beim Ein- und Ausfuegen der Masterpages nicht
        // dauernd via PageOrderChangedHint die Methode ResetActualPage gerufen
        // wird, wird jetzt blockiert.
        // That isn't quitely right. If the masterpageview is active and you are
        // removing a masterpage, it's possible that you are removing the
        // current masterpage. So you have to call ResetActualPage !
        if( pViewShell->ISA(DrawViewShell) && !bCheckMasters )
            static_cast<DrawView*>(pView)->BlockPageOrderChangedHint(TRUE);

        if (bLoad)
        {
            String aFileName = aFile.GetToken( 0, DOCUMENT_TOKEN );
            SdDrawDocument* pTempDoc = pDoc->OpenBookmarkDoc( aFileName );

            // #69581: If I chosed the standard-template I got no filename and so I get no
            //         SdDrawDocument-Pointer. But the method SetMasterPage is able to handle
            //         a NULL-pointer as a Standard-template ( look at SdDrawDocument::SetMasterPage )
            String aLayoutName;
            if( pTempDoc )
                aLayoutName = aFile.GetToken( 1, DOCUMENT_TOKEN );

            pDoc->SetMasterPage(nSelectedPage, aLayoutName, pTempDoc, bMasterPage, bCheckMasters);
            pDoc->CloseBookmarkDoc();
        }
        else
        {
            // MasterPage mit dem LayoutNamen aFile aus aktuellem Doc verwenden
            pDoc->SetMasterPage(nSelectedPage, aFile, pDoc, bMasterPage, bCheckMasters);
        }

        // Blockade wieder aufheben
        if (pViewShell->ISA(DrawViewShell) && !bCheckMasters )
            static_cast<DrawView*>(pView)->BlockPageOrderChangedHint(FALSE);

        /*************************************************************************
        |* Falls dargestellte Masterpage sichtbar war, neu darstellen
        \************************************************************************/
        if (!bError && nSelectedPage != SDRPAGE_NOTFOUND)
        {
            if (bOnMaster)
            {
                if (pViewShell->ISA(DrawViewShell))
                {
                    ::sd::View* pView =
                          static_cast<DrawViewShell*>(pViewShell)->GetView();
                    USHORT nPgNum = pSelectedPage->TRG_GetMasterPage().GetPageNum();

                    if (static_cast<DrawViewShell*>(pViewShell)->GetPageKind() == PK_NOTES)
                        nPgNum++;

                    pView->HideAllPages();
                    pView->ShowMasterPagePgNum(nPgNum, Point());
                }

                // damit TabBar aktualisiert wird
                pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_MASTERPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
            }
            else
            {
                pSelectedPage->SetAutoLayout(pSelectedPage->GetAutoLayout());
            }
        }

        // fake a mode change to repaint the page tab bar
        if( pViewShell && pViewShell->ISA( DrawViewShell ) )
        {
            DrawViewShell* pDrawViewSh =
                static_cast<DrawViewShell*>(pViewShell);
            EditMode eMode = pDrawViewSh->GetEditMode();
            BOOL bLayer = pDrawViewSh->IsLayerModeActive();
            pDrawViewSh->ChangeEditMode( eMode, !bLayer );
            pDrawViewSh->ChangeEditMode( eMode, bLayer );
        }

        pDocSh->SetWaitCursor( FALSE );
    }
}

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

FuPresentationLayout::~FuPresentationLayout()
{
}

/*************************************************************************
|*
|* Layoutvorlage von einem StyleSheetPool in einen anderen uebertragen
|*
\************************************************************************/

void FuPresentationLayout::TransferLayoutTemplate(String aFromName,
                                                  String aToName,
                                                  SfxStyleSheetBasePool* pFrom,
                                                  SfxStyleSheetBasePool* pTo)
{
    SfxStyleSheetBase* pHis = pFrom->Find(aFromName,SD_LT_FAMILY);
    SfxStyleSheetBase* pMy  = pTo->Find(aToName, SD_LT_FAMILY);

    DBG_ASSERT(pHis, "neue Layoutvorlage nicht gefunden");

    // gibt's noch nicht: neu anlegen
    if (!pMy)
    {
        pMy = &(pTo->Make(aToName, SD_LT_FAMILY));
    }

    // Inhalte neu setzen
    if (pHis)
        pMy->GetItemSet().Set(pHis->GetItemSet());
}

} // end of namespace sd
<commit_msg>INTEGRATION: CWS ooo19126 (1.9.362); FILE MERGED 2005/09/05 13:22:22 rt 1.9.362.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fuprlout.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 04:49:20 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#pragma hdrstop

#include "fuprlout.hxx"

#ifndef _SV_WRKWIN_HXX
#include <vcl/wrkwin.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFXSMPLHINT_HXX //autogen
#include <svtools/smplhint.hxx>
#endif
#ifndef _SFXITEMPOOL_HXX //autogen
#include <svtools/itempool.hxx>
#endif
#include <sot/storage.hxx>
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVDUNDO_HXX //autogen
#include <svx/svdundo.hxx>
#endif

#include <sfx2/viewfrm.hxx>

#include "drawdoc.hxx"
#include "sdpage.hxx"
#include "pres.hxx"
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif
#ifndef SD_FRAMW_VIEW_HXX
#include "FrameView.hxx"
#endif
#include "stlpool.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#include "glob.hrc"
#include "glob.hxx"
#include "strings.hrc"
#include "strmname.h"
#include "app.hrc"
#include "DrawDocShell.hxx"
#include "unprlout.hxx"
#include "unchss.hxx"
#include "unmovss.hxx"
#include "sdattr.hxx"
#include "sdresid.hxx"
//CHINA001 #include "sdpreslt.hxx"
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
#include "eetext.hxx"
#include <svx/editdata.hxx>
#include "sdabstdlg.hxx" //CHINA001
#include "sdpreslt.hrc" //CHINA001
namespace sd {

#ifndef SO2_DECL_SVSTORAGE_DEFINED
#define SO2_DECL_SVSTORAGE_DEFINED
SO2_DECL_REF(SvStorage)
#endif

TYPEINIT1( FuPresentationLayout, FuPoor );

#define POOL_BUFFER_SIZE        (USHORT)32768
#define DOCUMENT_BUFFER_SIZE    (USHORT)32768
#define DOCUMENT_TOKEN (sal_Unicode('#'))

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

FuPresentationLayout::FuPresentationLayout (
    ViewShell* pViewSh,
    ::sd::Window* pWin,
    ::sd::View* pView,
    SdDrawDocument* pDoc,
    SfxRequest& rReq)
    : FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
    // damit nicht Objekte, die gerade editiert werden oder selektiert
    // sind , verschwinden
    pView->EndTextEdit();

    USHORT nPgViewCount = pView->GetPageViewCount();
    for (USHORT nPgView = 0; nPgView < nPgViewCount; nPgView++)
    {
        pView->UnmarkAll();
    }

    BOOL bError = FALSE;

    // die aktive Seite ermitteln
    USHORT nSelectedPage = SDRPAGE_NOTFOUND;
    for (USHORT nPage = 0; nPage < pDoc->GetSdPageCount(PK_STANDARD); nPage++)
    {
        if (pDoc->GetSdPage(nPage, PK_STANDARD)->IsSelected())
        {
            nSelectedPage = nPage;
            break;
        }
    }

    DBG_ASSERT(nSelectedPage != SDRPAGE_NOTFOUND, "keine selektierte Seite");
    SdPage* pSelectedPage = pDoc->GetSdPage(nSelectedPage, PK_STANDARD);
    String aOldPageLayoutName(pSelectedPage->GetLayoutName());
    String aOldLayoutName(aOldPageLayoutName);
    aOldLayoutName.Erase(aOldLayoutName.SearchAscii(SD_LT_SEPARATOR));

    // wenn wir auf einer Masterpage sind, gelten die Aenderungen fuer alle
    // Seiten und Notizseiten, die das betreffende Layout benutzen
    BOOL bOnMaster = FALSE;
    if (pViewSh->ISA(DrawViewShell))
    {
        EditMode eEditMode =
            static_cast<DrawViewShell*>(pViewSh)->GetEditMode();
        if (eEditMode == EM_MASTERPAGE)
            bOnMaster = TRUE;
    }
    BOOL bMasterPage = bOnMaster;
    BOOL bCheckMasters = FALSE;

    // Dialog aufrufen
    BOOL   bLoad = FALSE;           // tauchen neue Masterpages auf?
    String aFile;
    SfxItemSet aSet(pDoc->GetPool(), ATTR_PRESLAYOUT_START, ATTR_PRESLAYOUT_END);

    aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_LOAD, bLoad));
    aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_MASTER_PAGE, bMasterPage ) );
    aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_CHECK_MASTERS, bCheckMasters ) );
    aSet.Put( SfxStringItem( ATTR_PRESLAYOUT_NAME, aOldLayoutName));

    //CHINA001 SdPresLayoutDlg* pDlg = new SdPresLayoutDlg( pDocSh, pViewSh, NULL, aSet);
    SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();//CHINA001
    DBG_ASSERT(pFact, "SdAbstractDialogFactory fail!");//CHINA001
    AbstractSdPresLayoutDlg* pDlg = pFact->CreateSdPresLayoutDlg(ResId( DLG_PRESLT ), pDocSh, pViewSh, NULL, aSet );
    DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
    USHORT nResult = pDlg->Execute();

    switch (nResult)
    {
        case RET_OK:
        {
            pDlg->GetAttr(aSet);
            if (aSet.GetItemState(ATTR_PRESLAYOUT_LOAD) == SFX_ITEM_SET)
                bLoad = ((SfxBoolItem&)aSet.Get(ATTR_PRESLAYOUT_LOAD)).GetValue();
            if( aSet.GetItemState( ATTR_PRESLAYOUT_MASTER_PAGE ) == SFX_ITEM_SET )
                bMasterPage = ( (SfxBoolItem&) aSet.Get( ATTR_PRESLAYOUT_MASTER_PAGE ) ).GetValue();
            if( aSet.GetItemState( ATTR_PRESLAYOUT_CHECK_MASTERS ) == SFX_ITEM_SET )
                bCheckMasters = ( (SfxBoolItem&) aSet.Get( ATTR_PRESLAYOUT_CHECK_MASTERS ) ).GetValue();
            if (aSet.GetItemState(ATTR_PRESLAYOUT_NAME) == SFX_ITEM_SET)
                aFile = ((SfxStringItem&)aSet.Get(ATTR_PRESLAYOUT_NAME)).GetValue();
        }
        break;

        default:
            bError = TRUE;
    }
    delete pDlg;

    if (!bError)
    {
        pDocSh->SetWaitCursor( TRUE );

        // Hier werden nur Masterpages ausgewechselt, d.h. die aktuelle Seite
        // bleibt aktuell. Damit beim Ein- und Ausfuegen der Masterpages nicht
        // dauernd via PageOrderChangedHint die Methode ResetActualPage gerufen
        // wird, wird jetzt blockiert.
        // That isn't quitely right. If the masterpageview is active and you are
        // removing a masterpage, it's possible that you are removing the
        // current masterpage. So you have to call ResetActualPage !
        if( pViewShell->ISA(DrawViewShell) && !bCheckMasters )
            static_cast<DrawView*>(pView)->BlockPageOrderChangedHint(TRUE);

        if (bLoad)
        {
            String aFileName = aFile.GetToken( 0, DOCUMENT_TOKEN );
            SdDrawDocument* pTempDoc = pDoc->OpenBookmarkDoc( aFileName );

            // #69581: If I chosed the standard-template I got no filename and so I get no
            //         SdDrawDocument-Pointer. But the method SetMasterPage is able to handle
            //         a NULL-pointer as a Standard-template ( look at SdDrawDocument::SetMasterPage )
            String aLayoutName;
            if( pTempDoc )
                aLayoutName = aFile.GetToken( 1, DOCUMENT_TOKEN );

            pDoc->SetMasterPage(nSelectedPage, aLayoutName, pTempDoc, bMasterPage, bCheckMasters);
            pDoc->CloseBookmarkDoc();
        }
        else
        {
            // MasterPage mit dem LayoutNamen aFile aus aktuellem Doc verwenden
            pDoc->SetMasterPage(nSelectedPage, aFile, pDoc, bMasterPage, bCheckMasters);
        }

        // Blockade wieder aufheben
        if (pViewShell->ISA(DrawViewShell) && !bCheckMasters )
            static_cast<DrawView*>(pView)->BlockPageOrderChangedHint(FALSE);

        /*************************************************************************
        |* Falls dargestellte Masterpage sichtbar war, neu darstellen
        \************************************************************************/
        if (!bError && nSelectedPage != SDRPAGE_NOTFOUND)
        {
            if (bOnMaster)
            {
                if (pViewShell->ISA(DrawViewShell))
                {
                    ::sd::View* pView =
                          static_cast<DrawViewShell*>(pViewShell)->GetView();
                    USHORT nPgNum = pSelectedPage->TRG_GetMasterPage().GetPageNum();

                    if (static_cast<DrawViewShell*>(pViewShell)->GetPageKind() == PK_NOTES)
                        nPgNum++;

                    pView->HideAllPages();
                    pView->ShowMasterPagePgNum(nPgNum, Point());
                }

                // damit TabBar aktualisiert wird
                pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_MASTERPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
            }
            else
            {
                pSelectedPage->SetAutoLayout(pSelectedPage->GetAutoLayout());
            }
        }

        // fake a mode change to repaint the page tab bar
        if( pViewShell && pViewShell->ISA( DrawViewShell ) )
        {
            DrawViewShell* pDrawViewSh =
                static_cast<DrawViewShell*>(pViewShell);
            EditMode eMode = pDrawViewSh->GetEditMode();
            BOOL bLayer = pDrawViewSh->IsLayerModeActive();
            pDrawViewSh->ChangeEditMode( eMode, !bLayer );
            pDrawViewSh->ChangeEditMode( eMode, bLayer );
        }

        pDocSh->SetWaitCursor( FALSE );
    }
}

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

FuPresentationLayout::~FuPresentationLayout()
{
}

/*************************************************************************
|*
|* Layoutvorlage von einem StyleSheetPool in einen anderen uebertragen
|*
\************************************************************************/

void FuPresentationLayout::TransferLayoutTemplate(String aFromName,
                                                  String aToName,
                                                  SfxStyleSheetBasePool* pFrom,
                                                  SfxStyleSheetBasePool* pTo)
{
    SfxStyleSheetBase* pHis = pFrom->Find(aFromName,SD_LT_FAMILY);
    SfxStyleSheetBase* pMy  = pTo->Find(aToName, SD_LT_FAMILY);

    DBG_ASSERT(pHis, "neue Layoutvorlage nicht gefunden");

    // gibt's noch nicht: neu anlegen
    if (!pMy)
    {
        pMy = &(pTo->Make(aToName, SD_LT_FAMILY));
    }

    // Inhalte neu setzen
    if (pHis)
        pMy->GetItemSet().Set(pHis->GetItemSet());
}

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