<commit_before>#ifndef AMGCL_RELAXATION_RUNTIME_HPP
#define AMGCL_RELAXATION_RUNTIME_HPP

/*
The MIT License

Copyright (c) 2012-2016 Denis Demidov <dennis.demidov@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
 * \file   amgcl/relaxation/runtime.hpp
 * \author Denis Demidov <dennis.demidov@gmail.com>
 * \brief  Runtime-configurable smoother as standalone preconditioner.
 */

#include <amgcl/runtime.hpp>
#include <amgcl/relaxation/as_preconditioner.hpp>

namespace amgcl {
namespace runtime {
namespace relaxation {

namespace detail {

template <
    class Backend,
    template <class> class Relaxation,
    class Func
    >
inline
typename boost::enable_if<
    typename backend::relaxation_is_supported<Backend, Relaxation>::type,
    void
>::type
process_rap(const Func &func) {
    typedef amgcl::relaxation::as_preconditioner<Backend, Relaxation> RAP;
    func.template process<RAP>();
}

template <
    class Backend,
    template <class> class Relaxation,
    class Func
    >
inline
typename boost::disable_if<
    typename backend::relaxation_is_supported<Backend, Relaxation>::type,
    void
>::type
process_rap(const Func &func) {
    throw std::logic_error("The relaxation scheme is not supported by the backend");
}

template <class Backend, class Func>
void process_rap(runtime::relaxation::type relaxation, const Func &func) {
    switch (relaxation) {
        case runtime::relaxation::gauss_seidel:
            process_rap<Backend, amgcl::relaxation::gauss_seidel>(func);
            break;
        case runtime::relaxation::multicolor_gauss_seidel:
            process_rap<Backend, amgcl::relaxation::multicolor_gauss_seidel>(func);
            break;
        case runtime::relaxation::ilu0:
            process_rap<Backend, amgcl::relaxation::ilu0>(func);
            break;
        case runtime::relaxation::parallel_ilu0:
            process_rap<Backend, amgcl::relaxation::parallel_ilu0>(func);
            break;
        case runtime::relaxation::ilut:
            process_rap<Backend, amgcl::relaxation::ilut>(func);
            break;
        case runtime::relaxation::damped_jacobi:
            process_rap<Backend, amgcl::relaxation::damped_jacobi>(func);
            break;
        case runtime::relaxation::spai0:
            process_rap<Backend, amgcl::relaxation::spai0>(func);
            break;
        case runtime::relaxation::spai1:
            process_rap<Backend, amgcl::relaxation::spai1>(func);
            break;
        case runtime::relaxation::chebyshev:
            process_rap<Backend, amgcl::relaxation::chebyshev>(func);
            break;
    }
}

template <class Backend, class Matrix>
struct rap_create {
    typedef boost::property_tree::ptree params;
    typedef typename Backend::params backend_params;

    void * &handle;
    const Matrix &A;
    const params &p;
    const backend_params &bp;

    rap_create(void* &handle, const Matrix &A, const params &p, const backend_params &bp)
        : handle(handle), A(A), p(p), bp(bp) {}

    template <class RAP>
    void process() const {
        handle = static_cast<void*>(new RAP(A, p, bp));
    }
};

struct rap_destroy {
    void * handle;

    rap_destroy(void *handle) : handle(handle) {}

    template <class RAP>
    void process() const {
        delete static_cast<RAP*>(handle);
    }
};

template <class Vec1, class Vec2>
struct rap_apply {
    void * handle;
    Vec1 const &rhs;
    Vec2 &x;

    rap_apply(void *handle, const Vec1 &rhs, Vec2 &x)
        : handle(handle), rhs(rhs), x(x) {}

    template <class RAP>
    void process() const {
        static_cast<RAP*>(handle)->apply(rhs, x);
    }
};

template <class Matrix>
struct rap_matrix {
    void * handle;
    const Matrix * &A;

    rap_matrix(void *handle, const Matrix * &A) : handle(handle), A(A) {}

    template <class RAP>
    void process() const {
        A = &(static_cast<RAP*>(handle)->system_matrix());
    }
};

}

/// Use one of AMGCL smoothers as standalone preconditioner.
/**
 * The exact smoother is selected at runtime through prm.type parameter
 */
template <class Backend>
class as_preconditioner {
    public:
        typedef Backend backend_type;

        typedef typename Backend::matrix  matrix;

        typedef boost::property_tree::ptree params;
        typedef typename Backend::params  backend_params;

        template <class Matrix>
        as_preconditioner(
                const Matrix &A,
                const params &prm = params(),
                const backend_params &bprm = backend_params()
                )
            : relaxation(prm.get("type", runtime::relaxation::spai0)),
              handle(0)
        {
            runtime::relaxation::detail::process_rap<Backend>(
                    relaxation,
                    runtime::relaxation::detail::rap_create<Backend, Matrix>(
                        handle, A, prm, bprm
                        )
                    );
        }

        ~as_preconditioner() {
            runtime::relaxation::detail::process_rap<Backend>(
                    relaxation,
                    runtime::relaxation::detail::rap_destroy(handle)
                    );
        }

        template <class Vec1, class Vec2>
        void apply(
                const Vec1 &rhs,
#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES
                Vec2       &x
#else
                Vec2       &&x
#endif
                ) const
        {
            runtime::relaxation::detail::process_rap<Backend>(
                    relaxation,
                    runtime::relaxation::detail::rap_apply<Vec1, Vec2>(
                        handle, rhs, x
                        )
                    );
        }

        const matrix& system_matrix() const {
            const matrix *A = 0;

            runtime::relaxation::detail::process_rap<Backend>(
                    relaxation,
                    runtime::relaxation::detail::rap_matrix<matrix>(handle, A)
                    );

            return *A;
        }
    private:
        runtime::relaxation::type relaxation;
        void * handle;
};

}
}
}

#endif
<commit_msg>Provide ostream output operator for relaxation::as_preconditioner<commit_after>#ifndef AMGCL_RELAXATION_RUNTIME_HPP
#define AMGCL_RELAXATION_RUNTIME_HPP

/*
The MIT License

Copyright (c) 2012-2016 Denis Demidov <dennis.demidov@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
 * \file   amgcl/relaxation/runtime.hpp
 * \author Denis Demidov <dennis.demidov@gmail.com>
 * \brief  Runtime-configurable smoother as standalone preconditioner.
 */

#include <amgcl/runtime.hpp>
#include <amgcl/relaxation/as_preconditioner.hpp>

namespace amgcl {
namespace runtime {
namespace relaxation {

namespace detail {

template <
    class Backend,
    template <class> class Relaxation,
    class Func
    >
inline
typename boost::enable_if<
    typename backend::relaxation_is_supported<Backend, Relaxation>::type,
    void
>::type
process_rap(const Func &func) {
    typedef amgcl::relaxation::as_preconditioner<Backend, Relaxation> RAP;
    func.template process<RAP>();
}

template <
    class Backend,
    template <class> class Relaxation,
    class Func
    >
inline
typename boost::disable_if<
    typename backend::relaxation_is_supported<Backend, Relaxation>::type,
    void
>::type
process_rap(const Func &func) {
    throw std::logic_error("The relaxation scheme is not supported by the backend");
}

template <class Backend, class Func>
void process_rap(runtime::relaxation::type relaxation, const Func &func) {
    switch (relaxation) {
        case runtime::relaxation::gauss_seidel:
            process_rap<Backend, amgcl::relaxation::gauss_seidel>(func);
            break;
        case runtime::relaxation::multicolor_gauss_seidel:
            process_rap<Backend, amgcl::relaxation::multicolor_gauss_seidel>(func);
            break;
        case runtime::relaxation::ilu0:
            process_rap<Backend, amgcl::relaxation::ilu0>(func);
            break;
        case runtime::relaxation::parallel_ilu0:
            process_rap<Backend, amgcl::relaxation::parallel_ilu0>(func);
            break;
        case runtime::relaxation::ilut:
            process_rap<Backend, amgcl::relaxation::ilut>(func);
            break;
        case runtime::relaxation::damped_jacobi:
            process_rap<Backend, amgcl::relaxation::damped_jacobi>(func);
            break;
        case runtime::relaxation::spai0:
            process_rap<Backend, amgcl::relaxation::spai0>(func);
            break;
        case runtime::relaxation::spai1:
            process_rap<Backend, amgcl::relaxation::spai1>(func);
            break;
        case runtime::relaxation::chebyshev:
            process_rap<Backend, amgcl::relaxation::chebyshev>(func);
            break;
    }
}

template <class Backend, class Matrix>
struct rap_create {
    typedef boost::property_tree::ptree params;
    typedef typename Backend::params backend_params;

    void * &handle;
    const Matrix &A;
    const params &p;
    const backend_params &bp;

    rap_create(void* &handle, const Matrix &A, const params &p, const backend_params &bp)
        : handle(handle), A(A), p(p), bp(bp) {}

    template <class RAP>
    void process() const {
        handle = static_cast<void*>(new RAP(A, p, bp));
    }
};

struct rap_destroy {
    void * handle;

    rap_destroy(void *handle) : handle(handle) {}

    template <class RAP>
    void process() const {
        delete static_cast<RAP*>(handle);
    }
};

template <class Vec1, class Vec2>
struct rap_apply {
    void * handle;
    Vec1 const &rhs;
    Vec2 &x;

    rap_apply(void *handle, const Vec1 &rhs, Vec2 &x)
        : handle(handle), rhs(rhs), x(x) {}

    template <class RAP>
    void process() const {
        static_cast<RAP*>(handle)->apply(rhs, x);
    }
};

template <class Matrix>
struct rap_matrix {
    void * handle;
    const Matrix * &A;

    rap_matrix(void *handle, const Matrix * &A) : handle(handle), A(A) {}

    template <class RAP>
    void process() const {
        A = &(static_cast<RAP*>(handle)->system_matrix());
    }
};

}

/// Use one of AMGCL smoothers as standalone preconditioner.
/**
 * The exact smoother is selected at runtime through prm.type parameter
 */
template <class Backend>
class as_preconditioner {
    public:
        typedef Backend backend_type;

        typedef typename Backend::matrix  matrix;

        typedef boost::property_tree::ptree params;
        typedef typename Backend::params  backend_params;

        template <class Matrix>
        as_preconditioner(
                const Matrix &A,
                const params &prm = params(),
                const backend_params &bprm = backend_params()
                )
            : relaxation(prm.get("type", runtime::relaxation::spai0)),
              handle(0)
        {
            runtime::relaxation::detail::process_rap<Backend>(
                    relaxation,
                    runtime::relaxation::detail::rap_create<Backend, Matrix>(
                        handle, A, prm, bprm
                        )
                    );
        }

        ~as_preconditioner() {
            runtime::relaxation::detail::process_rap<Backend>(
                    relaxation,
                    runtime::relaxation::detail::rap_destroy(handle)
                    );
        }

        template <class Vec1, class Vec2>
        void apply(
                const Vec1 &rhs,
#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES
                Vec2       &x
#else
                Vec2       &&x
#endif
                ) const
        {
            runtime::relaxation::detail::process_rap<Backend>(
                    relaxation,
                    runtime::relaxation::detail::rap_apply<Vec1, Vec2>(
                        handle, rhs, x
                        )
                    );
        }

        const matrix& system_matrix() const {
            const matrix *A = 0;

            runtime::relaxation::detail::process_rap<Backend>(
                    relaxation,
                    runtime::relaxation::detail::rap_matrix<matrix>(handle, A)
                    );

            return *A;
        }
    private:
        runtime::relaxation::type relaxation;
        void * handle;

        friend std::ostream& operator<<(std::ostream &os, const as_preconditioner &p)
        {
            os << "Using " << p.relaxation << " as preconditioner" << std::endl;
            os << "  unknowns: " << backend::rows(p.system_matrix()) << std::endl;
            os << "  nonzeros: " << backend::nonzeros(p.system_matrix()) << std::endl;
            return os;
        }
};

}
}
}

