<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: svdovirt.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SVDOVIRT_HXX
#define _SVDOVIRT_HXX

#include <svx/svdobj.hxx>
#include "svx/svxdllapi.h"

////////////////////////////////////////////////////////////////////////////////////////////////////
//
//   SdrVirtObj
//
// Achtung! Das virtuelle Objekt ist noch nicht bis in alle Feinheiten
// durchprogrammiert und getestet. Z.Zt. kommt es nur in abgeleiteter
// beim Writer zum Einsatz.
//
////////////////////////////////////////////////////////////////////////////////////////////////////

class SVX_DLLPUBLIC SdrVirtObj : public SdrObject
{
public:
    virtual sdr::properties::BaseProperties& GetProperties() const;

private:
    // AW, OD 2004-05-03 #i27224#
    virtual sdr::contact::ViewContact* CreateObjectSpecificViewContact();

protected:
    SdrObject&                  rRefObj; // Referenziertes Zeichenobjekt
    Rectangle                   aSnapRect;

protected:
    virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType);

    virtual SdrObjGeoData* NewGeoData() const;
    virtual void SaveGeoData(SdrObjGeoData& rGeo) const;
    virtual void RestGeoData(const SdrObjGeoData& rGeo);

public:
    TYPEINFO();
    SdrVirtObj(SdrObject& rNewObj);
    SdrVirtObj(SdrObject& rNewObj, const Point& rAnchorPos);
    virtual ~SdrVirtObj();
    virtual SdrObject& ReferencedObj();
    virtual const SdrObject& GetReferencedObj() const;
    virtual void NbcSetAnchorPos(const Point& rAnchorPos);
    virtual void SetModel(SdrModel* pNewModel);

    virtual void TakeObjInfo(SdrObjTransformInfoRec& rInfo) const;
    virtual UINT32 GetObjInventor() const;
    virtual UINT16 GetObjIdentifier() const;
    virtual SdrObjList* GetSubList() const;

    virtual const Rectangle& GetCurrentBoundRect() const;
    virtual const Rectangle& GetLastBoundRect() const;
    virtual void RecalcBoundRect();
    virtual void SetChanged();
    virtual sal_Bool DoPaintObject(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
    virtual SdrObject* CheckHit(const Point& rPnt, USHORT nTol, const SetOfByte* pVisiLayer) const;
    virtual SdrObject* Clone() const;
    virtual void operator=(const SdrObject& rObj);

    virtual void TakeObjNameSingul(String& rName) const;
    virtual void TakeObjNamePlural(String& rName) const;

    virtual basegfx::B2DPolyPolygon TakeXorPoly(sal_Bool bDetail) const;
    virtual sal_uInt32 GetHdlCount() const;
    virtual SdrHdl* GetHdl(sal_uInt32 nHdlNum) const;
    virtual sal_uInt32 GetPlusHdlCount(const SdrHdl& rHdl) const;
    virtual SdrHdl* GetPlusHdl(const SdrHdl& rHdl, sal_uInt32 nPlNum) const;
    virtual void AddToHdlList(SdrHdlList& rHdlList) const;
    virtual FASTBOOL HasSpecialDrag() const;
    virtual FASTBOOL BegDrag(SdrDragStat& rDrag) const;
    virtual FASTBOOL MovDrag(SdrDragStat& rDrag) const;
    virtual FASTBOOL EndDrag(SdrDragStat& rDrag);
    virtual void BrkDrag(SdrDragStat& rDrag) const;

    virtual String GetDragComment(const SdrDragStat& rDrag, FASTBOOL bUndoDragComment, FASTBOOL bCreateComment) const;
    virtual basegfx::B2DPolyPolygon TakeDragPoly(const SdrDragStat& rDrag) const;

    virtual FASTBOOL BegCreate(SdrDragStat& rStat);
    virtual FASTBOOL MovCreate(SdrDragStat& rStat);
    virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd);
    virtual FASTBOOL BckCreate(SdrDragStat& rStat);
    virtual void BrkCreate(SdrDragStat& rStat);
    virtual basegfx::B2DPolyPolygon TakeCreatePoly(const SdrDragStat& rDrag) const;

    virtual void NbcMove(const Size& rSiz);
    virtual void NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
    virtual void NbcRotate(const Point& rRef, long nWink, double sn, double cs);
    virtual void NbcMirror(const Point& rRef1, const Point& rRef2);
    virtual void NbcShear(const Point& rRef, long nWink, double tn, FASTBOOL bVShear);

    virtual void Move(const Size& rSiz);
    virtual void Resize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
    virtual void Rotate(const Point& rRef, long nWink, double sn, double cs);
    virtual void Mirror(const Point& rRef1, const Point& rRef2);
    virtual void Shear(const Point& rRef, long nWink, double tn, FASTBOOL bVShear);

    virtual void RecalcSnapRect();
    virtual const Rectangle& GetSnapRect() const;
    virtual void SetSnapRect(const Rectangle& rRect);
    virtual void NbcSetSnapRect(const Rectangle& rRect);

    virtual const Rectangle& GetLogicRect() const;
    virtual void SetLogicRect(const Rectangle& rRect);
    virtual void NbcSetLogicRect(const Rectangle& rRect);

    virtual long GetRotateAngle() const;
    virtual long GetShearAngle(FASTBOOL bVertical=FALSE) const;

    virtual sal_uInt32 GetSnapPointCount() const;
    virtual Point GetSnapPoint(sal_uInt32 i) const;

    virtual sal_Bool IsPolyObj() const;
    virtual sal_uInt32 GetPointCount() const;
    virtual Point GetPoint(sal_uInt32 i) const;
    virtual void NbcSetPoint(const Point& rPnt, sal_uInt32 i);

    virtual SdrObjGeoData* GetGeoData() const;
    virtual void SetGeoData(const SdrObjGeoData& rGeo);

    virtual void NbcReformatText();
    virtual void ReformatText();

    virtual FASTBOOL HasMacro() const;
    virtual SdrObject* CheckMacroHit (const SdrObjMacroHitRec& rRec) const;
    virtual Pointer GetMacroPointer (const SdrObjMacroHitRec& rRec) const;
    virtual void PaintMacro (XOutputDevice& rXOut, const Rectangle& rDirtyRect, const SdrObjMacroHitRec& rRec) const;
    virtual FASTBOOL DoMacro (const SdrObjMacroHitRec& rRec);
    virtual XubString GetMacroPopupComment(const SdrObjMacroHitRec& rRec) const;

    // OD 30.06.2003 #108784# - virtual <GetOffset()> returns Point(0,0)
    // #i73248# for default SdrVirtObj, offset is aAnchor, not (0,0)
    virtual const Point GetOffset() const;
};

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

#endif //_SVDOVIRT_HXX

<commit_msg>INTEGRATION: CWS aw033 (1.2.76); FILE MERGED 2008/05/14 13:57:44 aw 1.2.76.3: RESYNC: (1.2-1.3); FILE MERGED 2008/01/29 10:27:14 aw 1.2.76.2: updated refresh for ActionChanged(), diverse removals 2008/01/22 12:29:05 aw 1.2.76.1: adaptions and 1st stripping<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: svdovirt.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SVDOVIRT_HXX
#define _SVDOVIRT_HXX

#include <svx/svdobj.hxx>
#include "svx/svxdllapi.h"

////////////////////////////////////////////////////////////////////////////////////////////////////
//
//   SdrVirtObj
//
// Achtung! Das virtuelle Objekt ist noch nicht bis in alle Feinheiten
// durchprogrammiert und getestet. Z.Zt. kommt es nur in abgeleiteter
// beim Writer zum Einsatz.
//
////////////////////////////////////////////////////////////////////////////////////////////////////

class SVX_DLLPUBLIC SdrVirtObj : public SdrObject
{
public:
    virtual sdr::properties::BaseProperties& GetProperties() const;

private:
    // AW, OD 2004-05-03 #i27224#
    virtual sdr::contact::ViewContact* CreateObjectSpecificViewContact();

protected:
    SdrObject&                  rRefObj; // Referenziertes Zeichenobjekt
    Rectangle                   aSnapRect;

protected:
    virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType);

    virtual SdrObjGeoData* NewGeoData() const;
    virtual void SaveGeoData(SdrObjGeoData& rGeo) const;
    virtual void RestGeoData(const SdrObjGeoData& rGeo);

public:
    TYPEINFO();
    SdrVirtObj(SdrObject& rNewObj);
    SdrVirtObj(SdrObject& rNewObj, const Point& rAnchorPos);
    virtual ~SdrVirtObj();
    virtual SdrObject& ReferencedObj();
    virtual const SdrObject& GetReferencedObj() const;
    virtual void NbcSetAnchorPos(const Point& rAnchorPos);
    virtual void SetModel(SdrModel* pNewModel);

    virtual void TakeObjInfo(SdrObjTransformInfoRec& rInfo) const;
    virtual UINT32 GetObjInventor() const;
    virtual UINT16 GetObjIdentifier() const;
    virtual SdrObjList* GetSubList() const;

    virtual const Rectangle& GetCurrentBoundRect() const;
    virtual const Rectangle& GetLastBoundRect() const;
    virtual void RecalcBoundRect();
    virtual void SetChanged();
    virtual SdrObject* CheckHit(const Point& rPnt, USHORT nTol, const SetOfByte* pVisiLayer) const;
    virtual SdrObject* Clone() const;
    virtual void operator=(const SdrObject& rObj);

    virtual void TakeObjNameSingul(String& rName) const;
    virtual void TakeObjNamePlural(String& rName) const;

    virtual basegfx::B2DPolyPolygon TakeXorPoly(sal_Bool bDetail) const;
    virtual sal_uInt32 GetHdlCount() const;
    virtual SdrHdl* GetHdl(sal_uInt32 nHdlNum) const;
    virtual sal_uInt32 GetPlusHdlCount(const SdrHdl& rHdl) const;
    virtual SdrHdl* GetPlusHdl(const SdrHdl& rHdl, sal_uInt32 nPlNum) const;
    virtual void AddToHdlList(SdrHdlList& rHdlList) const;
    virtual FASTBOOL HasSpecialDrag() const;
    virtual FASTBOOL BegDrag(SdrDragStat& rDrag) const;
    virtual FASTBOOL MovDrag(SdrDragStat& rDrag) const;
    virtual FASTBOOL EndDrag(SdrDragStat& rDrag);
    virtual void BrkDrag(SdrDragStat& rDrag) const;

    virtual String GetDragComment(const SdrDragStat& rDrag, FASTBOOL bUndoDragComment, FASTBOOL bCreateComment) const;
    virtual basegfx::B2DPolyPolygon TakeDragPoly(const SdrDragStat& rDrag) const;

    virtual FASTBOOL BegCreate(SdrDragStat& rStat);
    virtual FASTBOOL MovCreate(SdrDragStat& rStat);
    virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd);
    virtual FASTBOOL BckCreate(SdrDragStat& rStat);
    virtual void BrkCreate(SdrDragStat& rStat);
    virtual basegfx::B2DPolyPolygon TakeCreatePoly(const SdrDragStat& rDrag) const;

    virtual void NbcMove(const Size& rSiz);
    virtual void NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
    virtual void NbcRotate(const Point& rRef, long nWink, double sn, double cs);
    virtual void NbcMirror(const Point& rRef1, const Point& rRef2);
    virtual void NbcShear(const Point& rRef, long nWink, double tn, FASTBOOL bVShear);

    virtual void Move(const Size& rSiz);
    virtual void Resize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
    virtual void Rotate(const Point& rRef, long nWink, double sn, double cs);
    virtual void Mirror(const Point& rRef1, const Point& rRef2);
    virtual void Shear(const Point& rRef, long nWink, double tn, FASTBOOL bVShear);

    virtual void RecalcSnapRect();
    virtual const Rectangle& GetSnapRect() const;
    virtual void SetSnapRect(const Rectangle& rRect);
    virtual void NbcSetSnapRect(const Rectangle& rRect);

    virtual const Rectangle& GetLogicRect() const;
    virtual void SetLogicRect(const Rectangle& rRect);
    virtual void NbcSetLogicRect(const Rectangle& rRect);

    virtual long GetRotateAngle() const;
    virtual long GetShearAngle(FASTBOOL bVertical=FALSE) const;

    virtual sal_uInt32 GetSnapPointCount() const;
    virtual Point GetSnapPoint(sal_uInt32 i) const;

    virtual sal_Bool IsPolyObj() const;
    virtual sal_uInt32 GetPointCount() const;
    virtual Point GetPoint(sal_uInt32 i) const;
    virtual void NbcSetPoint(const Point& rPnt, sal_uInt32 i);

    virtual SdrObjGeoData* GetGeoData() const;
    virtual void SetGeoData(const SdrObjGeoData& rGeo);

    virtual void NbcReformatText();
    virtual void ReformatText();

    virtual FASTBOOL HasMacro() const;
    virtual SdrObject* CheckMacroHit (const SdrObjMacroHitRec& rRec) const;
    virtual Pointer GetMacroPointer (const SdrObjMacroHitRec& rRec) const;
    virtual void PaintMacro (OutputDevice& rOut, const Rectangle& rDirtyRect, const SdrObjMacroHitRec& rRec) const;
    virtual FASTBOOL DoMacro (const SdrObjMacroHitRec& rRec);
    virtual XubString GetMacroPopupComment(const SdrObjMacroHitRec& rRec) const;

    // OD 30.06.2003 #108784# - virtual <GetOffset()> returns Point(0,0)
    // #i73248# for default SdrVirtObj, offset is aAnchor, not (0,0)
    virtual const Point GetOffset() const;
};

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

#endif //_SVDOVIRT_HXX

<|endoftext|>


<commit_before>// The K3 Runtime Collections Library.
//
// This file contains definitions for the various operations performed on K3 collections, used by
// the generated C++ code. The C++ realizations of K3 Collections will inherit from the
// K3::Collection class, providing a suitable content type.
//
// TODO:
//  - Use <algorithm> routines to perform collection transformations? In particular, investigate
//    order-of-operations semantics.
//  - Use container agnostic mutation operations?
//  - Use bulk mutation operations (iterator-based insertion, for example)?
//  - Optimize all the unnecessary copies, using std::move?
#ifndef K3_RUNTIME_COLLECTIONS_H
#define K3_RUNTIME_COLLECTIONS_H

#include <functional>
#include <list>
#include <map>
#include <memory>
#include <tuple>

#include <Engine.hpp>
#include <dataspace/StlDS.hpp>
#include <dataspace/SetDS.hpp>
#include <dataspace/ListDS.hpp>
#include <dataspace/SortedDS.hpp>
#include <boost/serialization/base_object.hpp>

namespace K3 {
  template <template <class...> class D, class E>
  class Collection: public D<E> {
    public:
      Collection(Engine * e) : D<E>(e) {}

      template <template <class> class F>
      Collection(const Collection<F, E> other) : D<E>(other)  {}

      template <template <class> class F>
      Collection(Collection<F, E>&& other) : D<E>(other) {}

      Collection(D<E> other) : D<E>(other) {}

      std::shared_ptr<E> peek() { return D<E>::peek(); }

      void insert(const E& elem) { D<E>::insert(elem); }
      void insert(E&& elem) { D<E>::insert(elem); }

      void erase(const E& elem)  { D<E>::erase(elem); }

      void update(const E& v1, const E& v2) { D<E>::update(v1,v2); }
      void update(const E& v1, E&& v2) { D<E>::update(v1,v2); }

      std::tuple<Collection<D, E>, Collection<D, E>> split() {
        auto tup = D<E>::split();
        D<E> ds1 = get<0>(tup);
        D<E> ds2 = get<1>(tup);
        return std::make_tuple(Collection<D,E>(ds1), Collection<D,E>(ds2));
      }

      template <template <class> class F>
      Collection<D, E> combine(const Collection<F, E>& other) {
       return Collection<D,E>(D<E>::combine(other));
      }

      template <class T>
      Collection<D, T> map(std::function<T(E)> f) {
       return Collection<D,T>(D<E>::map(f));
      }

      Collection<D, E> filter(std::function<bool(E)> f) {
       return Collection<D,E>(D<E>::filter(f));
      }

      template <class Z>
      Z fold(std::function<Z(Z, E)> f, Z init) {
       return D<E>::fold(f, init);
      }

      template <class K, class Z>
      Collection<D, std::tuple<K, Z>> group_by(
        std::function<K(E)> grouper, std::function<Z(Z, E)> folder, Z init) {
          // Create a map to hold partial results
          std::map<K, Z> accs = std::map<K,Z>();
          // lambda to apply to each element
          std::function<void(E)> f = [&] (E elem) {
            K key = grouper(elem);
            if (accs.find(key) == accs.end()) {
              accs[key] = init;
            }
            accs[key] = folder(accs[key], elem);
          };
          D<E>::iterate(f);
          // Build Collection result
          Collection<D, std::tuple<K,Z>> result = Collection<D,std::tuple<K,Z>>(D<E>::getEngine());
          typename std::map<K,Z>::iterator it;
          for (it = accs.begin(); it != accs.end(); ++it) {
            std::tuple<K,Z> tup = std::make_tuple(it->first, it->second);
            result.insert(tup);
          }
         return result;
      }

      template <template <class> class F, class T>
      Collection<D, T> ext(std::function<Collection<F, T>(E)> expand) {
        Collection<D, T> result = Collection<D,T>(D<E>::getEngine());
        auto add_to_result = [&] (T elem) {result.insert(elem); };
        auto fun = [&] (E elem) {
          expand(elem).iterate(add_to_result);
        };
        D<E>::iterate(fun);
        return result;
      }

  private:
    friend class boost::serialization::access;
    // Serialize a collection by serializing its base-class (a dataspace)
    template<class Archive>
    void serialize(Archive &ar, const unsigned int version) {
      ar & boost::serialization::base_object<D<E>>(*this);
    }

  };

  template <typename E>
  // TODO: make this more generic? ie a SeqDS interface
  class Seq : public Collection<ListDS, E> {
    typedef Collection<ListDS, E> Super;
     public:
      Seq(Engine * e) : Super(e) {};

      Seq(const Seq<E>& other) : Super(other)  {}

      Seq(Super other) : Super(other) {}

      // Convert from Collection<ListDS, E> to Seq<E>
      std::tuple<Seq<E>, Seq<E>> split() {
        auto tup = Super::split();
        Super ds1 = get<0>(tup);
        Super ds2 = get<1>(tup);
        return std::make_tuple(Seq<E>(ds1), Seq<E>(ds2));
      }

      Seq<E> combine(const Seq<E>& other) {
       return Seq<E>(Super::combine(other));
      }

      template <class T>
      Seq<T> map(std::function<T(E)> f) {
       return Seq<T>(Super::map(f));
      }

      Seq<E> filter(std::function<bool(E)> f) {
       return Seq<E>(Super::filter(f));
      }

      Seq<E> sort(std::function<int(E,E)> f) {
        Super s = Super(ListDS<E>::sort(f));
        return Seq<E>(s);

      }

      template <class K, class Z>
      Seq<std::tuple<K, Z>> group_by
      (std::function<K(E)> grouper, std::function<Z(Z, E)> folder, Z init) {
        Collection<ListDS, std::tuple<K,Z>> s = Super::group_by(grouper,folder,init);
        return Seq<std::tuple<K,Z>>(s);
      }

      template <class T>
      Seq<T> ext(std::function<Collection<ListDS, T>(E)> expand) {
        Collection<ListDS, T> result = Super::ext(expand);
        return Seq<T>(result);
      }
  };

  template <typename E>
  // TODO: make this more generic? ie a SetDS interface
  class Set : public Collection<SetDS, E> {
    typedef Collection<SetDS, E> Super;
    typedef SetDS<E> dataspace;
     public:
      Set(Engine * e) : Super(e) {};

      Set(const Set<E>& other) : Super(other)  {}

      Set(Super other) : Super(other) {}

      // Convert from Collection<ListDS, E> to Set<E>
      std::tuple<Set<E>, Set<E>> split() {
        auto tup = Super::split();
        Super ds1 = get<0>(tup);
        Super ds2 = get<1>(tup);
        return std::make_tuple(Set<E>(ds1), Set<E>(ds2));
      }

      Set<E> combine(const Set<E>& other) {
       return Set<E>(Super::combine(other));
      }

      template <class T>
      Set<T> map(std::function<T(E)> f) {
       return Set<T>(Super::map(f));
      }

      Set<E> filter(std::function<bool(E)> f) {
       return Set<E>(Super::filter(f));
      }

      template <class K, class Z>
      Set<std::tuple<K, Z>> group_by
      (std::function<K(E)> grouper, std::function<Z(Z, E)> folder, Z init) {
        Collection<SetDS, std::tuple<K,Z>> s = Super::group_by(grouper,folder,init);
        return Set<std::tuple<K,Z>>(s);
      }

      template <class T>
      Set<T> ext(std::function<Collection<SetDS, T>(E)> expand) {
        Collection<SetDS, T> result = Super::ext(expand);
        return Set<T>(result);
      }

      bool member(E e) {
        return dataspace::member(e);
      }

      bool isSubsetOf(SetDS<E> other) {
        return dataspace::isSubsetOf(other);
      }

      // TODO union is a reserved word
      Set union1(Set<E> other) {
        Super s = Super(dataspace::union1(other));
        return Set<E>(s);
      }

      Set intersect(Set<E> other) {
        Super s = Super(dataspace::intersect(other));
        return Set<E>(s);
      }

      Set difference(Set<E> other) {
        Super s = Super(dataspace::difference(other));
        return Set<E>(s);
      }

  };

  template <typename E>
  class Sorted : public Collection<SortedDS, E> {
    typedef Collection<SortedDS, E> Super;
    typedef SortedDS<E> dataspace;
     public:
      Sorted(Engine * e) : Super(e) {};

      Sorted(const Sorted<E>& other) : Super(other)  {}

      Sorted(Super other) : Super(other) {}