#endif
<|endoftext|>


<commit_before><commit_msg>TopCoder SRM647. Div2-250.<commit_after><|endoftext|>


<commit_before>// @(#)root/eg:$Id$
// Author: Pasha Murat   12/02/99

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//______________________________________________________________________________
//
// Description of the static properties of a particle.
// The class is typically generated by the TDatabasePDG class.
// It is referenced by the dynamic particle class TParticle.
//  Int_t            fPdgCode;          // PDG code of the particle
//  Double_t         fMass;             // particle mass in GeV
//  Double_t         fCharge;           // charge in units of |e|/3
//  Double_t         fLifetime;         // proper lifetime in nanoseconds
//  Double_t         fWidth;            // total width in GeV
//  Int_t            fParity;
//  Double_t         fSpin;
//  Double_t         fIsospin;          // isospin
//  Double_t         fI3;               // i3
//  Int_t            fStrangeness;      // flavours are defined if i3 != -1
//  Int_t            fCharm;            // 1 or -1 for C-particles,  0 for others
//  Int_t            fBeauty;           //
//  Int_t            fTop;              //
//  Int_t            fY;                // X,Y: quantum numbers for the 4-th generation
//  Int_t            fX;                //
//  Int_t            fStable;           // 1 if stable, 0 otherwise
//
//  TObjArray*       fDecayList;        // array of decay channels
//
//  TString          fParticleClass;    // lepton, meson etc
//
//  Int_t            fTrackingCode;     // G3 tracking code of the particle
//  TParticlePDG*    fAntiParticle;     // pointer to antiparticle

#include "TDecayChannel.h"
#include "TParticlePDG.h"
#include "TDatabasePDG.h"

ClassImp(TParticlePDG)

//______________________________________________________________________________
TParticlePDG::TParticlePDG()
{
   //default constructor
   fPdgCode      = 0;
   fMass         = 0;
   fCharge       = 0;
   fLifetime     = 0;
   fWidth        = 0;
   fParity       = 0;
   fSpin         = 0;
   fIsospin      = 0;
   fI3           = 0;
   fStrangeness  = 0;
   fCharm        = 0;
   fBeauty       = 0;
   fTop          = 0;
   fY            = 0;
   fX            = 0;
   fStable       = 0;
   fDecayList    = 0;
   fTrackingCode = 0;
   fAntiParticle = 0;
}

//______________________________________________________________________________
TParticlePDG::TParticlePDG(Int_t )
{
   // empty for the time  being

   fPdgCode      = 0;
   fMass         = 0;
   fCharge       = 0;
   fLifetime     = 0;
   fWidth        = 0;
   fParity       = 0;
   fSpin         = 0;
   fIsospin      = 0;
   fI3           = 0;
   fStrangeness  = 0;
   fCharm        = 0;
   fBeauty       = 0;
   fTop          = 0;
   fY            = 0;
   fX            = 0;
   fStable       = 0;
   fDecayList    = 0;
   fTrackingCode = 0;
   fAntiParticle = 0;
}

//______________________________________________________________________________
TParticlePDG::TParticlePDG(const char* Name, const char* Title, Double_t Mass,
                           Bool_t Stable, Double_t Width, Double_t Charge,
                           const char* ParticleClass, Int_t PdgCode, Int_t Anti,
                           Int_t TrackingCode)
  : TNamed(Name,Title)
{

   // empty for the time  being
   fLifetime      = 0;
   fParity        = 0;
   fSpin          = 0;
   fIsospin       = 0;
   fI3            = 0;
   fStrangeness   = 0;
   fCharm         = 0;
   fBeauty        = 0;
   fTop           = 0;
   fY             = 0;
   fX             = 0;
   fStable        = 0;

   fMass          = Mass;
   fStable        = Stable;
   fWidth         = Width;
   fCharge        = Charge;
   fParticleClass = ParticleClass;
   fPdgCode       = PdgCode;
   fTrackingCode  = TrackingCode;
   fDecayList     = NULL;
   if (Anti) fAntiParticle = this;
   else      fAntiParticle = 0;
}

//______________________________________________________________________________
TParticlePDG::TParticlePDG(const TParticlePDG& pdg) :
  TNamed(pdg),
  fPdgCode(pdg.fPdgCode),
  fMass(pdg.fMass),
  fCharge(pdg.fCharge),
  fLifetime(pdg.fLifetime),
  fWidth(pdg.fWidth),
  fParity(pdg.fParity),
  fSpin(pdg.fSpin),
  fIsospin(pdg.fIsospin),
  fI3(pdg.fI3),
  fStrangeness(pdg.fStrangeness),
  fCharm(pdg.fCharm),
  fBeauty(pdg.fBeauty),
  fTop(pdg.fTop),
  fY(pdg.fY),
  fX(pdg.fX),
  fStable(pdg.fStable),
  fDecayList(pdg.fDecayList),
  fParticleClass(pdg.fParticleClass),
  fTrackingCode(pdg.fTrackingCode),
  fAntiParticle(pdg.fAntiParticle)
{
   //copy constructor
}

//______________________________________________________________________________
TParticlePDG& TParticlePDG::operator=(const TParticlePDG& pdg)
{
   //assignement operator
   if(this!=&pdg) {
      TNamed::operator=(pdg);
      fPdgCode=pdg.fPdgCode;
      fMass=pdg.fMass;
      fCharge=pdg.fCharge;
      fLifetime=pdg.fLifetime;
      fWidth=pdg.fWidth;
      fParity=pdg.fParity;
      fSpin=pdg.fSpin;
      fIsospin=pdg.fIsospin;
      fI3=pdg.fI3;
      fStrangeness=pdg.fStrangeness;
      fCharm=pdg.fCharm;
      fBeauty=pdg.fBeauty;
      fTop=pdg.fTop;
      fY=pdg.fY;
      fX=pdg.fX;
      fStable=pdg.fStable;
      fDecayList=pdg.fDecayList;
      fParticleClass=pdg.fParticleClass;
      fTrackingCode=pdg.fTrackingCode;
      fAntiParticle=pdg.fAntiParticle;
   }
   return *this;
}

//______________________________________________________________________________
TParticlePDG::~TParticlePDG() {
   //destructor
   if (fDecayList) {
      fDecayList->Delete();
      delete fDecayList;
   }
}

//______________________________________________________________________________
Int_t TParticlePDG::AddDecayChannel(Int_t        Type,
                                    Double_t     BranchingRatio,
                                    Int_t        NDaughters,
                                    Int_t*       DaughterPdgCode)
{
   // add new decay channel, Particle owns those...

   Int_t n = NDecayChannels();
   if (NDecayChannels() == 0) {
      fDecayList = new TObjArray(5);
   }
   TDecayChannel* dc = new TDecayChannel(n,Type,BranchingRatio,NDaughters,
                                        DaughterPdgCode);
   fDecayList->Add(dc);
   return 0;
}

//_____________________________________________________________________________
TDecayChannel* TParticlePDG::DecayChannel(Int_t i)
{
   //return pointer to decay channel object at index i
   return (TDecayChannel*) fDecayList->At(i);
}

//_____________________________________________________________________________
void TParticlePDG::PrintDecayChannel(TDecayChannel* dc, Option_t* option) const
{
   //print the list of decays
   if (strstr(option,"banner")) {
                                // print banner

      printf(" Channel Code BranchingRatio Nd  ");
      printf(" ...................Daughters.................... \n");
   }
   if (strstr(option,"data")) {

      TDatabasePDG* db = TDatabasePDG::Instance();

      printf("%7i %5i %12.5e %5i  ",
           dc->Number(),
           dc->MatrixElementCode(),
           dc->BranchingRatio(),
           dc->NDaughters());

      for (int i=0; i<dc->NDaughters(); i++) {
         int ic = dc->DaughterPdgCode(i);
         TParticlePDG* p = db->GetParticle(ic);
         printf(" %15s(%8i)",p->GetName(),ic);
      }
      printf("\n");
   }
}

//______________________________________________________________________________
void TParticlePDG::Print(Option_t *) const
{
//
//  Print the entire information of this kind of particle
//

   printf("%-20s  %6d\t",GetName(),fPdgCode);
   if (!fStable) {
      printf("Mass:%9.4f Width (GeV):%11.4e\tCharge: %5.1f\n",
              fMass, fWidth, fCharge);
   } else {
      printf("Mass:%9.4f Width (GeV): Stable\tCharge: %5.1f\n",
              fMass, fCharge);
   }
   if (fDecayList) {
      int banner_printed = 0;
      TIter next(fDecayList);
      TDecayChannel* dc;
      while ((dc = (TDecayChannel*)next())) {
         if (! banner_printed) {
            PrintDecayChannel(dc,"banner");
            banner_printed = 1;
         }
         PrintDecayChannel(dc,"data");
      }
   }
}

<commit_msg>Doc alignment improvements<commit_after>// @(#)root/eg:$Id$
// Author: Pasha Murat   12/02/99

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//______________________________________________________________________________
//
// Description of the static properties of a particle.
// The class is typically generated by the TDatabasePDG class.
// It is referenced by the dynamic particle class TParticle.
//  Int_t            fPdgCode;          // PDG code of the particle
//  Double_t         fMass;             // particle mass in GeV
//  Double_t         fCharge;           // charge in units of |e|/3
//  Double_t         fLifetime;         // proper lifetime in nanoseconds
//  Double_t         fWidth;            // total width in GeV
//  Int_t            fParity;           // parity
//  Double_t         fSpin;             // spin
//  Double_t         fIsospin;          // isospin
//  Double_t         fI3;               // i3
//  Int_t            fStrangeness;      // flavours are defined if i3 != -1
//  Int_t            fCharm;            // 1 or -1 for C-particles,  0 for others
//  Int_t            fBeauty;
//  Int_t            fTop;
//  Int_t            fY;                // X,Y: quantum numbers for the 4-th generation
//  Int_t            fX;
//  Int_t            fStable;           // 1 if stable, 0 otherwise
//
//  TObjArray*       fDecayList;        // array of decay channels
//
//  TString          fParticleClass;    // lepton, meson etc
//
//  Int_t            fTrackingCode;     // G3 tracking code of the particle
//  TParticlePDG*    fAntiParticle;     // pointer to antiparticle

#include "TDecayChannel.h"
#include "TParticlePDG.h"
#include "TDatabasePDG.h"

ClassImp(TParticlePDG)

//______________________________________________________________________________
TParticlePDG::TParticlePDG()
{
   //default constructor
   fPdgCode      = 0;
   fMass         = 0;
   fCharge       = 0;
   fLifetime     = 0;
   fWidth        = 0;
   fParity       = 0;
   fSpin         = 0;
   fIsospin      = 0;
   fI3           = 0;
   fStrangeness  = 0;
   fCharm        = 0;
   fBeauty       = 0;
   fTop          = 0;
   fY            = 0;
   fX            = 0;
   fStable       = 0;
   fDecayList    = 0;
   fTrackingCode = 0;
   fAntiParticle = 0;
}

//______________________________________________________________________________
TParticlePDG::TParticlePDG(Int_t )
{
   // empty for the time  being

   fPdgCode      = 0;
   fMass         = 0;
   fCharge       = 0;
   fLifetime     = 0;
   fWidth        = 0;
   fParity       = 0;
   fSpin         = 0;
   fIsospin      = 0;
   fI3           = 0;
   fStrangeness  = 0;
   fCharm        = 0;
   fBeauty       = 0;
   fTop          = 0;
   fY            = 0;
   fX            = 0;
   fStable       = 0;
   fDecayList    = 0;
   fTrackingCode = 0;
   fAntiParticle = 0;
}