      // Convert from Collection<ListDS, E> to Sorted<E>
      std::tuple<Sorted<E>, Sorted<E>> split() {
        auto tup = Super::split();
        Super ds1 = get<0>(tup);
        Super ds2 = get<1>(tup);
        return std::make_tuple(Sorted<E>(ds1), Sorted<E>(ds2));
      }

      Sorted<E> combine(const Sorted<E>& other) {
       return Sorted<E>(Super::combine(other));
      }

      template <class T>
      Sorted<T> map(std::function<T(E)> f) {
       return Sorted<T>(Super::map(f));
      }

      Sorted<E> filter(std::function<bool(E)> f) {
       return Sorted<E>(Super::filter(f));
      }

      template <class K, class Z>
      Sorted<std::tuple<K, Z>> group_by
      (std::function<K(E)> grouper, std::function<Z(Z, E)> folder, Z init) {
        Collection<SortedDS, std::tuple<K,Z>> s = Super::group_by(grouper,folder,init);
        return Sorted<std::tuple<K,Z>>(s);
      }

      template <class T>
      Sorted<T> ext(std::function<Collection<SortedDS, T>(E)> expand) {
        Collection<SortedDS, T> result = Super::ext(expand);
        return Sorted<T>(result);
      }

      shared_ptr<E> min() { return dataspace::min(); }

      shared_ptr<E> max() { return dataspace::max(); }

      shared_ptr<E> lowerBound(E a) { return dataspace::lowerBound(a); }

      shared_ptr<E> upperBound(E a) { return dataspace::lowerBound(a); }

      Sorted<E> slice(E a, E b) {
        Super s = Super(dataspace::slice(a,b));
        return Sorted<E>(s);
      }

  };

  template <typename E>
  // TODO: make this more generic? ie an ExternalDS interface
  class ExternalCollection : public Collection<FileDS, E> {
    typedef Collection<FileDS, E> Super;
    typedef FileDS<E> Dataspace;
     public:
      ExternalCollection(Engine * e) : Super(e) {};

      ExternalCollection(const ExternalCollection<E>& other) : Super(other)  {}

      ExternalCollection(const Super& other) : Super(other) {}
      ExternalCollection(Super&& other) : Super(std::move(other)) {}

      // Convert from Collection<ListDS, E> to Set<E>
      std::tuple<Set<E>, Set<E>> split() {
        auto tup = Super::split();
        Super& ds1 = get<0>(tup);
        Super& ds2 = get<1>(tup);
        return std::make_tuple(ExternalCollection<E>(ds1), ExternalCollection<E>(ds2));
      }

      ExternalCollection<E> combine(const ExternalCollection<E>& other) {
       return ExternalCollection<E>(Super::combine(other));
      }

      template <class T>
      ExternalCollection<T> map(std::function<T(E)> f) {
       return ExternalCollection<T>(Super::map(f));
      }

      ExternalCollection<E> filter(std::function<bool(E)> f) {
       return ExternalCollection<E>(Super::filter(f));
      }

      template <class K, class Z>
      ExternalCollection<std::tuple<K, Z>> group_by
            (std::function<K(E)> grouper, std::function<Z(Z, E)> folder, Z init) {
        Collection<FileDS, std::tuple<K,Z>> s = Super::group_by(grouper,folder,init);
        return ExternalCollection<std::tuple<K,Z>>(s);
      }

      template <class T>
      ExternalCollection<T> ext(std::function<Collection<SetDS, T>(E)> expand) {
        Collection<SetDS, T> result = Super::ext(expand);
        return ExternalCollection<T>(result);
      }
  };
}

#endif
<commit_msg>Add iterator constructors to Collections<commit_after>// The K3 Runtime Collections Library.
//
// This file contains definitions for the various operations performed on K3 collections, used by
// the generated C++ code. The C++ realizations of K3 Collections will inherit from the
// K3::Collection class, providing a suitable content type.
//
// TODO:
//  - Use <algorithm> routines to perform collection transformations? In particular, investigate
//    order-of-operations semantics.
//  - Use container agnostic mutation operations?
//  - Use bulk mutation operations (iterator-based insertion, for example)?
//  - Optimize all the unnecessary copies, using std::move?
#ifndef K3_RUNTIME_COLLECTIONS_H
#define K3_RUNTIME_COLLECTIONS_H

#include <functional>
#include <list>
#include <map>
#include <memory>
#include <tuple>

#include <Engine.hpp>
#include <dataspace/StlDS.hpp>
#include <dataspace/SetDS.hpp>
#include <dataspace/ListDS.hpp>
#include <dataspace/SortedDS.hpp>
#include <boost/serialization/base_object.hpp>

namespace K3 {
  template <template <class...> class D, class E>
  class Collection: public D<E> {
    public:
      Collection(Engine * e) : D<E>(e) {}

      template <template <class> class F>
      Collection(const Collection<F, E> other) : D<E>(other)  {}

      template <template <class> class F>
      Collection(Collection<F, E>&& other) : D<E>(other) {}

      Collection(D<E> other) : D<E>(other) {}

      template<class Iterator>
      Collection(Engine * e, Iterator start, Iterator finish)
        : D<E>(e, start, finish)
      { }

      std::shared_ptr<E> peek() { return D<E>::peek(); }

      void insert(const E& elem) { D<E>::insert(elem); }
      void insert(E&& elem) { D<E>::insert(elem); }

      void erase(const E& elem)  { D<E>::erase(elem); }

      void update(const E& v1, const E& v2) { D<E>::update(v1,v2); }
      void update(const E& v1, E&& v2) { D<E>::update(v1,v2); }

      std::tuple<Collection<D, E>, Collection<D, E>> split() {
        auto tup = D<E>::split();
        D<E> ds1 = get<0>(tup);
        D<E> ds2 = get<1>(tup);
        return std::make_tuple(Collection<D,E>(ds1), Collection<D,E>(ds2));
      }

      template <template <class> class F>
      Collection<D, E> combine(const Collection<F, E>& other) {
       return Collection<D,E>(D<E>::combine(other));
      }

      template <class T>
      Collection<D, T> map(std::function<T(E)> f) {
       return Collection<D,T>(D<E>::map(f));
      }

      Collection<D, E> filter(std::function<bool(E)> f) {
       return Collection<D,E>(D<E>::filter(f));
      }

      template <class Z>
      Z fold(std::function<Z(Z, E)> f, Z init) {
       return D<E>::fold(f, init);
      }

      template <class K, class Z>
      Collection<D, std::tuple<K, Z>> group_by(
        std::function<K(E)> grouper, std::function<Z(Z, E)> folder, Z init) {
          // Create a map to hold partial results
          std::map<K, Z> accs = std::map<K,Z>();
          // lambda to apply to each element
          std::function<void(E)> f = [&] (E elem) {
            K key = grouper(elem);
            if (accs.find(key) == accs.end()) {
              accs[key] = init;
            }
            accs[key] = folder(accs[key], elem);
          };
          D<E>::iterate(f);
          // Build Collection result
          Collection<D, std::tuple<K,Z>> result = Collection<D,std::tuple<K,Z>>(D<E>::getEngine());
          typename std::map<K,Z>::iterator it;
          for (it = accs.begin(); it != accs.end(); ++it) {
            std::tuple<K,Z> tup = std::make_tuple(it->first, it->second);
            result.insert(tup);
          }
         return result;
      }

      template <template <class> class F, class T>
      Collection<D, T> ext(std::function<Collection<F, T>(E)> expand) {
        Collection<D, T> result = Collection<D,T>(D<E>::getEngine());
        auto add_to_result = [&] (T elem) {result.insert(elem); };
        auto fun = [&] (E elem) {
          expand(elem).iterate(add_to_result);
        };
        D<E>::iterate(fun);
        return result;
      }

  private:
    friend class boost::serialization::access;
    // Serialize a collection by serializing its base-class (a dataspace)
    template<class Archive>
    void serialize(Archive &ar, const unsigned int version) {
      ar & boost::serialization::base_object<D<E>>(*this);
    }

  };

  template <typename E>
  // TODO: make this more generic? ie a SeqDS interface
  class Seq : public Collection<ListDS, E> {
    typedef Collection<ListDS, E> Super;
     public:
      Seq(Engine * e) : Super(e) {};

      Seq(const Seq<E>& other) : Super(other)  {}

      Seq(Super other) : Super(other) {}

      template<class Iterator>
      Seq(Engine * e, Iterator start, Iterator finish)
        : Super(e, start, finish)
      { }

      // Convert from Collection<ListDS, E> to Seq<E>
      std::tuple<Seq<E>, Seq<E>> split() {
        auto tup = Super::split();
        Super ds1 = get<0>(tup);
        Super ds2 = get<1>(tup);
        return std::make_tuple(Seq<E>(ds1), Seq<E>(ds2));
      }

      Seq<E> combine(const Seq<E>& other) {
       return Seq<E>(Super::combine(other));
      }

      template <class T>
      Seq<T> map(std::function<T(E)> f) {
       return Seq<T>(Super::map(f));
      }

      Seq<E> filter(std::function<bool(E)> f) {
       return Seq<E>(Super::filter(f));
      }

      Seq<E> sort(std::function<int(E,E)> f) {
        Super s = Super(ListDS<E>::sort(f));
        return Seq<E>(s);

      }

      template <class K, class Z>
      Seq<std::tuple<K, Z>> group_by
      (std::function<K(E)> grouper, std::function<Z(Z, E)> folder, Z init) {
        Collection<ListDS, std::tuple<K,Z>> s = Super::group_by(grouper,folder,init);
        return Seq<std::tuple<K,Z>>(s);
      }

      template <class T>
      Seq<T> ext(std::function<Collection<ListDS, T>(E)> expand) {
        Collection<ListDS, T> result = Super::ext(expand);
        return Seq<T>(result);
      }
  };

  template <typename E>
  // TODO: make this more generic? ie a SetDS interface
  class Set : public Collection<SetDS, E> {
    typedef Collection<SetDS, E> Super;
    typedef SetDS<E> dataspace;
     public:
      Set(Engine * e) : Super(e) {};

      Set(const Set<E>& other) : Super(other)  {}

      Set(Super other) : Super(other) {}

      template<class Iterator>
      Set(Engine * e, Iterator start, Iterator finish)
        : Super(e, start, finish)
      { }

      // Convert from Collection<ListDS, E> to Set<E>
      std::tuple<Set<E>, Set<E>> split() {
        auto tup = Super::split();
        Super ds1 = get<0>(tup);
        Super ds2 = get<1>(tup);
        return std::make_tuple(Set<E>(ds1), Set<E>(ds2));
      }

      Set<E> combine(const Set<E>& other) {
       return Set<E>(Super::combine(other));
      }

      template <class T>
      Set<T> map(std::function<T(E)> f) {
       return Set<T>(Super::map(f));
      }

      Set<E> filter(std::function<bool(E)> f) {
       return Set<E>(Super::filter(f));
      }

      template <class K, class Z>
      Set<std::tuple<K, Z>> group_by
      (std::function<K(E)> grouper, std::function<Z(Z, E)> folder, Z init) {
        Collection<SetDS, std::tuple<K,Z>> s = Super::group_by(grouper,folder,init);
        return Set<std::tuple<K,Z>>(s);
      }

      template <class T>
      Set<T> ext(std::function<Collection<SetDS, T>(E)> expand) {
        Collection<SetDS, T> result = Super::ext(expand);
        return Set<T>(result);
      }

      bool member(E e) {
        return dataspace::member(e);
      }

      bool isSubsetOf(SetDS<E> other) {
        return dataspace::isSubsetOf(other);
      }

      // TODO union is a reserved word
      Set union1(Set<E> other) {
        Super s = Super(dataspace::union1(other));
        return Set<E>(s);
      }

      Set intersect(Set<E> other) {
        Super s = Super(dataspace::intersect(other));
        return Set<E>(s);
      }

      Set difference(Set<E> other) {
        Super s = Super(dataspace::difference(other));
        return Set<E>(s);
      }

  };

  template <typename E>
  class Sorted : public Collection<SortedDS, E> {
    typedef Collection<SortedDS, E> Super;
    typedef SortedDS<E> dataspace;
     public:
      Sorted(Engine * e) : Super(e) {};

      Sorted(const Sorted<E>& other) : Super(other)  {}

      Sorted(Super other) : Super(other) {}

      template<class Iterator>
      Sorted(Engine * e, Iterator start, Iterator finish)
        : Super(e, start, finish)
      { }

      // Convert from Collection<ListDS, E> to Sorted<E>
      std::tuple<Sorted<E>, Sorted<E>> split() {
        auto tup = Super::split();
        Super ds1 = get<0>(tup);
        Super ds2 = get<1>(tup);
        return std::make_tuple(Sorted<E>(ds1), Sorted<E>(ds2));
      }

      Sorted<E> combine(const Sorted<E>& other) {
       return Sorted<E>(Super::combine(other));
      }

      template <class T>
      Sorted<T> map(std::function<T(E)> f) {
       return Sorted<T>(Super::map(f));
      }

      Sorted<E> filter(std::function<bool(E)> f) {
       return Sorted<E>(Super::filter(f));
      }

      template <class K, class Z>
      Sorted<std::tuple<K, Z>> group_by
      (std::function<K(E)> grouper, std::function<Z(Z, E)> folder, Z init) {
        Collection<SortedDS, std::tuple<K,Z>> s = Super::group_by(grouper,folder,init);
        return Sorted<std::tuple<K,Z>>(s);
      }

      template <class T>
      Sorted<T> ext(std::function<Collection<SortedDS, T>(E)> expand) {
        Collection<SortedDS, T> result = Super::ext(expand);
        return Sorted<T>(result);
      }

      shared_ptr<E> min() { return dataspace::min(); }

      shared_ptr<E> max() { return dataspace::max(); }

      shared_ptr<E> lowerBound(E a) { return dataspace::lowerBound(a); }

      shared_ptr<E> upperBound(E a) { return dataspace::lowerBound(a); }

      Sorted<E> slice(E a, E b) {
        Super s = Super(dataspace::slice(a,b));
        return Sorted<E>(s);
      }

  };

  template <typename E>
  // TODO: make this more generic? ie an ExternalDS interface
  class ExternalCollection : public Collection<FileDS, E> {
    typedef Collection<FileDS, E> Super;
    typedef FileDS<E> Dataspace;
     public:
      ExternalCollection(Engine * e) : Super(e) {};

      ExternalCollection(const ExternalCollection<E>& other) : Super(other)  {}

      ExternalCollection(const Super& other) : Super(other) {}
      ExternalCollection(Super other) : Super(other) {}

      template<class Iterator>
      ExternalCollection(Engine * e, Iterator start, Iterator finish)
        : Super(e, start, finish)
      { }

      // Convert from Collection<ListDS, E> to Set<E>
      std::tuple<Set<E>, Set<E>> split() {
        auto tup = Super::split();
        Super& ds1 = get<0>(tup);
        Super& ds2 = get<1>(tup);
        return std::make_tuple(ExternalCollection<E>(ds1), ExternalCollection<E>(ds2));
      }

      ExternalCollection<E> combine(const ExternalCollection<E>& other) {
       return ExternalCollection<E>(Super::combine(other));
      }

      template <class T>
      ExternalCollection<T> map(std::function<T(E)> f) {
       return ExternalCollection<T>(Super::map(f));
      }

      ExternalCollection<E> filter(std::function<bool(E)> f) {
       return ExternalCollection<E>(Super::filter(f));
      }

      template <class K, class Z>
      ExternalCollection<std::tuple<K, Z>> group_by
            (std::function<K(E)> grouper, std::function<Z(Z, E)> folder, Z init) {
        Collection<FileDS, std::tuple<K,Z>> s = Super::group_by(grouper,folder,init);
        return ExternalCollection<std::tuple<K,Z>>(s);
      }

      template <class T>
      ExternalCollection<T> ext(std::function<Collection<SetDS, T>(E)> expand) {
        Collection<SetDS, T> result = Super::ext(expand);
        return ExternalCollection<T>(result);
      }
  };
}

#endif
<|endoftext|>


<commit_before>// The K3 Runtime Collections Library.
//
// This file contains definitions for the various operations performed on K3 collections, used by
// the generated C++ code. The C++ realizations of K3 Collections will inherit from the
// K3::Collection class, providing a suitable content type.
//
// TODO:
//  - Use <algorithm> routines to perform collection transformations? In particular, investigate
//    order-of-operations semantics.
//  - Use container agnostic mutation operations?
//  - Use bulk mutation operations (iterator-based insertion, for example)?
//  - Optimize all the unnecessary copies, using std::move?
#ifndef K3_RUNTIME_COLLECTIONS_H
#define K3_RUNTIME_COLLECTIONS_H

#include <functional>
#include <map>
#include <memory>
#include <tuple>
#include <vector>

namespace K3 {
    template <typename E> using chunk = std::vector<E>;

    template <typename E>
    class Collection {
        public:
            Collection() {}
            Collection(const chunk<E>& v): __data(v) {}
            Collection(const Collection& c): __data(c.__data) {}
            Collection(Collection&& c): __data(c.__data) {}

            std::shared_ptr<E> peek();

            void insert_basic(const E&);
            void delete_first(const E&);
            void update_first(const E&, const E&);

            template <typename T>
            Collection<T> map(std::function<T(E)>);

            Collection<E> filter(std::function<bool(E)>);

            template <typename Z>
            Z fold(std::function<Z(Z, E)>, Z);

            template <typename K, typename Z>
            Collection<std::tuple<K, Z>> group_by(std::function<K(E)>, std::function<Z(Z, E)>, Z);

            chunk<E> __data;
    };

    template <typename E>
    std::shared_ptr<E> Collection<E>::peek() {
        if (!__data.empty()) {
            return std::shared_ptr<E>(__data.front());
        } else {
            return nullptr;
        }

    }

    template <typename E>
    void Collection<E>::insert_basic(const E& e) {
        __data.push_back(e);
    }

    template <typename E>
    void Collection<E>::delete_first(const E& e) {
        auto location = find(begin(__data), end(__data), e);

        if (location != end(__data)) {
            __data.erase(location);
        }

        return;
    }

    template <typename E>
    void Collection<E>::update_first(const E& prev, const E& next) {
        auto location = find(begin(__data), end(__data), prev);

        if (location != end(__data)) {
            *location = next;
        }

        return;
    }

    template <typename E>
    template <typename T>
    Collection<T> Collection<E>::map(std::function<T(E)> f) {
        chunk<T> v;
        v.reserve(__data.size());

        for (auto i : __data) {
            v.push_back(f(i));
        }

        return Collection<T>(v);
    }

    template <typename E>
    Collection<E> Collection<E>::filter(std::function<bool(E)> p) {
        chunk<E> v;

        for (auto i: __data) {
            if (p(i)) {
                v.push_back(i);
            }
        }

        return Collection(v);
    }

    template <typename E>
    template <typename Z>
    Z Collection<E>::fold(std::function<Z(Z, E)> f, Z z) {
        for (auto i: __data) {
            z = f(z, i);
        }

        return z;
    }

    template <typename E>
    template <typename K, typename Z>
    Collection<std::tuple<K, Z>> Collection<E>::group_by(std::function<K(E)> g, std::function<Z(Z, E)> f, Z z) {
        std::map<K, Z> m;

        for (auto i: __data) {
            K k = g(i);
            if (m.find(k)) {
                m[k] = f(i, m[k]);
            } else {
                m[k] = f(z, i);
            }
        }

        chunk<std::tuple<K, Z>> v;
        v.reserve(m.count());

        for (auto i: m) {
            v.push_back(std::make_tuple(i.first, i.second));
        }

        return Collection<std::tuple<K, Z>>(v);
    }
}

#endif
<commit_msg>Switch to using std::list for data storage.<commit_after>// The K3 Runtime Collections Library.
//
// This file contains definitions for the various operations performed on K3 collections, used by
// the generated C++ code. The C++ realizations of K3 Collections will inherit from the
// K3::Collection class, providing a suitable content type.
//
// TODO:
//  - Use <algorithm> routines to perform collection transformations? In particular, investigate
//    order-of-operations semantics.
//  - Use container agnostic mutation operations?
//  - Use bulk mutation operations (iterator-based insertion, for example)?
//  - Optimize all the unnecessary copies, using std::move?
#ifndef K3_RUNTIME_COLLECTIONS_H
#define K3_RUNTIME_COLLECTIONS_H

#include <functional>
#include <map>
#include <memory>
#include <tuple>
#include <list>

namespace K3 {
    template <typename E> using chunk = std::list<E>;

    template <typename E>
    class Collection {
        public:
            Collection() {}
            Collection(const chunk<E>& v): __data(v) {}
            Collection(const Collection& c): __data(c.__data) {}
            Collection(Collection&& c): __data(c.__data) {}

            std::shared_ptr<E> peek();

            void insert_basic(const E&);
            void delete_first(const E&);
            void update_first(const E&, const E&);

            template <typename T>
            Collection<T> map(std::function<T(E)>);

            Collection<E> filter(std::function<bool(E)>);

            template <typename Z>
            Z fold(std::function<Z(Z, E)>, Z);

            template <typename K, typename Z>
            Collection<std::tuple<K, Z>> group_by(std::function<K(E)>, std::function<Z(Z, E)>, Z);

            chunk<E> __data;
    };

    template <typename E>
    std::shared_ptr<E> Collection<E>::peek() {
        if (!__data.empty()) {
            return std::shared_ptr<E>(__data.front());
        } else {
            return nullptr;
        }

    }

    template <typename E>
    void Collection<E>::insert_basic(const E& e) {
        __data.push_back(e);
    }

    template <typename E>
    void Collection<E>::delete_first(const E& e) {
        auto location = find(begin(__data), end(__data), e);

        if (location != end(__data)) {
            __data.erase(location);
        }

        return;
    }

    template <typename E>
    void Collection<E>::update_first(const E& prev, const E& next) {
        auto location = find(begin(__data), end(__data), prev);

        if (location != end(__data)) {
            *location = next;
        }

        return;
    }