//______________________________________________________________________________
TParticlePDG::TParticlePDG(const char* Name, const char* Title, Double_t Mass,
                           Bool_t Stable, Double_t Width, Double_t Charge,
                           const char* ParticleClass, Int_t PdgCode, Int_t Anti,
                           Int_t TrackingCode)
  : TNamed(Name,Title)
{

   // empty for the time  being
   fLifetime      = 0;
   fParity        = 0;
   fSpin          = 0;
   fIsospin       = 0;
   fI3            = 0;
   fStrangeness   = 0;
   fCharm         = 0;
   fBeauty        = 0;
   fTop           = 0;
   fY             = 0;
   fX             = 0;
   fStable        = 0;

   fMass          = Mass;
   fStable        = Stable;
   fWidth         = Width;
   fCharge        = Charge;
   fParticleClass = ParticleClass;
   fPdgCode       = PdgCode;
   fTrackingCode  = TrackingCode;
   fDecayList     = NULL;
   if (Anti) fAntiParticle = this;
   else      fAntiParticle = 0;
}

//______________________________________________________________________________
TParticlePDG::TParticlePDG(const TParticlePDG& pdg) :
  TNamed(pdg),
  fPdgCode(pdg.fPdgCode),
  fMass(pdg.fMass),
  fCharge(pdg.fCharge),
  fLifetime(pdg.fLifetime),
  fWidth(pdg.fWidth),
  fParity(pdg.fParity),
  fSpin(pdg.fSpin),
  fIsospin(pdg.fIsospin),
  fI3(pdg.fI3),
  fStrangeness(pdg.fStrangeness),
  fCharm(pdg.fCharm),
  fBeauty(pdg.fBeauty),
  fTop(pdg.fTop),
  fY(pdg.fY),
  fX(pdg.fX),
  fStable(pdg.fStable),
  fDecayList(pdg.fDecayList),
  fParticleClass(pdg.fParticleClass),
  fTrackingCode(pdg.fTrackingCode),
  fAntiParticle(pdg.fAntiParticle)
{
   //copy constructor
}

//______________________________________________________________________________
TParticlePDG& TParticlePDG::operator=(const TParticlePDG& pdg)
{
   //assignement operator
   if(this!=&pdg) {
      TNamed::operator=(pdg);
      fPdgCode=pdg.fPdgCode;
      fMass=pdg.fMass;
      fCharge=pdg.fCharge;
      fLifetime=pdg.fLifetime;
      fWidth=pdg.fWidth;
      fParity=pdg.fParity;
      fSpin=pdg.fSpin;
      fIsospin=pdg.fIsospin;
      fI3=pdg.fI3;
      fStrangeness=pdg.fStrangeness;
      fCharm=pdg.fCharm;
      fBeauty=pdg.fBeauty;
      fTop=pdg.fTop;
      fY=pdg.fY;
      fX=pdg.fX;
      fStable=pdg.fStable;
      fDecayList=pdg.fDecayList;
      fParticleClass=pdg.fParticleClass;
      fTrackingCode=pdg.fTrackingCode;
      fAntiParticle=pdg.fAntiParticle;
   }
   return *this;
}

//______________________________________________________________________________
TParticlePDG::~TParticlePDG() {
   //destructor
   if (fDecayList) {
      fDecayList->Delete();
      delete fDecayList;
   }
}

//______________________________________________________________________________
Int_t TParticlePDG::AddDecayChannel(Int_t        Type,
                                    Double_t     BranchingRatio,
                                    Int_t        NDaughters,
                                    Int_t*       DaughterPdgCode)
{
   // add new decay channel, Particle owns those...

   Int_t n = NDecayChannels();
   if (NDecayChannels() == 0) {
      fDecayList = new TObjArray(5);
   }
   TDecayChannel* dc = new TDecayChannel(n,Type,BranchingRatio,NDaughters,
                                        DaughterPdgCode);
   fDecayList->Add(dc);
   return 0;
}

//_____________________________________________________________________________
TDecayChannel* TParticlePDG::DecayChannel(Int_t i)
{
   //return pointer to decay channel object at index i
   return (TDecayChannel*) fDecayList->At(i);
}

//_____________________________________________________________________________
void TParticlePDG::PrintDecayChannel(TDecayChannel* dc, Option_t* option) const
{
   //print the list of decays
   if (strstr(option,"banner")) {
                                // print banner

      printf(" Channel Code BranchingRatio Nd  ");
      printf(" ...................Daughters.................... \n");
   }
   if (strstr(option,"data")) {

      TDatabasePDG* db = TDatabasePDG::Instance();

      printf("%7i %5i %12.5e %5i  ",
           dc->Number(),
           dc->MatrixElementCode(),
           dc->BranchingRatio(),
           dc->NDaughters());

      for (int i=0; i<dc->NDaughters(); i++) {
         int ic = dc->DaughterPdgCode(i);
         TParticlePDG* p = db->GetParticle(ic);
         printf(" %15s(%8i)",p->GetName(),ic);
      }
      printf("\n");
   }
}

//______________________________________________________________________________
void TParticlePDG::Print(Option_t *) const
{
//
//  Print the entire information of this kind of particle
//

   printf("%-20s  %6d\t",GetName(),fPdgCode);
   if (!fStable) {
      printf("Mass:%9.4f Width (GeV):%11.4e\tCharge: %5.1f\n",
              fMass, fWidth, fCharge);
   } else {
      printf("Mass:%9.4f Width (GeV): Stable\tCharge: %5.1f\n",
              fMass, fCharge);
   }
   if (fDecayList) {
      int banner_printed = 0;
      TIter next(fDecayList);
      TDecayChannel* dc;
      while ((dc = (TDecayChannel*)next())) {
         if (! banner_printed) {
            PrintDecayChannel(dc,"banner");
            banner_printed = 1;
         }
         PrintDecayChannel(dc,"data");
      }
   }
}

<|endoftext|>


<commit_before>//
// The Magic 8-ball
//
// Created by Ryan Lederman <lederman@gmail.com> on 14 June 2017
//
// License: MIT
// Original Copyright (C) Mattel Inc. This program is not affiliated with Mattel Inc.,
// and they retain all intellecutal property rights to the Magic 8-Ball.
//

#include "eightball.h"
#include "crc32.h"

#include <iostream>
#include <sstream>
#include <cstring>
#include <memory>
#include <chrono>
#include <random>

using namespace std;
using namespace std::chrono;

namespace eightball {
    wstring RetrieveQuestion()
    {
        wstring question;
        getline(wcin, question);
        return question;
    }

    wstring ComputeMagicAnswer(const wstring& question)
    {
        wstring retval;

        if (!question.empty()) {
            static uint32_t lastCrc32 = 0U;

            size_t questionLen = question.length();
            size_t buflen = questionLen * 2 + sizeof(uint32_t) + sizeof(time_t);
            shared_ptr<uint8_t> buf(new uint8_t[buflen]);

            if (buf) {
                // Fill buffer with input question, last CRC checksum (if present), and current time.
                memmove(buf.get(), question.c_str(), questionLen * 2);
                memmove(buf.get() + (questionLen * 2), &lastCrc32, sizeof(uint32_t));

                microseconds now = duration_cast<microseconds>(steady_clock::now().time_since_epoch());
                memmove(buf.get() + (questionLen * 2) + sizeof(uint32_t), &now, sizeof(microseconds::rep));

                // Compute CRC32.
                uint32_t crc32 = crc32c(0U, buf.get(), buflen);

                // Store checksum for next pass.
                lastCrc32 = crc32;

                // Seed RNG with new checksum (uses 32-bit mersenne twister).
                shared_ptr<mt19937> rng(new mt19937(crc32));

                // Look up magic answer!
                retval = rng ? Answers[(*rng)() % (sizeof(Answers) / sizeof(Answers[0]))].text : L"ERROR!";
            }
        }

        return retval;
    }

    wstring EightBallASCII(const wstring& answer)
    {
        wstringstream strm;

        strm << L"    ,888888888." << endl;
        strm << L"  d8'         `8b" << endl;
        strm << L" 88     888      88" << endl;
        strm << L"88     8   8      88" << endl;
        strm << L"88      888       88" << "\t" << answer << endl;
        strm << L"88     8   8      88" << endl;
        strm << L" 88     888      88" << endl;
        strm << L"  Y8.          .8P" << endl;
        strm << L"    `888888888P`'" << endl;

        return strm.str();
    }

    int PrintUsage()
    {
        // TODO: If command-line arguments are added, implement this.
        return 1;
    }
}; // !namespace eightball
<commit_msg>Fix formatting.<commit_after>//
// The Magic 8-ball
//
// Created by Ryan Lederman <lederman@gmail.com> on 14 June 2017
//
// License: MIT
// Original Copyright (C) Mattel Inc. This program is not affiliated with Mattel Inc.,
// and they retain all intellecutal property rights to the Magic 8-Ball.
//

#include "eightball.h"
#include "crc32.h"

#include <iostream>
#include <sstream>
#include <cstring>
#include <memory>
#include <chrono>
#include <random>

using namespace std;
using namespace std::chrono;

namespace eightball
{
    wstring RetrieveQuestion()
    {
        wstring question;
        getline(wcin, question);
        return question;
    }

    wstring ComputeMagicAnswer(const wstring& question)
    {
        wstring retval;

        if (!question.empty()) {
            static uint32_t lastCrc32 = 0U;

            size_t questionLen = question.length();
            size_t buflen = questionLen * 2 + sizeof(uint32_t) + sizeof(time_t);
            shared_ptr<uint8_t> buf(new uint8_t[buflen]);

            if (buf) {
                // Fill buffer with input question, last CRC checksum (if present), and current time.
                memmove(buf.get(), question.c_str(), questionLen * 2);
                memmove(buf.get() + (questionLen * 2), &lastCrc32, sizeof(uint32_t));

                microseconds now = duration_cast<microseconds>(steady_clock::now().time_since_epoch());
                memmove(buf.get() + (questionLen * 2) + sizeof(uint32_t), &now, sizeof(microseconds::rep));

                // Compute CRC32.
                uint32_t crc32 = crc32c(0U, buf.get(), buflen);

                // Store checksum for next pass.
                lastCrc32 = crc32;

                // Seed RNG with new checksum (uses 32-bit mersenne twister).
                shared_ptr<mt19937> rng(new mt19937(crc32));

                // Look up magic answer!
                retval = rng ? Answers[(*rng)() % (sizeof(Answers) / sizeof(Answers[0]))].text : L"ERROR!";
            }
        }

        return retval;
    }

    wstring EightBallASCII(const wstring& answer)
    {
        wstringstream strm;

        strm << L"    ,888888888." << endl;
        strm << L"  d8'         `8b" << endl;
        strm << L" 88     888      88" << endl;
        strm << L"88     8   8      88" << endl;
        strm << L"88      888       88" << "\t" << answer << endl;
        strm << L"88     8   8      88" << endl;
        strm << L" 88     888      88" << endl;
        strm << L"  Y8.          .8P" << endl;
        strm << L"    `888888888P`'" << endl;

        return strm.str();
    }

    int PrintUsage()
    {
        // TODO: If command-line arguments are added, implement this.
        return 1;
    }
}; // !namespace eightball
<|endoftext|>


<commit_before>

#if 0
#include <iostream>
#include <set>
#include <vector>
#include <map>

#include <StateMachine.h>
using namespace std;
using namespace STATEMACHINE;

class Test1DataSource : public STATEMACHINE::DataSource
{
public:
		Test1DataSource()
		{}
		virtual ~Test1DataSource()
		{}
		void ResetInputEvents(){}
		void ResetInternalEvents(){}
		 void ResetEvents()//reset input,output,internal event list
		{}
		 void ApplyAndResetInputEvents() // Resets current events. Apply input events as current event and reset input event list
		{}
		 void ApplyAndResetInternalEvents()//Resets current events. Apply internal events as current event and reset input event list
		{}