    template <typename E>
    template <typename T>
    Collection<T> Collection<E>::map(std::function<T(E)> f) {
        chunk<T> v;
        v.reserve(__data.size());

        for (auto i : __data) {
            v.push_back(f(i));
        }

        return Collection<T>(v);
    }

    template <typename E>
    Collection<E> Collection<E>::filter(std::function<bool(E)> p) {
        chunk<E> v;

        for (auto i: __data) {
            if (p(i)) {
                v.push_back(i);
            }
        }

        return Collection(v);
    }

    template <typename E>
    template <typename Z>
    Z Collection<E>::fold(std::function<Z(Z, E)> f, Z z) {
        for (auto i: __data) {
            z = f(z, i);
        }

        return z;
    }

    template <typename E>
    template <typename K, typename Z>
    Collection<std::tuple<K, Z>> Collection<E>::group_by(std::function<K(E)> g, std::function<Z(Z, E)> f, Z z) {
        std::map<K, Z> m;

        for (auto i: __data) {
            K k = g(i);
            if (m.find(k)) {
                m[k] = f(i, m[k]);
            } else {
                m[k] = f(z, i);
            }
        }

        chunk<std::tuple<K, Z>> v;
        v.reserve(m.count());

        for (auto i: m) {
            v.push_back(std::make_tuple(i.first, i.second));
        }

        return Collection<std::tuple<K, Z>>(v);
    }
}

#endif
<|endoftext|>