		void ResetOutputEvents(){} // Resets output event list

		 bool IsInternalEventSet(){ return false;} // Checks if there are any internal events set
		 void GetOutputEvents(set<Event>& events){events.clear();} // Gets the list of Output Events generated

		 void performStateEntryAction(STATEID sid){}	//Execute state entry-action
		 void performStateExitAction(STATEID sid){} //Execute state exit-action
		 void performStateDuringAction(STATEID sid){}//Execute state during-action

		 void performTransitionAction(TRANSID tid){} // Execute transaction -action
		 bool evalTransitionGuard(TRANSID tid) //Evaluate transaction - guard
		{
			return true;
		}
		 bool evalTransitionEventTrigger(TRANSID tid) //Evaluate transaction - trigger
		{
			return true;
		}

};

int mainTest1()
{
	Test1DataSource* ds = new Test1DataSource();

	string smname("STest1");
	StateMachine sm(smname, ds);

	string smrname("RSTest1");
	Region smr(smrname,0,&sm);
	sm.addChildRegion(&smr);

	string s1name("s1");
	State s1(&smr, &sm, s1name, STATEMACHINE::OR,1);
	smr.addState(&s1,true);

	string s2name("s2");
	State s2(&smr, &sm, s2name, STATEMACHINE::OR,2);
	smr.addState(&s2,false);

	Transition t1(&s1,&s2,1,1);
	s1.addOutgoingTransition(&t1);

	Transition t2(&s2,&s1,2,2);
	s2.addOutgoingTransition(&t2);

	s1.SetDataSource(ds);
	s2.SetDataSource(ds);
	t1.SetDataSource(ds);
	t2.SetDataSource(ds);

	sm.computePathToRoot();
	s1.computePathToRoot();
	s2.computePathToRoot();

	t1.computeEntryAndExitPoints();
	t2.computeEntryAndExitPoints();

	sm.step();
	cout <<"------------------------------------"<<endl;
	sm.step();

	return 0;
}

namespace MACHINE1
{

	Event TICK("TICK",1);
	Event RESET("RESET",2);

	class DataSource : public STATEMACHINE::DataSource
	{
	public:
		DataSource()
		{
			m_inputEvents.clear();
			m_outputEvents.clear();
			m_internalEvents.clear();
			m_currentEvents.clear();

			counter = 0;

		}
		virtual ~DataSource()
		{
			m_inputEvents.clear();
			m_outputEvents.clear();
			m_internalEvents.clear();
			m_currentEvents.clear();

		}

		 void ResetEvents()//reset input,output,internal event list
		{
			m_inputEvents.clear();
			m_outputEvents.clear();
			m_internalEvents.clear();
			m_currentEvents.clear();

		}
		 void ApplyAndResetInputEvents() // Resets current events. Apply input events as current event and reset input event list
		{
			m_currentEvents.clear();
			std::copy(m_inputEvents.begin(), m_inputEvents.end(), std::inserter(m_currentEvents,m_currentEvents.begin()));
			m_inputEvents.clear();

		}
		 void ApplyAndResetInternalEvents()//Resets current events. Apply internal events as current event and reset input event list
		{
			m_currentEvents.clear();
			std::copy(m_internalEvents.begin(), m_internalEvents.end(), std::inserter(m_currentEvents,m_currentEvents.begin()));
			m_internalEvents.clear();

		}

		 void ResetOutputEvents() // Resets output event list
		{
			m_outputEvents.clear();

		}

		 bool IsInternalEventSet(){
			return  !m_internalEvents.empty();
		} // Checks if there are any internal events set

		 void GetOutputEvents(set<Event>& events){
			events.clear();
			std::copy(m_outputEvents.begin(), m_outputEvents.end(), std::inserter(events,events.begin()));

		} // Gets the list of Output Events generated

		 void performStateEntryAction(STATEID sid){}	//Execute state entry-action
		 void performStateExitAction(STATEID sid){} //Execute state exit-action
		 void performStateDuringAction(STATEID sid){}//Execute state during-action

		 void performTransitionAction(TRANSID tid)
		{
			switch(tid)
			{
				case 1:	return TA_T1();
				case 2: return TA_T2();
				default: return;
			}
			return;
		} // Execute transaction -action

		 bool evalTransitionGuard(TRANSID tid) //Evaluate transaction - guard
		{
			return true;

		}

		 bool evalTransitionEventTrigger(TRANSID tid) //Evaluate transaction - trigger
		{
			switch(tid)
			{
				case 1:	return ET_T1();
				case 2: return ET_T2();
				default: break;
			}
			return true;

		}

		bool ET_T1()
		{
			return (m_currentEvents.find(RESET) != m_currentEvents.end());
		}

		bool ET_T2()
		{
			return (m_currentEvents.find(TICK) != m_currentEvents.end());
		}

		void TA_T1()
		{
			counter = 0;
		}

		void TA_T2()
		{
			counter++;
		}

		void SetEvent(Event e)
		{
			m_inputEvents.insert(e);
		}

		void Send(Event e)
		{
			m_outputEvents.insert(e);
		}

		void Consume(Event e)
		{
			m_internalEvents.insert(e);
		}

		set<Event> m_inputEvents;
		set<Event> m_outputEvents;
		set<Event> m_internalEvents;
		set<Event> m_currentEvents;

		int counter;

	};
}

int mainTest2()
{
	MACHINE1::DataSource* ds = new MACHINE1::DataSource();

	string smname("Machine1");
	StateMachine sm(smname, ds);

	string smrname("RMachine1");
	Region smr(smrname,0,&sm);
	sm.addChildRegion(&smr);

	string sNominalname("Nominal");
	State sNominal(&smr, &sm, sNominalname, STATEMACHINE::OR,1);
	smr.addState(&sNominal,true);

	Transition t1(&sNominal,&sNominal,1,1);
	sNominal.addOutgoingTransition(&t1);

	Transition t2(&sNominal,&sNominal,2,2);
	sNominal.addOutgoingTransition(&t2);

	sNominal.SetDataSource(ds);
	t1.SetDataSource(ds);
	t2.SetDataSource(ds);

	sm.computePathToRoot();
	sNominal.computePathToRoot();

	t1.computeEntryAndExitPoints();
	t2.computeEntryAndExitPoints();

cout<<"-----------------------------------------"<<endl;
	ds->SetEvent(MACHINE1::TICK);
	sm.step();
	cout<<"after step1 counter "<<ds->counter<<endl;
cout<<"-----------------------------------------"<<endl;
	//ds->SetEvent(MACHINE1::TICK);
	sm.step();
	cout<<"after step 2 counter "<<ds->counter<<endl;
cout<<"-----------------------------------------"<<endl;
	ds->SetEvent(MACHINE1::TICK);
	sm.step();
	cout<<"after step 3 counter "<<ds->counter<<endl;
cout<<"-----------------------------------------"<<endl;
	ds->SetEvent(MACHINE1::TICK);
	sm.step();
	cout<<"after step 4 counter "<<ds->counter<<endl;
	cout<<"-----------------------------------------"<<endl;

	ds->SetEvent(MACHINE1::RESET);
	sm.step();
	cout<<"after step 5 counter "<<ds->counter<<endl;

	cout<<"-----------------------------------------"<<endl;
	//ds->SetEvent(MACHINE1::TICK);
	sm.step();
	cout<<"after step 6 counter "<<ds->counter<<endl;

	cout<<"-----------------------------------------"<<endl;
	ds->SetEvent(MACHINE1::TICK);
	sm.step();
	cout<<"after step 7 counter "<<ds->counter<<endl;

	cout <<"------------------------------------"<<endl;
	//sm.step();

	return 0;
}

namespace MACHINE2
{
	Event TICK("TICK",1);
	Event RESET("RESET",2);
	Event STOP("STOP",3);
	Event START("START",4);

	class DataSource : public STATEMACHINE::DataSource
	{
	public:
		DataSource()
		{
			m_inputEvents.clear();
			m_outputEvents.clear();
			m_internalEvents.clear();
			m_currentEvents.clear();

			counter = 0;

		}

		virtual ~DataSource()
		{
			m_inputEvents.clear();
			m_outputEvents.clear();
			m_internalEvents.clear();
			m_currentEvents.clear();

		}

		virtual void ResetEvents()//reset input,output,internal event list
		{
			m_inputEvents.clear();
			m_outputEvents.clear();
			m_internalEvents.clear();
			m_currentEvents.clear();

		}

		virtual void ApplyAndResetInputEvents() // Resets current events. Apply input events as current event and reset input event list
		{
			m_currentEvents.clear();
			std::copy(m_inputEvents.begin(), m_inputEvents.end(), std::inserter(m_currentEvents,m_currentEvents.begin()));
			m_inputEvents.clear();

		}

		virtual void ApplyAndResetInternalEvents()//Resets current events. Apply internal events as current event and reset input event list
		{
			m_currentEvents.clear();
			std::copy(m_internalEvents.begin(), m_internalEvents.end(), std::inserter(m_currentEvents,m_currentEvents.begin()));
			m_internalEvents.clear();

		}

		virtual void ResetOutputEvents() // Resets output event list
		{
			m_outputEvents.clear();

		}

		virtual bool IsInternalEventSet(){
			return  !m_internalEvents.empty();
		} // Checks if there are any internal events set

		virtual void GetOutputEvents(set<Event>& events){
			events.clear();
			std::copy(m_outputEvents.begin(), m_outputEvents.end(), std::inserter(events,events.begin()));

		} // Gets the list of Output Events generated

		virtual void performStateEntryAction(STATEID sid){}	//Execute state entry-action
		virtual void performStateExitAction(STATEID sid){} //Execute state exit-action
		virtual void performStateDuringAction(STATEID sid){}//Execute state during-action

		virtual void performTransitionAction(TRANSID tid)
		{
			switch(tid)
			{
				case 1:	return TA_T1();
				case 3: return TA_T3();
				case 4:	return TA_T4();
				case 6:	return TA_T6();

				default: return;
			}
			return;
		} // Execute transaction -action

		virtual bool evalTransitionGuard(TRANSID tid) //Evaluate transaction - guard
		{
			return true;

		}

		virtual bool evalTransitionEventTrigger(TRANSID tid) //Evaluate transaction - trigger
		{
			switch(tid)
			{
				case 1:	return ET_T1();
				case 2: return ET_T2();
				case 3:	return ET_T3();
				case 4: return ET_T4();
				case 5:	return ET_T5();
				case 6: return ET_T6();
				default: break;
			}
			return true;

		}

		bool ET_T1()
		{
			return (m_currentEvents.find(RESET) != m_currentEvents.end());
		}

		bool ET_T2()
		{
			return (m_currentEvents.find(STOP) != m_currentEvents.end());
		}

		bool ET_T3()
		{
			return (m_currentEvents.find(START) != m_currentEvents.end());
		}

		bool ET_T4()
		{
			return (m_currentEvents.find(TICK) != m_currentEvents.end());
		}

		bool ET_T5()
		{
			return (m_currentEvents.find(START) != m_currentEvents.end());
		}

		bool ET_T6()
		{
			return (m_currentEvents.find(TICK) != m_currentEvents.end());
		}

		void TA_T1()
		{
			counter = 0;
		}

		void TA_T3()
		{
			Produce(MACHINE2::START);
		}

		void TA_T4()
		{
			counter++;
		}

		void TA_T6()
		{
			counter++;
		}

		void SetEvent(Event e)
		{
			m_inputEvents.insert(e);
		}

		void Send(Event e)
		{
			m_outputEvents.insert(e);
		}

		void Produce(Event e)
		{
			m_internalEvents.insert(e);
		}

		set<Event> m_inputEvents;
		set<Event> m_outputEvents;
		set<Event> m_internalEvents;
		set<Event> m_currentEvents;