<commit_before>//=====================================================================//
/*! @file
    @brief  RX64M SDRAM サンプル @n
			・P07(176) ピンに赤色LED（VF:1.9V）を吸い込みで接続する @n
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2017 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/cmt_io.hpp"
#include "common/sci_io.hpp"
#include "common/fixed_fifo.hpp"
#include "common/format.hpp"
#include <random>

namespace {

	typedef device::cmt_io<device::CMT0, utils::null_task> CMT;
	CMT		cmt_;

	typedef utils::fixed_fifo<char, 128> BUFFER;
	typedef device::sci_io<device::SCI1, BUFFER, BUFFER> SCI;
	SCI		sci_;

	utils::SDRAM_128M_32W	sdram_;
}

extern "C" {

	void sci_putch(char ch)
	{
		sci_.putch(ch);
	}

	char sci_getch(void)
	{
		return sci_.getch();
	}
}

int main(int argc, char** argv);

int main(int argc, char** argv)
{
	device::system_io<12000000>::setup_system_clock();

	// SDRAM 初期化 128M/32bits bus
	sdram_();

	{
		// タイマー設定（６０Ｈｚ）
		uint8_t cmt_irq_level = 4;
		cmt_.start(60, cmt_irq_level);
	}

	{
		// SCI 設定
		static const uint8_t sci_level = 2;
		sci_.start(115200, sci_level);
	}

	utils::format("RX64M SDRAM sample\n");

	device::PORT0::PDR.B7 = 1; // output

	// 乱数を書き込む
	{
		std::mt19937 mt;
		volatile uint32_t* p = reinterpret_cast<uint32_t*>(0x08000000);
		uint32_t j = 0;
		for(uint32_t i = 0; i < 1024 * 1024 * 32 / 4; ++i) {
			if(j == 0) {
				utils::format("Write block:  0x%08X\n") % reinterpret_cast<uint32_t>(p);
				device::PORT0::PODR.B7 = !device::PORT0::PODR.B7();
			}
			++j;
			if(j >= 16384) j = 0;
			*p++ = mt();
		}
	}

	// 乱数を読み出す
	{
		uint32_t error = 0;
		std::mt19937 mt;
		volatile uint32_t* p = reinterpret_cast<uint32_t*>(0x08000000);
		uint32_t j = 0;
		uint32_t all = 1024 * 1024 * 32;
		for(uint32_t i = 0; i < all / 4; ++i) {
			auto n = mt();
			if(*p != n) {
				++error;
				utils::format("Read block error: 0x%08X\n") % reinterpret_cast<uint32_t>(p);
			}
			++p;
			if(j == (16384 - 1)) {
				utils::format("Read block OK: 0x%08X\n") % (reinterpret_cast<uint32_t>(p) - 16384);
				device::PORT0::PODR.B7 = !device::PORT0::PODR.B7();
			}
			++j;
			if(j >= 16384) j = 0;
		}
		if(error) {
			utils::format("Read error: %d bytes\n") % (error * 4);
		} else {
			utils::format("Write/Read All OK: %d bytes\n") % all;
		}
	}

	uint32_t cnt = 0;
	while(1) {
		cmt_.sync();

		if(sci_.recv_length()) {
			auto ch = sci_.getch();
			sci_.putch(ch);
		}

		++cnt;
		if(cnt >= 30) {
			cnt = 0;
		}
		device::PORT0::PODR.B7 = (cnt < 10) ? 0 : 1;
	}
}
<commit_msg>Rename: cmt_io to cmt_mgr<commit_after>//=====================================================================//
/*! @file
    @brief  RX64M SDRAM サンプル @n
			・P07(176) ピンに赤色LED（VF:1.9V）を吸い込みで接続する @n
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2017 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/cmt_mgr.hpp"
#include "common/sci_io.hpp"
#include "common/fixed_fifo.hpp"
#include "common/format.hpp"
#include <random>

namespace {

	typedef device::cmt_mgr<device::CMT0, utils::null_task> CMT;
	CMT		cmt_;

	typedef utils::fixed_fifo<char, 128> BUFFER;
	typedef device::sci_io<device::SCI1, BUFFER, BUFFER> SCI;
	SCI		sci_;

	utils::SDRAM_128M_32W	sdram_;
}

extern "C" {

	void sci_putch(char ch)
	{
		sci_.putch(ch);
	}

	char sci_getch(void)
	{
		return sci_.getch();
	}
}

int main(int argc, char** argv);

int main(int argc, char** argv)
{
	device::system_io<12000000>::setup_system_clock();

	// SDRAM 初期化 128M/32bits bus
	sdram_();

	{
		// タイマー設定（６０Ｈｚ）
		uint8_t cmt_irq_level = 4;
		cmt_.start(60, cmt_irq_level);
	}

	{
		// SCI 設定
		static const uint8_t sci_level = 2;
		sci_.start(115200, sci_level);
	}

	utils::format("RX64M SDRAM sample\n");

	device::PORT0::PDR.B7 = 1; // output

	// 乱数を書き込む
	{
		std::mt19937 mt;
		volatile uint32_t* p = reinterpret_cast<uint32_t*>(0x08000000);
		uint32_t j = 0;
		for(uint32_t i = 0; i < 1024 * 1024 * 32 / 4; ++i) {
			if(j == 0) {
				utils::format("Write block:  0x%08X\n") % reinterpret_cast<uint32_t>(p);
				device::PORT0::PODR.B7 = !device::PORT0::PODR.B7();
			}
			++j;
			if(j >= 16384) j = 0;
			*p++ = mt();
		}
	}

	// 乱数を読み出す
	{
		uint32_t error = 0;
		std::mt19937 mt;
		volatile uint32_t* p = reinterpret_cast<uint32_t*>(0x08000000);
		uint32_t j = 0;
		uint32_t all = 1024 * 1024 * 32;
		for(uint32_t i = 0; i < all / 4; ++i) {
			auto n = mt();
			if(*p != n) {
				++error;
				utils::format("Read block error: 0x%08X\n") % reinterpret_cast<uint32_t>(p);
			}
			++p;
			if(j == (16384 - 1)) {
				utils::format("Read block OK: 0x%08X\n") % (reinterpret_cast<uint32_t>(p) - 16384);
				device::PORT0::PODR.B7 = !device::PORT0::PODR.B7();
			}
			++j;
			if(j >= 16384) j = 0;
		}
		if(error) {
			utils::format("Read error: %d bytes\n") % (error * 4);
		} else {
			utils::format("Write/Read All OK: %d bytes\n") % all;
		}
	}

	uint32_t cnt = 0;
	while(1) {
		cmt_.sync();

		if(sci_.recv_length()) {
			auto ch = sci_.getch();
			sci_.putch(ch);
		}

		++cnt;
		if(cnt >= 30) {
			cnt = 0;
		}
		device::PORT0::PODR.B7 = (cnt < 10) ? 0 : 1;
	}
}
<|endoftext|>


<commit_before>
#include <ionCore.h>
#include <catch.hpp>

class A
{};

class B : public A
{};

class C
{
public:
	virtual ~C()
	{}
};

TEST_CASE("InstanceOf", "")
{
	A a;
	B b;
	C c;

	A const * const aPtr = &a;

	CHECK(InstanceOf<A>(a));
	CHECK(InstanceOf<A>(aPtr));
	CHECK(InstanceOf<A>(&a));
	CHECK(InstanceOf<A>(b));
	CHECK(InstanceOf<A>(&b));
	CHECK(InstanceOf<C>(c));
	CHECK(! InstanceOf<A>(c));
	CHECK(! InstanceOf<A>(&c));
	CHECK(nullptr != As<A>(&a));
	CHECK(nullptr != As<A>(&b));
	CHECK(nullptr == As<A>(&c));
}

class TestBase
{
public:
	TestBase() {}
	virtual ~TestBase() {}
};

class TestDerived : public TestBase
{};

TEST_CASE("ionClass::As", "As function converts between objects")
{
	TestBase a;
	TestBase const constA;
	TestDerived b;
	C c;

	TestBase const * const aPtr = &a;
	TestDerived const * const bPtr = &b;
	C const * const cPtr = &c;

	CHECK(As<TestDerived>((TestBase*)&b) == &b);
	CHECK(As<TestDerived>((TestBase const * const)bPtr) == bPtr);
	CHECK(As<TestBase>(& a) == & a);
	CHECK(! As<TestDerived>(& a));
	CHECK(! & As<TestDerived>(a));
	CHECK(! & As<TestDerived>(constA));
}

TEST_CASE("Type", "[ionClass :: Type]")
{
	Type TypeA(typeid(A));
	Type TypeB(typeid(B));
	Type TypeC(typeid(C));

	CHECK((TypeA < TypeB) != (TypeB < TypeA));
	CHECK((TypeA < TypeC) != (TypeC < TypeA));
	CHECK((TypeB < TypeC) != (TypeC < TypeB));
}

class F;

class E : public Singleton<E>
{
public:
	SingletonPointer<F> FPtr;
};

class F : public Singleton<F>
{
public:
	SingletonPointer<E> EPtr;
};

TEST_CASE("Singleton lazy initialization", "[ionClass :: Singleton]")
{
	SingletonPointer<E> e;
	SingletonPointer<E> const constE = SingletonPointer<E>();
	SingletonPointer<F> f;

	CHECK(e->FPtr.Get() == f.Get());
	CHECK(constE->FPtr.Get() == f.Get());
	CHECK(f->EPtr.Get() == e.Get());
	CHECK(f->EPtr.Get() == constE.Get());
	CHECK(f->EPtr == e);
	CHECK(f->EPtr == constE);
}

<commit_msg>[TestUnits] Fix some undefined use of a null reference<commit_after>
#include <ionCore.h>
#include <catch.hpp>

class A
{};

class B : public A
{};

class C
{
public:
	virtual ~C()
	{}
};

TEST_CASE("InstanceOf", "")
{
	A a;
	B b;
	C c;

	A const * const aPtr = &a;

	CHECK(InstanceOf<A>(a));
	CHECK(InstanceOf<A>(aPtr));
	CHECK(InstanceOf<A>(&a));
	CHECK(InstanceOf<A>(b));
	CHECK(InstanceOf<A>(&b));
	CHECK(InstanceOf<C>(c));
	CHECK(! InstanceOf<A>(c));
	CHECK(! InstanceOf<A>(&c));
	CHECK(nullptr != As<A>(&a));
	CHECK(nullptr != As<A>(&b));
	CHECK(nullptr == As<A>(&c));
}

class TestBase
{
public:
	TestBase() {}
	virtual ~TestBase() {}
};

class TestDerived : public TestBase
{};

TEST_CASE("ionClass::As", "As function converts between objects")
{
	TestBase a;
	TestBase const constA;
	TestDerived b;
	C c;

	TestBase const * const aPtr = &a;
	TestDerived const * const bPtr = &b;
	C const * const cPtr = &c;

	CHECK(As<TestDerived>((TestBase*)&b) == &b);
	CHECK(As<TestDerived>((TestBase const * const)bPtr) == bPtr);
	CHECK(As<TestBase>(& a) == & a);
	CHECK(nullptr == As<TestDerived>(& a));
	CHECK(nullptr == As<TestDerived>(& constA));
}

TEST_CASE("Type", "[ionClass :: Type]")
{
	Type TypeA(typeid(A));
	Type TypeB(typeid(B));
	Type TypeC(typeid(C));

	CHECK((TypeA < TypeB) != (TypeB < TypeA));
	CHECK((TypeA < TypeC) != (TypeC < TypeA));
	CHECK((TypeB < TypeC) != (TypeC < TypeB));
}

class F;

class E : public Singleton<E>
{
public:
	SingletonPointer<F> FPtr;
};

class F : public Singleton<F>
{
public:
	SingletonPointer<E> EPtr;
};

TEST_CASE("Singleton lazy initialization", "[ionClass :: Singleton]")
{
	SingletonPointer<E> e;
	SingletonPointer<E> const constE = SingletonPointer<E>();
	SingletonPointer<F> f;

	CHECK(e->FPtr.Get() == f.Get());
	CHECK(constE->FPtr.Get() == f.Get());
	CHECK(f->EPtr.Get() == e.Get());
	CHECK(f->EPtr.Get() == constE.Get());
	CHECK(f->EPtr == e);
	CHECK(f->EPtr == constE);
}

<|endoftext|>


<commit_before>#include <QTimer>
#include <QAction>
#include <QPainter>
#include <QToolBar>
#include <QMouseEvent>

#include "CommentLib.h"

#include "AssassinWar.h"
#include "GameScreen.h"
#include "MapManager.h"
#include "ToolbarManager.h"
#include "ChoosingMapDlg.h"
#include "CharacterManager.h"
#include "PixelCoordinateTransfer.h"

const int ICON_SIZE = 45;
const int MAIN_WIN_WIDTH = 850;
const int ENSURE_VISIBLE_BOUNDARY_DISTANCE = 500;

AssassinWar::AssassinWar(const int &iWidth, const int &iHeight,
                         QWidget *parent, Qt::WFlags flags)
    : QMainWindow(parent, flags),
      m_pRepaintTimer(NULL), m_pToolbar(NULL), m_pGameScreen(NULL),
      m_pToolbarManager(NULL), m_pChoosingMapDlg(NULL),
      m_bIsAWRun(false),
      m_iScreenWidth(iWidth), m_iScreenHeight(iHeight)
{

}

AssassinWar::~AssassinWar()
{
    if(NULL != m_pGameScreen)
    {
        delete m_pGameScreen;
        m_pGameScreen = NULL;
    }

    if(NULL != m_pRepaintTimer)
    {
        m_pRepaintTimer->stop();
    }

    if(NULL != m_pToolbarManager)
    {
        delete m_pToolbarManager;
        m_pToolbarManager = NULL;
    }
}

void AssassinWar::mouseMoveEvent(QMouseEvent *mouseEvent)
{
    if(ICON_SIZE > mouseEvent->pos().y() && !m_bIsAWRun)
    {
        m_pToolbar->setVisible(true);
    }
    else
    {
        m_pToolbar->setVisible(false);
    }
}

void AssassinWar::paintEvent(QPaintEvent *paintEvent)
{
    QPainter painter(this);

    painter.drawPixmap(0, 0, m_background);

    if(m_bIsAWRun)
    {
        int iPlayerX = PixelCoordinateTransfer::instance().gridXToPixelCoordinateX(CharacterManager::instance().getPlayerCharacterGridX());
        int iPlayerY = PixelCoordinateTransfer::instance().gridYToPixelCoordinateY(CharacterManager::instance().getPlayerCharacterGridY());
        m_pGameScreen->ensureVisible(iPlayerX, iPlayerY, ENSURE_VISIBLE_BOUNDARY_DISTANCE, ENSURE_VISIBLE_BOUNDARY_DISTANCE);
        CharacterManager::instance().drawAllCharacter(painter, m_pGameScreen->getScreenOffsetX(), m_pGameScreen->getScreenOffsetY());
    }
}

void AssassinWar::onButttonHost_()
{
    setMouseTracking(false);
    m_pToolbar->setVisible(false);

    m_pChoosingMapDlg->updateMapList(MapManager::instance().getMapList());
    m_pChoosingMapDlg->show();

}

bool AssassinWar::runAW_(const QString& strCurrntMapName)
{
    m_pChoosingMapDlg->hide();

    setWindowState(Qt::WindowFullScreen);

    initBackground_(MapManager::instance().getMapBackground(strCurrntMapName));

    m_bIsAWRun = m_pGameScreen->openScreen(strCurrntMapName);

    return m_bIsAWRun ;
}

void AssassinWar::initMainWin()
{
    setWindowFlags(Qt::FramelessWindowHint);

    initGameScreen_();

    initToolbarManager_();

    initChoosingMapDlg_();

    initToolbar_();

    initRepainter_();

    initBackground_("./AssassinsWar.jpg");

    showMainWin_();
}

void AssassinWar::initToolbar_()
{
    m_pToolbar = addToolBar(tr("MainToolbar"));
    m_pToolbar->addAction(m_pToolbarManager->getButtonHost());
    m_pToolbar->addAction(m_pToolbarManager->getButtonJoin());
    m_pToolbar->addAction(m_pToolbarManager->getButtonHelp());
    m_pToolbar->addAction(m_pToolbarManager->getButtonSetting());
    m_pToolbar->setIconSize(QSize(ICON_SIZE, ICON_SIZE));
    m_pToolbar->setMovable(false);
    m_pToolbar->setVisible(false);

    connect(m_pToolbarManager->getButtonHost(), SIGNAL(triggered()), this, SLOT(onButttonHost_()));
}

void AssassinWar::initBackground_(const QString& strBackgroundImagePath)
{
    QImage background;
    background.load(strBackgroundImagePath);
    m_background = QPixmap::fromImage(background.scaled(size(), Qt::KeepAspectRatioByExpanding));
}

void AssassinWar::initToolbarManager_()
{
    m_pToolbarManager = new ToolbarManager();
    m_pToolbarManager->initialize();
}

void AssassinWar::initRepainter_()
{
    m_pRepaintTimer = new QTimer(this);
    connect(m_pRepaintTimer, SIGNAL(timeout()), this, SLOT(repaint()));
    m_pRepaintTimer->start(250);
}

void AssassinWar::initChoosingMapDlg_()
{
    m_pChoosingMapDlg = new ChoosingMapDlg(this);
    m_pChoosingMapDlg->initialize();
    connect(m_pChoosingMapDlg, SIGNAL(createGame(QString)), this, SLOT(runAW_(QString)));
    connect(m_pChoosingMapDlg, SIGNAL(cancelCreateGame()), this, SLOT(showMainWin_()));
}

void AssassinWar::showMainWin_()
{
    resize(MAIN_WIN_WIDTH, MAIN_WIN_WIDTH / 2);

    initBackground_("./AssassinsWar.jpg");

    setMouseTracking(true);
}

void AssassinWar::initGameScreen_()
{
    m_pGameScreen = new GameScreen(m_iScreenWidth, m_iScreenHeight);

    m_pGameScreen->initScreen();

    m_pGameScreen->setStyleSheet("background-color:transparent;");

    setCentralWidget(m_pGameScreen);
}
<commit_msg>fix a bug if Resolution too small,Screen change camera crazy<commit_after>#include <QTimer>
#include <QAction>
#include <QPainter>
#include <QToolBar>
#include <QMouseEvent>

#include "CommentLib.h"

#include "AssassinWar.h"
#include "GameScreen.h"
#include "MapManager.h"
#include "ToolbarManager.h"
#include "ChoosingMapDlg.h"
#include "CharacterManager.h"
#include "PixelCoordinateTransfer.h"

const int ICON_SIZE = 45;
const int MAIN_WIN_WIDTH = 850;
const int ENSURE_VISIBLE_BOUNDARY_DISTANCE = 250;

AssassinWar::AssassinWar(const int &iWidth, const int &iHeight,
                         QWidget *parent, Qt::WFlags flags)
    : QMainWindow(parent, flags),
      m_pRepaintTimer(NULL), m_pToolbar(NULL), m_pGameScreen(NULL),
      m_pToolbarManager(NULL), m_pChoosingMapDlg(NULL),
      m_bIsAWRun(false),
      m_iScreenWidth(iWidth), m_iScreenHeight(iHeight)
{

}

AssassinWar::~AssassinWar()
{
    if(NULL != m_pGameScreen)
    {
        delete m_pGameScreen;
        m_pGameScreen = NULL;
    }

    if(NULL != m_pRepaintTimer)
    {
        m_pRepaintTimer->stop();
    }

    if(NULL != m_pToolbarManager)
    {
        delete m_pToolbarManager;
        m_pToolbarManager = NULL;
    }
}

void AssassinWar::mouseMoveEvent(QMouseEvent *mouseEvent)
{
    if(ICON_SIZE > mouseEvent->pos().y() && !m_bIsAWRun)
    {
        m_pToolbar->setVisible(true);
    }
    else
    {
        m_pToolbar->setVisible(false);
    }
}

void AssassinWar::paintEvent(QPaintEvent *paintEvent)
{
    QPainter painter(this);

    painter.drawPixmap(0, 0, m_background);

    if(m_bIsAWRun)
    {
        int iPlayerX = PixelCoordinateTransfer::instance().gridXToPixelCoordinateX(CharacterManager::instance().getPlayerCharacterGridX());
        int iPlayerY = PixelCoordinateTransfer::instance().gridYToPixelCoordinateY(CharacterManager::instance().getPlayerCharacterGridY());
        m_pGameScreen->ensureVisible(iPlayerX, iPlayerY, ENSURE_VISIBLE_BOUNDARY_DISTANCE, ENSURE_VISIBLE_BOUNDARY_DISTANCE);
        CharacterManager::instance().drawAllCharacter(painter, m_pGameScreen->getScreenOffsetX(), m_pGameScreen->getScreenOffsetY());
    }
}

void AssassinWar::onButttonHost_()
{
    setMouseTracking(false);
    m_pToolbar->setVisible(false);

    m_pChoosingMapDlg->updateMapList(MapManager::instance().getMapList());
    m_pChoosingMapDlg->show();

}

bool AssassinWar::runAW_(const QString& strCurrntMapName)
{
    m_pChoosingMapDlg->hide();

    setWindowState(Qt::WindowFullScreen);

    initBackground_(MapManager::instance().getMapBackground(strCurrntMapName));

    m_bIsAWRun = m_pGameScreen->openScreen(strCurrntMapName);

    return m_bIsAWRun ;
}

void AssassinWar::initMainWin()
{
    setWindowFlags(Qt::FramelessWindowHint);

    initGameScreen_();

    initToolbarManager_();

    initChoosingMapDlg_();

    initToolbar_();

    initRepainter_();

    initBackground_("./AssassinsWar.jpg");

    showMainWin_();
}

void AssassinWar::initToolbar_()
{
    m_pToolbar = addToolBar(tr("MainToolbar"));
    m_pToolbar->addAction(m_pToolbarManager->getButtonHost());
    m_pToolbar->addAction(m_pToolbarManager->getButtonJoin());
    m_pToolbar->addAction(m_pToolbarManager->getButtonHelp());
    m_pToolbar->addAction(m_pToolbarManager->getButtonSetting());
    m_pToolbar->setIconSize(QSize(ICON_SIZE, ICON_SIZE));
    m_pToolbar->setMovable(false);
    m_pToolbar->setVisible(false);

    connect(m_pToolbarManager->getButtonHost(), SIGNAL(triggered()), this, SLOT(onButttonHost_()));
}

void AssassinWar::initBackground_(const QString& strBackgroundImagePath)
{
    QImage background;
    background.load(strBackgroundImagePath);
    m_background = QPixmap::fromImage(background.scaled(size(), Qt::KeepAspectRatioByExpanding));
}

void AssassinWar::initToolbarManager_()
{
    m_pToolbarManager = new ToolbarManager();
    m_pToolbarManager->initialize();
}

void AssassinWar::initRepainter_()
{
    m_pRepaintTimer = new QTimer(this);
    connect(m_pRepaintTimer, SIGNAL(timeout()), this, SLOT(repaint()));
    m_pRepaintTimer->start(250);
}

void AssassinWar::initChoosingMapDlg_()
{
    m_pChoosingMapDlg = new ChoosingMapDlg(this);
    m_pChoosingMapDlg->initialize();
    connect(m_pChoosingMapDlg, SIGNAL(createGame(QString)), this, SLOT(runAW_(QString)));
    connect(m_pChoosingMapDlg, SIGNAL(cancelCreateGame()), this, SLOT(showMainWin_()));
}

void AssassinWar::showMainWin_()
{
    resize(MAIN_WIN_WIDTH, MAIN_WIN_WIDTH / 2);

    initBackground_("./AssassinsWar.jpg");

    setMouseTracking(true);
}

void AssassinWar::initGameScreen_()
{
    m_pGameScreen = new GameScreen(m_iScreenWidth, m_iScreenHeight);

    m_pGameScreen->initScreen();

    m_pGameScreen->setStyleSheet("background-color:transparent;");

    setCentralWidget(m_pGameScreen);
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#include <fb/fbjni/CoreClasses.h>

#include <fb/assert.h>
#include <fb/log.h>

#include <alloca.h>
#include <cstdlib>
#include <ios>
#include <stdexcept>
#include <stdio.h>
#include <string>
#include <system_error>

#include <jni.h>

namespace facebook {
namespace jni {

namespace {
class JRuntimeException : public JavaClass<JRuntimeException, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Ljava/lang/RuntimeException;";

  static local_ref<JRuntimeException> create(const char* str) {
    return newInstance(make_jstring(str));
  }

  static local_ref<JRuntimeException> create() {
    return newInstance();
  }
};

class JIOException : public JavaClass<JIOException, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Ljava/io/IOException;";

  static local_ref<JIOException> create(const char* str) {
    return newInstance(make_jstring(str));
  }
};

class JOutOfMemoryError : public JavaClass<JOutOfMemoryError, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Ljava/lang/OutOfMemoryError;";

  static local_ref<JOutOfMemoryError> create(const char* str) {
    return newInstance(make_jstring(str));
  }
};

class JArrayIndexOutOfBoundsException : public JavaClass<JArrayIndexOutOfBoundsException, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Ljava/lang/ArrayIndexOutOfBoundsException;";

  static local_ref<JArrayIndexOutOfBoundsException> create(const char* str) {
    return newInstance(make_jstring(str));
  }
};

class JUnknownCppException : public JavaClass<JUnknownCppException, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Lcom/facebook/jni/UnknownCppException;";

  static local_ref<JUnknownCppException> create() {
    return newInstance();
  }

  static local_ref<JUnknownCppException> create(const char* str) {
    return newInstance(make_jstring(str));
  }
};

class JCppSystemErrorException : public JavaClass<JCppSystemErrorException, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Lcom/facebook/jni/CppSystemErrorException;";

  static local_ref<JCppSystemErrorException> create(const std::system_error& e) {
    return newInstance(make_jstring(e.what()), e.code().value());
  }
};

// Exception throwing & translating functions //////////////////////////////////////////////////////

// Functions that throw Java exceptions

void setJavaExceptionAndAbortOnFailure(alias_ref<JThrowable> throwable) {
  auto env = Environment::current();
  if (throwable) {
    env->Throw(throwable.get());
  }
  if (env->ExceptionCheck() != JNI_TRUE) {
    std::abort();
  }
}

}

// Functions that throw C++ exceptions

// TODO(T6618159) Take a stack dump here to save context if it results in a crash when propagated
void throwPendingJniExceptionAsCppException() {
  JNIEnv* env = Environment::current();
  if (env->ExceptionCheck() == JNI_FALSE) {
    return;
  }

  auto throwable = adopt_local(env->ExceptionOccurred());
  if (!throwable) {
    throw std::runtime_error("Unable to get pending JNI exception.");
  }
  env->ExceptionClear();

  throw JniException(throwable);
}

void throwCppExceptionIf(bool condition) {
  if (!condition) {
    return;
  }

  auto env = Environment::current();
  if (env->ExceptionCheck() == JNI_TRUE) {
    throwPendingJniExceptionAsCppException();
    return;
  }

  throw JniException();
}

void throwNewJavaException(jthrowable throwable) {
  throw JniException(wrap_alias(throwable));
}

void throwNewJavaException(const char* throwableName, const char* msg) {
  // If anything of the fbjni calls fail, an exception of a suitable
  // form will be thrown, which is what we want.
  auto throwableClass = findClassLocal(throwableName);
  auto throwable = throwableClass->newObject(
    throwableClass->getConstructor<jthrowable(jstring)>(),
    make_jstring(msg).release());
  throwNewJavaException(throwable.get());
}

// Translate C++ to Java Exception

namespace {

// The implementation std::rethrow_if_nested uses a dynamic_cast to determine
// if the exception is a nested_exception. If the exception is from a library
// built with -fno-rtti, then that will crash. This avoids that.
void rethrow_if_nested() {
  try {
    throw;
  } catch (const std::nested_exception& e) {
    e.rethrow_nested();
  } catch (...) {
  }
}

// For each exception in the chain of the currently handled exception, func
// will be called with that exception as the currently handled exception (in
// reverse order, i.e. innermost first).
void denest(std::function<void()> func) {
<commit_msg>Lines authored by ritzau<commit_after>/*
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#include <fb/fbjni/CoreClasses.h>

#include <fb/assert.h>
#include <fb/log.h>

#include <alloca.h>
#include <cstdlib>
#include <ios>
#include <stdexcept>
#include <stdio.h>
#include <string>
#include <system_error>

#include <jni.h>

namespace facebook {
namespace jni {

namespace {
class JRuntimeException : public JavaClass<JRuntimeException, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Ljava/lang/RuntimeException;";

  static local_ref<JRuntimeException> create(const char* str) {
    return newInstance(make_jstring(str));
  }

  static local_ref<JRuntimeException> create() {
    return newInstance();
  }
};

class JIOException : public JavaClass<JIOException, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Ljava/io/IOException;";

  static local_ref<JIOException> create(const char* str) {
    return newInstance(make_jstring(str));
  }
};

class JOutOfMemoryError : public JavaClass<JOutOfMemoryError, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Ljava/lang/OutOfMemoryError;";

  static local_ref<JOutOfMemoryError> create(const char* str) {
    return newInstance(make_jstring(str));
  }
};

class JArrayIndexOutOfBoundsException : public JavaClass<JArrayIndexOutOfBoundsException, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Ljava/lang/ArrayIndexOutOfBoundsException;";

  static local_ref<JArrayIndexOutOfBoundsException> create(const char* str) {
    return newInstance(make_jstring(str));
  }
};

class JUnknownCppException : public JavaClass<JUnknownCppException, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Lcom/facebook/jni/UnknownCppException;";

  static local_ref<JUnknownCppException> create() {
    return newInstance();
  }

  static local_ref<JUnknownCppException> create(const char* str) {
    return newInstance(make_jstring(str));
  }
};

class JCppSystemErrorException : public JavaClass<JCppSystemErrorException, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Lcom/facebook/jni/CppSystemErrorException;";

  static local_ref<JCppSystemErrorException> create(const std::system_error& e) {
    return newInstance(make_jstring(e.what()), e.code().value());
  }
};

// Exception throwing & translating functions //////////////////////////////////////////////////////

// Functions that throw Java exceptions

void setJavaExceptionAndAbortOnFailure(alias_ref<JThrowable> throwable) {
  auto env = Environment::current();
  if (throwable) {
    env->Throw(throwable.get());
  }
  if (env->ExceptionCheck() != JNI_TRUE) {
    std::abort();
  }
}

}

// Functions that throw C++ exceptions

// TODO(T6618159) Take a stack dump here to save context if it results in a crash when propagated
void throwPendingJniExceptionAsCppException() {
  JNIEnv* env = Environment::current();
  if (env->ExceptionCheck() == JNI_FALSE) {
    return;
  }

  auto throwable = adopt_local(env->ExceptionOccurred());
  if (!throwable) {
    throw std::runtime_error("Unable to get pending JNI exception.");
  }
  env->ExceptionClear();

  throw JniException(throwable);
}

void throwCppExceptionIf(bool condition) {
  if (!condition) {
    return;
  }

  auto env = Environment::current();
  if (env->ExceptionCheck() == JNI_TRUE) {
    throwPendingJniExceptionAsCppException();
    return;
  }

  throw JniException();
}

void throwNewJavaException(jthrowable throwable) {
  throw JniException(wrap_alias(throwable));
}

void throwNewJavaException(const char* throwableName, const char* msg) {
  // If anything of the fbjni calls fail, an exception of a suitable
  // form will be thrown, which is what we want.
  auto throwableClass = findClassLocal(throwableName);
  auto throwable = throwableClass->newObject(
    throwableClass->getConstructor<jthrowable(jstring)>(),
    make_jstring(msg).release());
  throwNewJavaException(throwable.get());
}

// Translate C++ to Java Exception

namespace {

// The implementation std::rethrow_if_nested uses a dynamic_cast to determine
// if the exception is a nested_exception. If the exception is from a library
// built with -fno-rtti, then that will crash. This avoids that.
void rethrow_if_nested() {
  try {
    throw;
  } catch (const std::nested_exception& e) {
    e.rethrow_nested();
  } catch (...) {
  }
}

// For each exception in the chain of the currently handled exception, func
// will be called with that exception as the currently handled exception (in
// reverse order, i.e. innermost first).
void denest(std::function<void()> func) {
  try {
<|endoftext|>


<commit_before>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>
#include <list>
#include <windows.h>
#include <commctrl.h>
#include "base/command_line.h"
#include "base/event_recorder.h"
#include "base/gfx/native_theme.h"
#include "base/resource_util.h"
#include "base/win_util.h"
#include "webkit/tools/test_shell/foreground_helper.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"

TestShellPlatformDelegate::TestShellPlatformDelegate(
    const CommandLine& command_line)
    : command_line_(command_line) {
#ifdef _CRTDBG_MAP_ALLOC
  _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
#endif
}

TestShellPlatformDelegate::~TestShellPlatformDelegate() {
#ifdef _CRTDBG_MAP_ALLOC
  _CrtDumpMemoryLeaks();
#endif
}

void TestShellPlatformDelegate::PreflightArgs(int *argc, char ***argv) {
}

// This test approximates whether you are running the default themes for
// your platform by inspecting a couple of metrics.
// It does not catch all cases, but it does pick up on classic vs xp,
// and normal vs large fonts. Something it misses is changes to the color
// scheme (which will infact cause pixel test failures).
bool TestShellPlatformDelegate::CheckLayoutTestSystemDependencies() {
  std::list<std::string> errors;

  OSVERSIONINFOEX osvi;
  ::ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
  osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
  ::GetVersionEx((OSVERSIONINFO *)&osvi);

  // default to XP metrics, override if on Vista
  int requiredVScrollSize = 17;
  int requiredFontSize = -11; // 8 pt
  const WCHAR *requiredFont = L"Tahoma";
  bool isVista = false;
  if (osvi.dwMajorVersion == 6
      && osvi.dwMinorVersion == 0
      && osvi.wProductType == VER_NT_WORKSTATION) {
    requiredFont = L"Segoe UI";
    requiredFontSize = -12; // 9 pt
    isVista = true;
  } else if (osvi.dwMajorVersion == 5
             && osvi.dwMinorVersion == 1
             && osvi.wProductType == VER_NT_WORKSTATION) {
    // XP;
  } else {
    errors.push_back("Unsupported Operating System version "
                     "(must use XP or Vista)");
  }

  // on both XP and Vista, this metric will be 17 when font size is "Normal".
  // The size of drop-down menus depends on it.
  int vScrollSize = ::GetSystemMetrics(SM_CXVSCROLL);
  if (vScrollSize != requiredVScrollSize) {
    errors.push_back("Must use normal size fonts (96 dpi)");
  }

  // font smoothing (including ClearType) must be disabled
  BOOL bFontSmoothing;
  SystemParametersInfo(SPI_GETFONTSMOOTHING, (UINT)0,
                       (PVOID)&bFontSmoothing, (UINT)0);
  if (bFontSmoothing) {
    errors.push_back("Font smoothing (ClearType) must be disabled");
  }

  // Check that we're using the default system fonts
  NONCLIENTMETRICS metrics;
  win_util::GetNonClientMetrics(&metrics);
  LOGFONTW* system_fonts[] =
  { &metrics.lfStatusFont, &metrics.lfMenuFont, &metrics.lfSmCaptionFont };

  for (size_t i = 0; i < arraysize(system_fonts); ++i) {
    if (system_fonts[i]->lfHeight != requiredFontSize ||
        wcscmp(requiredFont, system_fonts[i]->lfFaceName)) {
      if (isVista)
        errors.push_back("Must use either the Aero or Basic theme");
      else
        errors.push_back("Must use the default XP theme (Luna)");
      break;
    }
  }

  if (!errors.empty()) {
    fprintf(stderr, "%s",
      "##################################################################\n"
      "## Layout test system dependencies check failed.\n"
      "##\n");
    for (std::list<std::string>::iterator it = errors.begin();
         it != errors.end();
         ++it) {
      fprintf(stderr, "## %s\n", it->c_str());
    }
    fprintf(stderr, "%s",
      "##\n"
      "##################################################################\n");
  }
  return errors.empty();
}

void TestShellPlatformDelegate::SuppressErrorReporting() {
  _set_abort_behavior(0, _WRITE_ABORT_MSG);
}

void TestShellPlatformDelegate::InitializeGUI() {
  INITCOMMONCONTROLSEX InitCtrlEx;

  InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
  InitCtrlEx.dwICC  = ICC_STANDARD_CLASSES;
  InitCommonControlsEx(&InitCtrlEx);
  TestShell::RegisterWindowClass();
}

void TestShellPlatformDelegate::SelectUnifiedTheme() {
  gfx::NativeTheme::instance()->DisableTheming();
}

void TestShellPlatformDelegate::SetWindowPositionForRecording(
    TestShell *shell) {
  // Move the window to the upper left corner for consistent
  // record/playback mode.  For automation, we want this to work
  // on build systems where the script invoking us is a background
  // process.  So for this case, make our window the topmost window
  // as well.
  ForegroundHelper::SetForeground(shell->mainWnd());
  ::SetWindowPos(shell->mainWnd(), HWND_TOP, 0, 0, 600, 800, 0);
}
<commit_msg>Modify change in CL 21434 - allow standard font smoothing as well as none<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>
#include <list>
#include <windows.h>
#include <commctrl.h>
#include "base/command_line.h"
#include "base/event_recorder.h"
#include "base/gfx/native_theme.h"
#include "base/resource_util.h"
#include "base/win_util.h"
#include "webkit/tools/test_shell/foreground_helper.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"

TestShellPlatformDelegate::TestShellPlatformDelegate(
    const CommandLine& command_line)
    : command_line_(command_line) {
#ifdef _CRTDBG_MAP_ALLOC
  _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
#endif
}

TestShellPlatformDelegate::~TestShellPlatformDelegate() {
#ifdef _CRTDBG_MAP_ALLOC
  _CrtDumpMemoryLeaks();
#endif
}

void TestShellPlatformDelegate::PreflightArgs(int *argc, char ***argv) {
}

// This test approximates whether you are running the default themes for
// your platform by inspecting a couple of metrics.
// It does not catch all cases, but it does pick up on classic vs xp,
// and normal vs large fonts. Something it misses is changes to the color
// scheme (which will infact cause pixel test failures).
bool TestShellPlatformDelegate::CheckLayoutTestSystemDependencies() {
  std::list<std::string> errors;

  OSVERSIONINFOEX osvi;
  ::ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
  osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
  ::GetVersionEx((OSVERSIONINFO *)&osvi);

  // default to XP metrics, override if on Vista
  int requiredVScrollSize = 17;
  int requiredFontSize = -11; // 8 pt
  const WCHAR *requiredFont = L"Tahoma";
  bool isVista = false;
  if (osvi.dwMajorVersion == 6
      && osvi.dwMinorVersion == 0
      && osvi.wProductType == VER_NT_WORKSTATION) {
    requiredFont = L"Segoe UI";
    requiredFontSize = -12; // 9 pt
    isVista = true;
  } else if (osvi.dwMajorVersion == 5
             && osvi.dwMinorVersion == 1
             && osvi.wProductType == VER_NT_WORKSTATION) {
    // XP;
  } else {
    errors.push_back("Unsupported Operating System version "
                     "(must use XP or Vista).");
  }

  // on both XP and Vista, this metric will be 17 when font size is "Normal".
  // The size of drop-down menus depends on it.
  int vScrollSize = ::GetSystemMetrics(SM_CXVSCROLL);
  if (vScrollSize != requiredVScrollSize) {
    errors.push_back("Must use normal size fonts (96 dpi).");
  }

  // ClearType must be disabled, because the rendering is unpredictable.
  BOOL bFontSmoothing;
  SystemParametersInfo(SPI_GETFONTSMOOTHING, (UINT)0,
                       (PVOID)&bFontSmoothing, (UINT)0);
  int fontSmoothingType;
  SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, (UINT)0,
                       (PVOID)&fontSmoothingType, (UINT)0);
  if (bFontSmoothing && (fontSmoothingType == FE_FONTSMOOTHINGCLEARTYPE)) {
    errors.push_back("ClearType must be disabled.");
  }

  // Check that we're using the default system fonts
  NONCLIENTMETRICS metrics;
  win_util::GetNonClientMetrics(&metrics);
  LOGFONTW* system_fonts[] =
  { &metrics.lfStatusFont, &metrics.lfMenuFont, &metrics.lfSmCaptionFont };

  for (size_t i = 0; i < arraysize(system_fonts); ++i) {
    if (system_fonts[i]->lfHeight != requiredFontSize ||
        wcscmp(requiredFont, system_fonts[i]->lfFaceName)) {
      if (isVista)
        errors.push_back("Must use either the Aero or Basic theme.");
      else
        errors.push_back("Must use the default XP theme (Luna).");
      break;
    }
  }

  if (!errors.empty()) {
    fprintf(stderr, "%s",
      "##################################################################\n"
      "## Layout test system dependencies check failed.\n"
      "##\n");
    for (std::list<std::string>::iterator it = errors.begin();
         it != errors.end();
         ++it) {
      fprintf(stderr, "## %s\n", it->c_str());
    }
    fprintf(stderr, "%s",
      "##\n"
      "##################################################################\n");
  }
  return errors.empty();
}

void TestShellPlatformDelegate::SuppressErrorReporting() {
  _set_abort_behavior(0, _WRITE_ABORT_MSG);
}

void TestShellPlatformDelegate::InitializeGUI() {
  INITCOMMONCONTROLSEX InitCtrlEx;

  InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
  InitCtrlEx.dwICC  = ICC_STANDARD_CLASSES;
  InitCommonControlsEx(&InitCtrlEx);
  TestShell::RegisterWindowClass();
}

void TestShellPlatformDelegate::SelectUnifiedTheme() {
  gfx::NativeTheme::instance()->DisableTheming();
}

void TestShellPlatformDelegate::SetWindowPositionForRecording(
    TestShell *shell) {
  // Move the window to the upper left corner for consistent
  // record/playback mode.  For automation, we want this to work
  // on build systems where the script invoking us is a background
  // process.  So for this case, make our window the topmost window
  // as well.
  ForegroundHelper::SetForeground(shell->mainWnd());
  ::SetWindowPos(shell->mainWnd(), HWND_TOP, 0, 0, 600, 800, 0);
}
<|endoftext|>