		int counter;

	};
}

int mainTest3()
{
	MACHINE2::DataSource* ds = new MACHINE2::DataSource();

	string smname("Machine2");
	StateMachine sm(smname, ds);

	string smrname("RMachine2");
	Region smr(smrname,0,&sm);
	sm.addChildRegion(&smr);

	string sNominalname("Nominal");
	State sNominal(&smr, &sm, sNominalname, STATEMACHINE::AND,1);
	smr.addState(&sNominal,true);

	Transition t1(&sNominal,&sNominal,1,1,true);
	sNominal.addOutgoingTransition(&t1);

	Transition t2(&sNominal,&sNominal,2,2);
	sNominal.addOutgoingTransition(&t2);

	string rNominal_Firstname("RNominal_First");
	Region rNominal_First(rNominal_Firstname,0,&sNominal);
	rNominal_First.EnableDeepHistory();
	sNominal.addChildRegion(&rNominal_First);

	string sFirstname("First");
	State sFirst(&rNominal_First, &sNominal, sFirstname, STATEMACHINE::OR,2);
	rNominal_First.addState(&sFirst,true);

	string rNominal_Secondname("RSecond");
	Region rNominal_Second(rNominal_Secondname,1,&sNominal);
	rNominal_Second.EnableDeepHistory();
	sNominal.addChildRegion(&rNominal_Second);
	string sSecondname("Second");
	State sSecond(&rNominal_Second, &sNominal, sSecondname, STATEMACHINE::OR,3);
	rNominal_Second.addState(&sSecond,true);

	string rFirstname("RFirst");
	Region rFirst(rFirstname,0,&sFirst);
	sFirst.addChildRegion(&rFirst);

	string sOffname("Off");
	State sOff(&rFirst, &sFirst, sOffname, STATEMACHINE::OR,4);
	rFirst.addState(&sOff,true);

	string sOnname("On");
	State sOn(&rFirst, &sFirst, sOnname, STATEMACHINE::OR,5);
	rFirst.addState(&sOn,false);

	Transition t3(&sOff,&sOn,1,3);
	sOff.addOutgoingTransition(&t3);

	Transition t4(&sOn,&sOn,1,4);
	sOn.addOutgoingTransition(&t4);

	string rSecondname("RSecond");
	Region rSecond(rSecondname,0,&sSecond);
	sSecond.addChildRegion(&rSecond);

	State sOff1(&rSecond, &sSecond, sOffname, STATEMACHINE::OR,6);
	rSecond.addState(&sOff1,true);

	State sOn1(&rSecond, &sSecond, sOnname, STATEMACHINE::OR,7);
	rSecond.addState(&sOn1,false);

	Transition t5(&sOff1,&sOn1,1,5);
	sOff1.addOutgoingTransition(&t5);

	Transition t6(&sOn,&sOn,1,6);
	sOn1.addOutgoingTransition(&t6);

	sm.SetDataSource(ds);
	sNominal.SetDataSource(ds);
	t1.SetDataSource(ds);
	t2.SetDataSource(ds);

	sFirst.SetDataSource(ds);
	sOff.SetDataSource(ds);
	sOn.SetDataSource(ds);
	t3.SetDataSource(ds);
	t4.SetDataSource(ds);

	sSecond.SetDataSource(ds);
	sOff1.SetDataSource(ds);
	sOn1.SetDataSource(ds);
	t5.SetDataSource(ds);
	t6.SetDataSource(ds);

	sm.computePathToRoot();
	sNominal.computePathToRoot();
	sFirst.computePathToRoot();
	sSecond.computePathToRoot();
	sOn.computePathToRoot();
	sOff.computePathToRoot();
	sOn1.computePathToRoot();
	sOff1.computePathToRoot();

	t1.computeEntryAndExitPoints();
	t2.computeEntryAndExitPoints();
	t3.computeEntryAndExitPoints();
	t4.computeEntryAndExitPoints();
	t5.computeEntryAndExitPoints();
	t6.computeEntryAndExitPoints();

	cout<<"-----------------------------------------"<<endl;
	ds->SetEvent(MACHINE2::TICK);
	sm.step();
	cout<<"after step1 counter "<<ds->counter<<endl;
	cout<<"-----------------------------------------"<<endl;

	ds->SetEvent(MACHINE2::START);
	sm.step();
	cout<<"after step 2 counter "<<ds->counter<<endl;
	cout<<"-----------------------------------------"<<endl;

	ds->SetEvent(MACHINE2::TICK);
	sm.step();
	cout<<"after step 3 counter "<<ds->counter<<endl;
	cout<<"-----------------------------------------"<<endl;

	ds->SetEvent(MACHINE2::TICK);
	sm.step();
	cout<<"after step 4 counter "<<ds->counter<<endl;
	cout<<"-----------------------------------------"<<endl;

	ds->SetEvent(MACHINE2::RESET);
	sm.step();
	cout<<"after step 5 counter "<<ds->counter<<endl;
	cout<<"-----------------------------------------"<<endl;

	ds->SetEvent(MACHINE2::TICK);
	sm.step();
	cout<<"after step 6 counter "<<ds->counter<<endl;
	cout <<"------------------------------------"<<endl;

	ds->SetEvent(MACHINE2::TICK);
	sm.step();
	cout<<"after step 7 counter "<<ds->counter<<endl;

	cout <<"------------------------------------"<<endl;
	ds->SetEvent(MACHINE2::STOP);
	sm.step();
	cout<<"after step 8 counter "<<ds->counter<<endl;

	cout <<"------------------------------------"<<endl;
	ds->SetEvent(MACHINE2::TICK);
	sm.step();
	cout<<"after step 9 counter "<<ds->counter<<endl;

	return 0;
}

#endif

#include "SMTest.h"
using namespace std;
using namespace STATEMACHINE;

using namespace SMTest_Behavior;

int mainTest()
{
	Repo* r = Repo::Instance();

	if (r)
	{
		cout<<"init step"<<endl;
		r->SM()->step();

		r->DS()->setCurrentTime();
		r->DS()->setVariable_FC(1);
		cout<<"step 2"<<endl;
		r->SM()->step();

	}

	Repo::Terminate();

	return 0;

}

int main()
{
	//return mainTest1();
	//return mainTest2();
	return mainTest();
}<commit_msg>Update Test1.cpp<commit_after>
#include "SMTest.h"
using namespace std;
using namespace STATEMACHINE;

using namespace SMTest_Behavior;

int mainTest()
{
	Repo* r = Repo::Instance();

	if (r)
	{
		cout<<"init step"<<endl;
		r->SM()->step();

		r->DS()->setCurrentTime();
		r->DS()->setVariable_FC(1);
		cout<<"step 2"<<endl;
		r->SM()->step();

	}

	Repo::Terminate();

	return 0;

}

int main()
{
	//return mainTest1();
	//return mainTest2();
	return mainTest();
}
<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "rendertab.h"

// appleseed.studio headers.
#include "mainwindow/rendering/renderwidget.h"

// appleseed.renderer headers.
#include "renderer/api/frame.h"
#include "renderer/api/project.h"

// appleseed.foundation headers.
#include "foundation/image/canvasproperties.h"
#include "foundation/image/color.h"
#include "foundation/image/image.h"

// Qt headers.
#include <QComboBox>
#include <QGridLayout>
#include <QIcon>
#include <QLabel>
#include <QLayout>
#include <QScrollArea>
#include <QSize>
#include <QString>
#include <Qt>
#include <QToolBar>
#include <QToolButton>

using namespace foundation;
using namespace renderer;

namespace appleseed {
namespace studio {

//
// RenderTab class implementation.
//

RenderTab::RenderTab(
    ProjectExplorer&    project_explorer,
    Project&            project)
  : m_project_explorer(project_explorer)
  , m_project(project)
{
    create_render_widget();
    create_toolbar();
    create_scrollarea();

    setObjectName(QString::fromUtf8("render_widget_tab"));
    setLayout(new QGridLayout());
    layout()->setSpacing(0);
    layout()->setMargin(0);
    layout()->addWidget(m_toolbar);
    layout()->addWidget(m_scroll_area);

    recreate_handlers();
}

void RenderTab::clear()
{
    m_render_widget->clear(Color4f(0.0f));
    m_render_widget->repaint();
}

void RenderTab::darken()
{
    m_render_widget->multiply(0.2f);
}

void RenderTab::reset_zoom()
{
    m_zoom_handler->reset_zoom();
}

void RenderTab::update()
{
    m_render_widget->update();
}

void RenderTab::update_size()
{
    m_set_render_region_button->setChecked(false);

    const CanvasProperties& props = m_project.get_frame()->image().properties();

    m_render_widget->resize(
        props.m_canvas_width,
        props.m_canvas_height);

    recreate_handlers();
}

RenderWidget* RenderTab::get_render_widget() const
{
    return m_render_widget;
}

RenderTab::State RenderTab::save_state() const
{
    State state;
    state.m_zoom_handler_state = m_zoom_handler->save_state();
    state.m_pan_handler_state = m_pan_handler->save_state();
    return state;
}

void RenderTab::load_state(const State& state)
{
    // The order matters here.
    m_zoom_handler->load_state(state.m_zoom_handler_state);
    m_pan_handler->load_state(state.m_pan_handler_state);
}

void RenderTab::slot_render_widget_context_menu(const QPoint& point)
{
    emit signal_render_widget_context_menu(m_render_widget->mapToGlobal(point));
}

void RenderTab::slot_toggle_render_region(const bool checked)
{
    m_picking_handler->set_enabled(!checked);
    m_render_region_handler->set_enabled(checked);
}

void RenderTab::slot_set_render_region(const QRect& rect)
{
    m_set_render_region_button->setChecked(false);
    emit signal_set_render_region(rect);
}

void RenderTab::create_render_widget()
{
    const CanvasProperties& props = m_project.get_frame()->image().properties();

    m_render_widget =
        new RenderWidget(
            props.m_canvas_width,
            props.m_canvas_height);

    m_render_widget->setContextMenuPolicy(Qt::CustomContextMenu);

    connect(
        m_render_widget, SIGNAL(customContextMenuRequested(const QPoint&)),
        SLOT(slot_render_widget_context_menu(const QPoint&)));

    m_render_widget->setMouseTracking(true);
}

void RenderTab::create_toolbar()
{
    // Create the render toolbar.
    m_toolbar = new QToolBar();
    m_toolbar->setObjectName(QString::fromUtf8("render_toolbar"));
    m_toolbar->setIconSize(QSize(18, 18));

    // Create the Save Image button in the render toolbar.
    m_save_aovs_button = new QToolButton();
    m_save_aovs_button->setIcon(QIcon(":/icons/save_image.png"));
    m_save_aovs_button->setToolTip("Save All AOVs...");
    connect(
        m_save_aovs_button, SIGNAL(clicked()),
        SIGNAL(signal_save_all_aovs()));
    m_toolbar->addWidget(m_save_aovs_button);

    // Create the Quick Save Image button in the render toolbar.
    m_quick_save_aovs_button = new QToolButton();
    m_quick_save_aovs_button->setIcon(QIcon(":/icons/quick_save_aovs.png"));
    m_quick_save_aovs_button->setToolTip("Quicksave All AOVs");
    connect(
        m_quick_save_aovs_button, SIGNAL(clicked()),
        SIGNAL(signal_quicksave_all_aovs()));
    m_toolbar->addWidget(m_quick_save_aovs_button);

    m_toolbar->addSeparator();

    // Create the Set Render Region button in the render toolbar.
    m_set_render_region_button = new QToolButton();
    m_set_render_region_button->setIcon(QIcon(":/icons/selection-blue.png"));
    m_set_render_region_button->setToolTip("Set Render Region");
    m_set_render_region_button->setShortcut(Qt::Key_R);
    m_set_render_region_button->setCheckable(true);
    connect(
        m_set_render_region_button, SIGNAL(toggled(bool)),
        SLOT(slot_toggle_render_region(const bool)));
    m_toolbar->addWidget(m_set_render_region_button);

    // Create the Clear Render Region button in the render toolbar.
    m_clear_render_region_button = new QToolButton();
    m_clear_render_region_button->setIcon(QIcon(":/icons/selection-crossed.png"));
    m_clear_render_region_button->setToolTip("Clear Render Region");
    m_clear_render_region_button->setShortcut(Qt::Key_C);
    connect(
        m_clear_render_region_button, SIGNAL(clicked()),
        SIGNAL(signal_clear_render_region()));
    m_toolbar->addWidget(m_clear_render_region_button);

    // Create the Clear Frame button in the render toolbar.
    m_clear_frame_button = new QToolButton();
    m_clear_frame_button->setIcon(QIcon(":/icons/picture_empty.png"));
    m_clear_frame_button->setToolTip("Clear Frame");
    m_clear_frame_button->setShortcut(Qt::Key_X);
    connect(
        m_clear_frame_button, SIGNAL(clicked()),
        SIGNAL(signal_clear_frame()));
    m_toolbar->addWidget(m_clear_frame_button);

    m_toolbar->addSeparator();

    // Create the Reset Zoom button in the render toolbar.
    m_reset_zoom_button = new QToolButton();
    m_reset_zoom_button->setIcon(QIcon(":/icons/reset_zoom.png"));
    m_reset_zoom_button->setToolTip("Reset Zoom");
    m_reset_zoom_button->setShortcut(Qt::Key_Asterisk);
    connect(
        m_reset_zoom_button, SIGNAL(clicked()),
        SIGNAL(signal_reset_zoom()));
    m_toolbar->addWidget(m_reset_zoom_button);

    m_toolbar->addSeparator();

    // Create the label preceding the picking mode combobox.
    QLabel* picking_mode_label = new QLabel("Picking Mode:");
    picking_mode_label->setObjectName(QString::fromUtf8("picking_mode_label"));
    m_toolbar->addWidget(picking_mode_label);

    // Create the picking mode combobox.
    // The combo will be populated by the ScenePickingHandler instantiated below.
    m_picking_mode_combo = new QComboBox();
    m_picking_mode_combo->setObjectName(QString::fromUtf8("picking_mode_combo"));
    m_toolbar->addWidget(m_picking_mode_combo);

    m_toolbar->addSeparator();

    // Create a label to display various information such as mouse coordinates, etc.
    m_info_label = new QLabel();
    m_info_label->setScaledContents(true);
    m_info_label->setObjectName(QString::fromUtf8("info_label"));
    m_toolbar->addWidget(m_info_label);

    m_toolbar->addSeparator();

    // Create a labels to display RGBA values.
    m_r_label = new QLabel();
    m_r_label->setScaledContents(true);
    m_r_label->setObjectName(QString::fromUtf8("r_label"));
    m_toolbar->addWidget(m_r_label);

    m_g_label = new QLabel();
    m_g_label->setScaledContents(true);
    m_g_label->setObjectName(QString::fromUtf8("g_label"));
    m_toolbar->addWidget(m_g_label);

    m_b_label = new QLabel();
    m_b_label->setScaledContents(true);
    m_b_label->setObjectName(QString::fromUtf8("b_label"));
    m_toolbar->addWidget(m_b_label);

    m_a_label = new QLabel();
    m_a_label->setScaledContents(true);
    m_a_label->setObjectName(QString::fromUtf8("a_label"));
    m_toolbar->addWidget(m_a_label);
}

void RenderTab::create_scrollarea()
{
    // Encapsulate the render widget into another widget that adds a margin around it.
    QWidget* render_widget_wrapper = new QWidget();
    render_widget_wrapper->setObjectName(QString::fromUtf8("render_widget_wrapper"));
    render_widget_wrapper->setLayout(new QGridLayout());
    render_widget_wrapper->layout()->setSizeConstraint(QLayout::SetFixedSize);
    render_widget_wrapper->layout()->setContentsMargins(20, 20, 20, 20);
    render_widget_wrapper->layout()->addWidget(m_render_widget);

    // Wrap the render widget in a scroll area.
    m_scroll_area = new QScrollArea();
    m_scroll_area->setObjectName(QString::fromUtf8("render_widget_scrollarea"));
    m_scroll_area->setAlignment(Qt::AlignCenter);
    m_scroll_area->setWidget(render_widget_wrapper);
}

void RenderTab::recreate_handlers()
{
    // Handler to handle zooming the render widget in and out with the keyboard or the mouse wheel.
    m_zoom_handler.reset(
        new WidgetZoomHandler(
            m_scroll_area,
            m_render_widget));

    // Handler for camera panning with the mouse.
    m_pan_handler.reset(
        new ScrollAreaPanHandler(
            m_scroll_area));

    // Handler for camera tracking with the mouse.
    m_mouse_tracker.reset(
        new MouseCoordinatesTracker(
            m_render_widget,
            m_info_label,
            m_r_label,
            m_g_label,
            m_b_label,
            m_a_label));

    // Handler for picking scene entities in the render widget.
    m_picking_handler.reset(
        new ScenePickingHandler(
            m_render_widget,
            m_picking_mode_combo,
            *m_mouse_tracker.get(),
            m_project_explorer,
            m_project));

    // Handler for defining render regions with the mouse.
    m_render_region_handler.reset(
        new RenderRegionHandler(
            m_render_widget,
            *m_mouse_tracker.get()));
    connect(
        m_render_region_handler.get(), SIGNAL(signal_render_region(const QRect&)),
        SLOT(slot_set_render_region(const QRect&)));

    // Clipboard handler.
    m_clipboard_handler.reset(new RenderClipboardHandler(m_render_widget));

    // Initially, the picking handler is active and the render region is inactive.
    m_picking_handler->set_enabled(true);
    m_render_region_handler->set_enabled(false);
}

void RenderTab::set_clear_frame_button_enabled(const bool enabled)
{
    m_clear_frame_button->setEnabled(enabled);
}

}   // namespace studio
}   // namespace appleseed

#include "mainwindow/rendering/moc_cpp_rendertab.cxx"
<commit_msg>fixed typo.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "rendertab.h"

// appleseed.studio headers.
#include "mainwindow/rendering/renderwidget.h"

// appleseed.renderer headers.
#include "renderer/api/frame.h"
#include "renderer/api/project.h"

// appleseed.foundation headers.
#include "foundation/image/canvasproperties.h"
#include "foundation/image/color.h"
#include "foundation/image/image.h"

// Qt headers.
#include <QComboBox>
#include <QGridLayout>
#include <QIcon>
#include <QLabel>
#include <QLayout>
#include <QScrollArea>
#include <QSize>
#include <QString>
#include <Qt>
#include <QToolBar>
#include <QToolButton>

using namespace foundation;
using namespace renderer;

namespace appleseed {
namespace studio {

//
// RenderTab class implementation.
//

RenderTab::RenderTab(
    ProjectExplorer&    project_explorer,
    Project&            project)
  : m_project_explorer(project_explorer)
  , m_project(project)
{
    create_render_widget();
    create_toolbar();
    create_scrollarea();

    setObjectName(QString::fromUtf8("render_widget_tab"));
    setLayout(new QGridLayout());
    layout()->setSpacing(0);
    layout()->setMargin(0);
    layout()->addWidget(m_toolbar);
    layout()->addWidget(m_scroll_area);

    recreate_handlers();
}

void RenderTab::clear()
{
    m_render_widget->clear(Color4f(0.0f));
    m_render_widget->repaint();
}

void RenderTab::darken()
{
    m_render_widget->multiply(0.2f);
}

void RenderTab::reset_zoom()
{
    m_zoom_handler->reset_zoom();
}

void RenderTab::update()
{
    m_render_widget->update();
}

void RenderTab::update_size()
{
    m_set_render_region_button->setChecked(false);

    const CanvasProperties& props = m_project.get_frame()->image().properties();

    m_render_widget->resize(
        props.m_canvas_width,
        props.m_canvas_height);

    recreate_handlers();
}

RenderWidget* RenderTab::get_render_widget() const
{
    return m_render_widget;
}

RenderTab::State RenderTab::save_state() const
{
    State state;
    state.m_zoom_handler_state = m_zoom_handler->save_state();
    state.m_pan_handler_state = m_pan_handler->save_state();
    return state;
}

void RenderTab::load_state(const State& state)
{
    // The order matters here.
    m_zoom_handler->load_state(state.m_zoom_handler_state);
    m_pan_handler->load_state(state.m_pan_handler_state);
}

void RenderTab::slot_render_widget_context_menu(const QPoint& point)
{
    emit signal_render_widget_context_menu(m_render_widget->mapToGlobal(point));
}

void RenderTab::slot_toggle_render_region(const bool checked)
{
    m_picking_handler->set_enabled(!checked);
    m_render_region_handler->set_enabled(checked);
}

void RenderTab::slot_set_render_region(const QRect& rect)
{
    m_set_render_region_button->setChecked(false);
    emit signal_set_render_region(rect);
}

void RenderTab::create_render_widget()
{
    const CanvasProperties& props = m_project.get_frame()->image().properties();

    m_render_widget =
        new RenderWidget(
            props.m_canvas_width,
            props.m_canvas_height);

    m_render_widget->setContextMenuPolicy(Qt::CustomContextMenu);

    connect(
        m_render_widget, SIGNAL(customContextMenuRequested(const QPoint&)),
        SLOT(slot_render_widget_context_menu(const QPoint&)));

    m_render_widget->setMouseTracking(true);
}

void RenderTab::create_toolbar()
{
    // Create the render toolbar.
    m_toolbar = new QToolBar();
    m_toolbar->setObjectName(QString::fromUtf8("render_toolbar"));
    m_toolbar->setIconSize(QSize(18, 18));

    // Create the Save Image button in the render toolbar.
    m_save_aovs_button = new QToolButton();
    m_save_aovs_button->setIcon(QIcon(":/icons/save_image.png"));
    m_save_aovs_button->setToolTip("Save All AOVs...");
    connect(
        m_save_aovs_button, SIGNAL(clicked()),
        SIGNAL(signal_save_all_aovs()));
    m_toolbar->addWidget(m_save_aovs_button);

    // Create the Quick Save Image button in the render toolbar.
    m_quick_save_aovs_button = new QToolButton();
    m_quick_save_aovs_button->setIcon(QIcon(":/icons/quick_save_aovs.png"));
    m_quick_save_aovs_button->setToolTip("Quicksave All AOVs");
    connect(
        m_quick_save_aovs_button, SIGNAL(clicked()),
        SIGNAL(signal_quicksave_all_aovs()));
    m_toolbar->addWidget(m_quick_save_aovs_button);

    m_toolbar->addSeparator();

    // Create the Set Render Region button in the render toolbar.
    m_set_render_region_button = new QToolButton();
    m_set_render_region_button->setIcon(QIcon(":/icons/selection-blue.png"));
    m_set_render_region_button->setToolTip("Set Render Region");
    m_set_render_region_button->setShortcut(Qt::Key_R);
    m_set_render_region_button->setCheckable(true);
    connect(
        m_set_render_region_button, SIGNAL(toggled(bool)),
        SLOT(slot_toggle_render_region(const bool)));
    m_toolbar->addWidget(m_set_render_region_button);

    // Create the Clear Render Region button in the render toolbar.
    m_clear_render_region_button = new QToolButton();
    m_clear_render_region_button->setIcon(QIcon(":/icons/selection-crossed.png"));
    m_clear_render_region_button->setToolTip("Clear Render Region");
    m_clear_render_region_button->setShortcut(Qt::Key_C);
    connect(
        m_clear_render_region_button, SIGNAL(clicked()),
        SIGNAL(signal_clear_render_region()));
    m_toolbar->addWidget(m_clear_render_region_button);

    // Create the Clear Frame button in the render toolbar.
    m_clear_frame_button = new QToolButton();
    m_clear_frame_button->setIcon(QIcon(":/icons/picture_empty.png"));
    m_clear_frame_button->setToolTip("Clear Frame");
    m_clear_frame_button->setShortcut(Qt::Key_X);
    connect(
        m_clear_frame_button, SIGNAL(clicked()),
        SIGNAL(signal_clear_frame()));
    m_toolbar->addWidget(m_clear_frame_button);

    m_toolbar->addSeparator();

    // Create the Reset Zoom button in the render toolbar.
    m_reset_zoom_button = new QToolButton();
    m_reset_zoom_button->setIcon(QIcon(":/icons/reset_zoom.png"));
    m_reset_zoom_button->setToolTip("Reset Zoom");
    m_reset_zoom_button->setShortcut(Qt::Key_Asterisk);
    connect(
        m_reset_zoom_button, SIGNAL(clicked()),
        SIGNAL(signal_reset_zoom()));
    m_toolbar->addWidget(m_reset_zoom_button);

    m_toolbar->addSeparator();

    // Create the label preceding the picking mode combobox.
    QLabel* picking_mode_label = new QLabel("Picking Mode:");
    picking_mode_label->setObjectName(QString::fromUtf8("picking_mode_label"));
    m_toolbar->addWidget(picking_mode_label);

    // Create the picking mode combobox.
    // The combo will be populated by the ScenePickingHandler instantiated below.
    m_picking_mode_combo = new QComboBox();
    m_picking_mode_combo->setObjectName(QString::fromUtf8("picking_mode_combo"));
    m_toolbar->addWidget(m_picking_mode_combo);

    m_toolbar->addSeparator();

    // Create a label to display various information such as mouse coordinates, etc.
    m_info_label = new QLabel();
    m_info_label->setScaledContents(true);
    m_info_label->setObjectName(QString::fromUtf8("info_label"));
    m_toolbar->addWidget(m_info_label);

    m_toolbar->addSeparator();

    // Create labels to display RGBA values.

    m_r_label = new QLabel();
    m_r_label->setScaledContents(true);
    m_r_label->setObjectName(QString::fromUtf8("r_label"));
    m_toolbar->addWidget(m_r_label);

    m_g_label = new QLabel();
    m_g_label->setScaledContents(true);
    m_g_label->setObjectName(QString::fromUtf8("g_label"));
    m_toolbar->addWidget(m_g_label);

    m_b_label = new QLabel();
    m_b_label->setScaledContents(true);
    m_b_label->setObjectName(QString::fromUtf8("b_label"));
    m_toolbar->addWidget(m_b_label);

    m_a_label = new QLabel();
    m_a_label->setScaledContents(true);
    m_a_label->setObjectName(QString::fromUtf8("a_label"));
    m_toolbar->addWidget(m_a_label);
}

void RenderTab::create_scrollarea()
{
    // Encapsulate the render widget into another widget that adds a margin around it.
    QWidget* render_widget_wrapper = new QWidget();
    render_widget_wrapper->setObjectName(QString::fromUtf8("render_widget_wrapper"));
    render_widget_wrapper->setLayout(new QGridLayout());
    render_widget_wrapper->layout()->setSizeConstraint(QLayout::SetFixedSize);
    render_widget_wrapper->layout()->setContentsMargins(20, 20, 20, 20);
    render_widget_wrapper->layout()->addWidget(m_render_widget);

    // Wrap the render widget in a scroll area.
    m_scroll_area = new QScrollArea();
    m_scroll_area->setObjectName(QString::fromUtf8("render_widget_scrollarea"));
    m_scroll_area->setAlignment(Qt::AlignCenter);
    m_scroll_area->setWidget(render_widget_wrapper);
}

void RenderTab::recreate_handlers()
{
    // Handler to handle zooming the render widget in and out with the keyboard or the mouse wheel.
    m_zoom_handler.reset(
        new WidgetZoomHandler(
            m_scroll_area,
            m_render_widget));

    // Handler for camera panning with the mouse.
    m_pan_handler.reset(
        new ScrollAreaPanHandler(
            m_scroll_area));

    // Handler for camera tracking with the mouse.
    m_mouse_tracker.reset(
        new MouseCoordinatesTracker(
            m_render_widget,
            m_info_label,
            m_r_label,
            m_g_label,
            m_b_label,
            m_a_label));

    // Handler for picking scene entities in the render widget.
    m_picking_handler.reset(
        new ScenePickingHandler(
            m_render_widget,
            m_picking_mode_combo,
            *m_mouse_tracker.get(),
            m_project_explorer,
            m_project));

    // Handler for defining render regions with the mouse.
    m_render_region_handler.reset(
        new RenderRegionHandler(
            m_render_widget,
            *m_mouse_tracker.get()));
    connect(
        m_render_region_handler.get(), SIGNAL(signal_render_region(const QRect&)),
        SLOT(slot_set_render_region(const QRect&)));

    // Clipboard handler.
    m_clipboard_handler.reset(new RenderClipboardHandler(m_render_widget));

    // Initially, the picking handler is active and the render region is inactive.
    m_picking_handler->set_enabled(true);
    m_render_region_handler->set_enabled(false);
}

void RenderTab::set_clear_frame_button_enabled(const bool enabled)
{
    m_clear_frame_button->setEnabled(enabled);
}

}   // namespace studio
}   // namespace appleseed

#include "mainwindow/rendering/moc_cpp_rendertab.cxx"
<|endoftext|>


<commit_before>#ifndef CLUSTERING_ADMINISTRATION_MACHINE_ID_TO_PEER_ID_HPP_
#define CLUSTERING_ADMINISTRATION_MACHINE_ID_TO_PEER_ID_HPP_

#include "clustering/administration/machine_metadata.hpp"
#include "rpc/directory/read_view.hpp"

inline peer_id_t machine_id_to_peer_id(const machine_id_t &input, const clone_ptr_t<directory_rview_t<machine_id_t> > &translation_table) {
    std::set<peer_id_t> peers_list = translation_table->get_directory_service()->get_connectivity_service()->get_peers_list();
    for (std::set<peer_id_t>::iterator it = peers_list.begin(); it != peers_list.end(); it++) {
        machine_id_t machine_id = translation_table->get_value(*it).get();
        if (machine_id == input) {
            return *it;
        }
    }
    return peer_id_t();
}

inline peer_id_t machine_id_to_peer_id(const machine_id_t &input, const std::map<peer_id_t, machine_id_t> &translation_table) {
    for (std::map<peer_id_t, machine_id_t>::const_iterator it = translation_table.begin(); it != translation_table.end(); it++) {
        if (it->second == input) {
            return it->first;
        }
    }
    return peer_id_t();
}

#endif /* CLUSTERING_ADMINISTRATION_MACHINE_ID_TO_PEER_ID_HPP_ */
<commit_msg>Remove unused version of machine_id_to_peer_id().<commit_after>#ifndef CLUSTERING_ADMINISTRATION_MACHINE_ID_TO_PEER_ID_HPP_
#define CLUSTERING_ADMINISTRATION_MACHINE_ID_TO_PEER_ID_HPP_

#include "clustering/administration/machine_metadata.hpp"
#include "rpc/directory/read_view.hpp"

inline peer_id_t machine_id_to_peer_id(const machine_id_t &input, const std::map<peer_id_t, machine_id_t> &translation_table) {
    for (std::map<peer_id_t, machine_id_t>::const_iterator it = translation_table.begin(); it != translation_table.end(); it++) {
        if (it->second == input) {
            return it->first;
        }
    }
    return peer_id_t();
}

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


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

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

#include "unotools/accessiblerelationsethelper.hxx"
#include <rtl/uuid.h>
#include <vector>
#include <comphelper/sequence.hxx>

using namespace ::utl;
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::accessibility;

class AccessibleRelationSetHelperImpl
{
public:
    AccessibleRelationSetHelperImpl();
    AccessibleRelationSetHelperImpl(const AccessibleRelationSetHelperImpl& rImpl);
    ~AccessibleRelationSetHelperImpl();

    sal_Int32 getRelationCount(  )
        throw (uno::RuntimeException);
    AccessibleRelation getRelation( sal_Int32 nIndex )
            throw (lang::IndexOutOfBoundsException,
                    uno::RuntimeException);
    sal_Bool containsRelation( sal_Int16 aRelationType )
        throw (uno::RuntimeException);
    AccessibleRelation getRelationByType( sal_Int16 aRelationType )
            throw (uno::RuntimeException);
    void AddRelation(const AccessibleRelation& rRelation)
            throw (uno::RuntimeException);

private:
    std::vector<AccessibleRelation> maRelations;
};

AccessibleRelationSetHelperImpl::AccessibleRelationSetHelperImpl()
{
}

AccessibleRelationSetHelperImpl::AccessibleRelationSetHelperImpl(const AccessibleRelationSetHelperImpl& rImpl)
    : maRelations(rImpl.maRelations)
{
}

AccessibleRelationSetHelperImpl::~AccessibleRelationSetHelperImpl()
{
}

sal_Int32 AccessibleRelationSetHelperImpl::getRelationCount(  )
    throw (uno::RuntimeException)
{
    return maRelations.size();
}

AccessibleRelation AccessibleRelationSetHelperImpl::getRelation( sal_Int32 nIndex )
    throw (lang::IndexOutOfBoundsException,
            uno::RuntimeException)
{
    if ((nIndex < 0) || (static_cast<sal_uInt32>(nIndex) >= maRelations.size()))
        throw lang::IndexOutOfBoundsException();
    return maRelations[nIndex];
}

sal_Bool AccessibleRelationSetHelperImpl::containsRelation( sal_Int16 aRelationType )
    throw (uno::RuntimeException)
{
    sal_Int32 nCount(getRelationCount());
    sal_Int32 i(0);
    sal_Bool bFound(sal_False);
    while ((i < nCount) && !bFound)
    {
        if (maRelations[i].RelationType == aRelationType)
            bFound = sal_True;
        else
            i++;
    }
    return bFound;
}

AccessibleRelation AccessibleRelationSetHelperImpl::getRelationByType( sal_Int16 aRelationType )
    throw (uno::RuntimeException)
{
    sal_Int32 nCount(getRelationCount());
    sal_Int32 i(0);
    sal_Bool bFound(sal_False);
    while ((i < nCount) && !bFound)
    {
        if (maRelations[i].RelationType == aRelationType)
            bFound = sal_True;
        else
            i++;
    }
    return maRelations[i];
}

void AccessibleRelationSetHelperImpl::AddRelation(const AccessibleRelation& rRelation)
    throw (uno::RuntimeException)
{
    sal_Int32 nCount(getRelationCount());
    sal_Int32 i(0);
    sal_Bool bFound(sal_False);
    while ((i < nCount) && !bFound)
    {
        if (maRelations[i].RelationType == rRelation.RelationType)
            bFound = sal_True;
        else
            i++;
    }
    if (bFound)
        maRelations[i].TargetSet = comphelper::concatSequences(maRelations[i].TargetSet, rRelation.TargetSet);
    else
        maRelations.push_back(rRelation);
}

//=====  internal  ============================================================

AccessibleRelationSetHelper::AccessibleRelationSetHelper ()
    : mpHelperImpl(NULL)
{
    mpHelperImpl = new AccessibleRelationSetHelperImpl();
}

AccessibleRelationSetHelper::AccessibleRelationSetHelper (const AccessibleRelationSetHelper& rHelper)
    : cppu::WeakImplHelper1<XAccessibleRelationSet>()
    , mpHelperImpl(NULL)
{
    if (rHelper.mpHelperImpl)
        mpHelperImpl = new AccessibleRelationSetHelperImpl(*rHelper.mpHelperImpl);
    else
        mpHelperImpl = new AccessibleRelationSetHelperImpl();
}

AccessibleRelationSetHelper::~AccessibleRelationSetHelper(void)
{
    delete mpHelperImpl;
}

//=====  XAccessibleRelationSet  ==============================================

    /** Returns the number of relations in this relation set.

        @return
            Returns the number of relations or zero if there are none.
    */
sal_Int32 SAL_CALL
    AccessibleRelationSetHelper::getRelationCount(  )
        throw (uno::RuntimeException)
{
    ::vos::OGuard aGuard (maMutex);
    return mpHelperImpl->getRelationCount();
}

    /** Returns the relation of this relation set that is specified by
        the given index.

        @param nIndex
            This index specifies the relatio to return.

        @return
            For a valid index, i.e. inside the range 0 to the number of
            relations minus one, the returned value is the requested
            relation.  If the index is invalid then the returned relation
            has the type INVALID.

    */
 AccessibleRelation SAL_CALL
        AccessibleRelationSetHelper::getRelation( sal_Int32 nIndex )
            throw (lang::IndexOutOfBoundsException,
                    uno::RuntimeException)
{
    ::vos::OGuard aGuard (maMutex);
    return mpHelperImpl->getRelation(nIndex);
}

    /** Tests whether the relation set contains a relation matching the
        specified key.

        @param aRelationType
            The type of relation to look for in this set of relations.  This
            has to be one of the constants of
            <type>AccessibleRelationType</type>.

        @return
            Returns <TRUE/> if there is a (at least one) relation of the
            given type and <FALSE/> if there is no such relation in the set.
    */
sal_Bool SAL_CALL
    AccessibleRelationSetHelper::containsRelation( sal_Int16 aRelationType )
        throw (uno::RuntimeException)
{
    ::vos::OGuard aGuard (maMutex);
    return mpHelperImpl->containsRelation(aRelationType);
}

    /** Retrieve and return the relation with the given relation type.

        @param aRelationType
            The type of the relation to return.  This has to be one of the
            constants of <type>AccessibleRelationType</type>.

        @return
            If a relation with the given type could be found than (a copy
            of) this relation is returned.  Otherwise a relation with the
            type INVALID is returned.
    */
AccessibleRelation SAL_CALL
        AccessibleRelationSetHelper::getRelationByType( sal_Int16 aRelationType )
            throw (uno::RuntimeException)
{
    ::vos::OGuard aGuard (maMutex);
    return mpHelperImpl->getRelationByType(aRelationType);
}

void AccessibleRelationSetHelper::AddRelation(const AccessibleRelation& rRelation)
            throw (uno::RuntimeException)
{
    ::vos::OGuard aGuard (maMutex);
    mpHelperImpl->AddRelation(rRelation);
}

//=====  XTypeProvider  =======================================================

uno::Sequence< ::com::sun::star::uno::Type>
    AccessibleRelationSetHelper::getTypes (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    ::vos::OGuard aGuard (maMutex);
    const ::com::sun::star::uno::Type aTypeList[] = {
        ::getCppuType((const uno::Reference<
            XAccessibleRelationSet>*)0),
        ::getCppuType((const uno::Reference<
            lang::XTypeProvider>*)0)
        };
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type>
        aTypeSequence (aTypeList, 2);
    return aTypeSequence;
}

uno::Sequence<sal_Int8> SAL_CALL
    AccessibleRelationSetHelper::getImplementationId (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    ::vos::OGuard aGuard (maMutex);
    static uno::Sequence<sal_Int8> aId;
    if (aId.getLength() == 0)
    {
        aId.realloc (16);
        rtl_createUuid ((sal_uInt8 *)aId.getArray(), 0, sal_True);
    }
    return aId;
}
<commit_msg>INTEGRATION: CWS aqua11y01 (1.8.76); FILE MERGED 2008/02/27 09:21:43 fne 1.8.76.2: #i82877# small fix 2008/02/26 10:47:55 fne 1.8.76.1: #i82877# fixed problem with getRelationByType<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: accessiblerelationsethelper.cxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include "unotools/accessiblerelationsethelper.hxx"
#include <rtl/uuid.h>
#include <vector>
#include <comphelper/sequence.hxx>

using namespace ::utl;
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::accessibility;

class AccessibleRelationSetHelperImpl
{
public:
    AccessibleRelationSetHelperImpl();
    AccessibleRelationSetHelperImpl(const AccessibleRelationSetHelperImpl& rImpl);
    ~AccessibleRelationSetHelperImpl();

    sal_Int32 getRelationCount(  )
        throw (uno::RuntimeException);
    AccessibleRelation getRelation( sal_Int32 nIndex )
            throw (lang::IndexOutOfBoundsException,
                    uno::RuntimeException);
    sal_Bool containsRelation( sal_Int16 aRelationType )
        throw (uno::RuntimeException);
    AccessibleRelation getRelationByType( sal_Int16 aRelationType )
            throw (uno::RuntimeException);
    void AddRelation(const AccessibleRelation& rRelation)
            throw (uno::RuntimeException);

private:
    std::vector<AccessibleRelation> maRelations;
};

AccessibleRelationSetHelperImpl::AccessibleRelationSetHelperImpl()
{
}

AccessibleRelationSetHelperImpl::AccessibleRelationSetHelperImpl(const AccessibleRelationSetHelperImpl& rImpl)
    : maRelations(rImpl.maRelations)
{
}

AccessibleRelationSetHelperImpl::~AccessibleRelationSetHelperImpl()
{
}

sal_Int32 AccessibleRelationSetHelperImpl::getRelationCount(  )
    throw (uno::RuntimeException)
{
    return maRelations.size();
}

AccessibleRelation AccessibleRelationSetHelperImpl::getRelation( sal_Int32 nIndex )
    throw (lang::IndexOutOfBoundsException,
            uno::RuntimeException)
{
    if ((nIndex < 0) || (static_cast<sal_uInt32>(nIndex) >= maRelations.size()))
        throw lang::IndexOutOfBoundsException();
    return maRelations[nIndex];
}

sal_Bool AccessibleRelationSetHelperImpl::containsRelation( sal_Int16 aRelationType )
    throw (uno::RuntimeException)
{
    AccessibleRelation defaultRelation; // default is INVALID
    AccessibleRelation relationByType = getRelationByType(aRelationType);
    return relationByType.RelationType != defaultRelation.RelationType;
}

AccessibleRelation AccessibleRelationSetHelperImpl::getRelationByType( sal_Int16 aRelationType )
    throw (uno::RuntimeException)
{
    sal_Int32 nCount(getRelationCount());
    sal_Int32 i(0);
    sal_Bool bFound(sal_False);
    while ((i < nCount) && !bFound)
    {
        if (maRelations[i].RelationType == aRelationType)
            return maRelations[i];
        else
            i++;
    }
    return AccessibleRelation();
}

void AccessibleRelationSetHelperImpl::AddRelation(const AccessibleRelation& rRelation)
    throw (uno::RuntimeException)
{
    sal_Int32 nCount(getRelationCount());
    sal_Int32 i(0);
    sal_Bool bFound(sal_False);
    while ((i < nCount) && !bFound)
    {
        if (maRelations[i].RelationType == rRelation.RelationType)
            bFound = sal_True;
        else
            i++;
    }
    if (bFound)
        maRelations[i].TargetSet = comphelper::concatSequences(maRelations[i].TargetSet, rRelation.TargetSet);
    else
        maRelations.push_back(rRelation);
}

//=====  internal  ============================================================

AccessibleRelationSetHelper::AccessibleRelationSetHelper ()
    : mpHelperImpl(NULL)
{
    mpHelperImpl = new AccessibleRelationSetHelperImpl();
}

AccessibleRelationSetHelper::AccessibleRelationSetHelper (const AccessibleRelationSetHelper& rHelper)
    : cppu::WeakImplHelper1<XAccessibleRelationSet>()
    , mpHelperImpl(NULL)
{
    if (rHelper.mpHelperImpl)
        mpHelperImpl = new AccessibleRelationSetHelperImpl(*rHelper.mpHelperImpl);
    else
        mpHelperImpl = new AccessibleRelationSetHelperImpl();
}

AccessibleRelationSetHelper::~AccessibleRelationSetHelper(void)
{
    delete mpHelperImpl;
}

//=====  XAccessibleRelationSet  ==============================================

    /** Returns the number of relations in this relation set.

        @return
            Returns the number of relations or zero if there are none.
    */
sal_Int32 SAL_CALL
    AccessibleRelationSetHelper::getRelationCount(  )
        throw (uno::RuntimeException)
{
    ::vos::OGuard aGuard (maMutex);
    return mpHelperImpl->getRelationCount();
}

    /** Returns the relation of this relation set that is specified by
        the given index.

        @param nIndex
            This index specifies the relatio to return.

        @return
            For a valid index, i.e. inside the range 0 to the number of
            relations minus one, the returned value is the requested
            relation.  If the index is invalid then the returned relation
            has the type INVALID.

    */
 AccessibleRelation SAL_CALL
        AccessibleRelationSetHelper::getRelation( sal_Int32 nIndex )
            throw (lang::IndexOutOfBoundsException,
                    uno::RuntimeException)
{
    ::vos::OGuard aGuard (maMutex);
    return mpHelperImpl->getRelation(nIndex);
}

    /** Tests whether the relation set contains a relation matching the
        specified key.

        @param aRelationType
            The type of relation to look for in this set of relations.  This
            has to be one of the constants of
            <type>AccessibleRelationType</type>.

        @return
            Returns <TRUE/> if there is a (at least one) relation of the
            given type and <FALSE/> if there is no such relation in the set.
    */
sal_Bool SAL_CALL
    AccessibleRelationSetHelper::containsRelation( sal_Int16 aRelationType )
        throw (uno::RuntimeException)
{
    ::vos::OGuard aGuard (maMutex);
    return mpHelperImpl->containsRelation(aRelationType);
}

    /** Retrieve and return the relation with the given relation type.

        @param aRelationType
            The type of the relation to return.  This has to be one of the
            constants of <type>AccessibleRelationType</type>.

        @return
            If a relation with the given type could be found than (a copy
            of) this relation is returned.  Otherwise a relation with the
            type INVALID is returned.
    */
AccessibleRelation SAL_CALL
        AccessibleRelationSetHelper::getRelationByType( sal_Int16 aRelationType )
            throw (uno::RuntimeException)
{
    ::vos::OGuard aGuard (maMutex);
    return mpHelperImpl->getRelationByType(aRelationType);
}

void AccessibleRelationSetHelper::AddRelation(const AccessibleRelation& rRelation)
            throw (uno::RuntimeException)
{
    ::vos::OGuard aGuard (maMutex);
    mpHelperImpl->AddRelation(rRelation);
}

//=====  XTypeProvider  =======================================================

uno::Sequence< ::com::sun::star::uno::Type>
    AccessibleRelationSetHelper::getTypes (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    ::vos::OGuard aGuard (maMutex);
    const ::com::sun::star::uno::Type aTypeList[] = {
        ::getCppuType((const uno::Reference<
            XAccessibleRelationSet>*)0),
        ::getCppuType((const uno::Reference<
            lang::XTypeProvider>*)0)
        };
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type>
        aTypeSequence (aTypeList, 2);
    return aTypeSequence;
}

uno::Sequence<sal_Int8> SAL_CALL
    AccessibleRelationSetHelper::getImplementationId (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    ::vos::OGuard aGuard (maMutex);
    static uno::Sequence<sal_Int8> aId;
    if (aId.getLength() == 0)
    {
        aId.realloc (16);
        rtl_createUuid ((sal_uInt8 *)aId.getArray(), 0, sal_True);
    }
    return aId;
}
<|endoftext|>