<commit_before>#ifndef INF_DEF_VISITOR
#define INF_DEF_VISITOR

#include <boost/python.hpp>
#include <sstream>
#include <string>
#include <boost/python/def_visitor.hpp>

#include <opengm/python/opengmpython.hxx>
#include <opengm/python/converter.hxx>
#include <opengm/python/numpyview.hxx>
#include <opengm/python/pythonfunction.hxx>

#include "gil.hxx"
#include "visitor_def_visitor.hxx"

#include <opengm/inference/inference.hxx>
#include <opengm/opengm.hxx>
#include <opengm/python/opengmpython.hxx>
#include <opengm/python/converter.hxx>
#include <opengm/python/numpyview.hxx>
#include <opengm/python/pythonfunction.hxx>

///////////////////////////////////
// RESET?????
///////////////////////////////////
template<class INF,bool HAS_RESET>
class InfResetSuite ;

template<class INF>
class InfResetSuite<INF,true> : public boost::python::def_visitor<InfResetSuite<INF,true> >{
public:
    friend class boost::python::def_visitor_access;
    template <class classT>
    void visit(classT& c) const{
        c.def("reset", &reset) ;
    }

    static void reset(INF & inf){
        inf.reset();
    }
};

template<class INF>
class InfResetSuite<INF,false> : public boost::python::def_visitor<InfResetSuite<INF,false> >{
public:
    friend class def_visitor_access;
    template <class classT>
    void visit(classT& c) const{
    }
};

template<class OP,class ACC>
inline std::string semiRingName(){
   std::string opString,accString;
   if(opengm::meta::Compare<OP,opengm::Adder>::value){
      opString="Adder_";
   }
   else if(opengm::meta::Compare<OP,opengm::Multiplier>::value){
      opString="Multiplier_";
   }
   if(opengm::meta::Compare<ACC,opengm::Minimizer>::value){
      opString="Minimizer";
   }
   else if(opengm::meta::Compare<ACC,opengm::Maximizer>::value){
      opString="Maximizer";
   }
   return opString+accString;
}

typedef std::vector<std::string> StringVector;

class InfSetup{
public:
    InfSetup()
    :
        cite(),
        guarantees(),
        limitations("None, this algorithm can be used for any graphical model"),
        notes(),
        algType(),
        dependencies("None, this inference algorithms is implemented in OpenGM by default."),
        hyperParameterKeyWords(),
        hyperParameters(),
        hyperParametersDoc(),
        isDefault(true),
        isParameterFree(false),
        hasInterchangeableParameter(true)
    {

    }
    std::string cite,guarantees,limitations,notes,algType,dependencies,examples;
    StringVector hyperParameterKeyWords,hyperParameters,hyperParametersDoc;
    bool isDefault,isParameterFree,hasInterchangeableParameter;
};

template<
    class INF,
    bool HAS_RESET=true,
    bool HAS_VERBOSE_VISITOR=true,
    bool HAS_PYTHON_VISITOR=true
>
class InfSuite : public  boost::python::def_visitor<InfSuite<INF,HAS_RESET,HAS_VERBOSE_VISITOR,HAS_PYTHON_VISITOR> >
{
public:
    friend class boost::python::def_visitor_access;

    typedef typename INF::GraphicalModelType                    GraphicalModelType;
    typedef typename GraphicalModelType::IndependentFactorType  IndependentFactorType;
    typedef typename INF::Parameter                             ParameterType;
    typedef typename GraphicalModelType::IndexType              IndexType;
    typedef typename GraphicalModelType::LabelType              LabelType;
    typedef typename GraphicalModelType::ValueType              ValueType;
    InfSuite(
        const std::string & algName,                                               // "Icm , Gibbs, LazyFlipper,GraphCut, AlphaBetaSwap"
        const InfSetup & infSetup
    )
    :   algName_(algName),
        infSetup_(infSetup){
    }
    const std::string algName_;
    const InfSetup infSetup_;
    const std::string extraName_;

    template <class classT>
    void visit(classT& c) const{
        std::string className = std::string("_")+algName_;
        for(size_t hp=0;hp<infSetup_.hyperParameters.size();++hp){
            className+=std::string("_");
            className+=infSetup_.hyperParameters[hp];
        }
        const std::string verboseVisitorClassName =std::string("_")+className +std::string("VerboseVisitor");
        const std::string pythonVisitorClassName  =std::string("_")+className + std::string("PythonVisitor");
        c
            // BASIC INTEFACE
            .def( boost::python::init<const GraphicalModelType & ,const ParameterType & >(
                (
                    boost::python::arg("gm"),
                    boost::python::arg("parameter")
                )
            ))
            .def("_arg",&infArg,(
                boost::python::arg("out"),
                boost::python::arg("argNumber")=1)
            )
            .def("_setStartingPoint",&setStartingPoint,(boost::python::arg("labels")))
            .def("_infer_no_visitor", &infer,
                (
                    boost::python::arg("releaseGil")=true
                )
            )
            .def("bound",&bound)
            .def("value",&value)
            .def("graphicalModel",&graphicalModel,boost::python::return_internal_reference<>())
            // OPTIONAL INTERFACE
            // has reset??
            .def(InfResetSuite<INF,HAS_RESET>())
            // visitors
            .def(InfVerboseVisitorSuite<INF,HAS_VERBOSE_VISITOR>(verboseVisitorClassName))
            .def(InfPythonVisitorSuite <INF,HAS_PYTHON_VISITOR>(pythonVisitorClassName) )

            // STRING
            .def("_algName",     &stringFromArg,(boost::python::arg("_dont_use_me_")=algName_ )).staticmethod("_algName")
            // DOCSTRING RELATED
            .def("_cite",        &stringFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.cite         )).staticmethod("_cite")
            .def("_guarantees",  &stringFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.guarantees   )).staticmethod("_guarantees")
            .def("_limitations", &stringFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.limitations  )).staticmethod("_limitations")
            .def("_notes",       &stringFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.notes        )).staticmethod("_notes")
            .def("_algType",     &stringFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.algType      )).staticmethod("_algType")
            .def("_dependencies",&stringFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.dependencies )).staticmethod("_dependencies")
            .def("_examples",    &stringFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.examples     )).staticmethod("_examples")
            // BOOL
            .def("_isParameterFree",            &boolFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.isParameterFree             )).staticmethod("_isParameterFree")
            .def("_isDefault",                  &boolFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.isDefault                   )).staticmethod("_isDefault")
            .def("_hasInterchangeableParameter",&boolFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.hasInterchangeableParameter )).staticmethod("_hasInterchangeableParameter")

            // stringvector
            .def("_hyperParameterKeywords", &stringVectorFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.hyperParameterKeyWords )).staticmethod("_hyperParameterKeywords")
            .def("_hyperParameters",        &stringVectorFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.hyperParameters        )).staticmethod("_hyperParameters")
            .def("_hyperParametersDoc",     &stringVectorFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.hyperParametersDoc     )).staticmethod("_hyperParametersDoc")

            // PARAMETER
            .def("_parameter",&getParameter).staticmethod("_parameter")
        ;

    }

    static const typename INF::GraphicalModelType & graphicalModel(const INF & inf){
        return inf.graphicalModel();
    }

    static ValueType bound(const INF & inf){
        return inf.bound();
    }

    static ValueType value(const INF & inf){
        return inf.value();
    }

    static std::string stringFromArg(const std::string & arg){
        return arg;
    }

    static StringVector stringVectorFromArg(const StringVector & arg){
        return arg;
    }

    static bool boolFromArg(const bool arg){
        return arg;
    }

    static ParameterType getParameter(){
        return ParameterType();
    }

    static opengm::InferenceTermination infer(INF & inf,const bool releaseGil){
        opengm::InferenceTermination result;
        if(releaseGil){
            releaseGIL rgil;
            result= inf.infer();
        }
        else{
            result= inf.infer();
        }
        return result;
    }

    static opengm::InferenceTermination infArg(const INF & inf,std::vector<LabelType> & arg,const size_t argnr){
        if(arg.size()<inf.graphicalModel().numberOfVariables()){
            arg.resize(inf.graphicalModel().numberOfVariables());
        }
        return inf.arg(arg,argnr);
    }

    static void setStartingPoint(INF & inf,const std::vector<LabelType> & start){
        inf.setStartingPoint(start.begin());
    }
};

#endif // INF_DEF_VISITOR <commit_msg>Use correct namespace in inf_def_visitor.hxx<commit_after>#ifndef INF_DEF_VISITOR
#define INF_DEF_VISITOR

#include <boost/python.hpp>
#include <sstream>
#include <string>
#include <boost/python/def_visitor.hpp>

#include <opengm/python/opengmpython.hxx>
#include <opengm/python/converter.hxx>
#include <opengm/python/numpyview.hxx>
#include <opengm/python/pythonfunction.hxx>

#include "gil.hxx"
#include "visitor_def_visitor.hxx"

#include <opengm/inference/inference.hxx>
#include <opengm/opengm.hxx>
#include <opengm/python/opengmpython.hxx>
#include <opengm/python/converter.hxx>
#include <opengm/python/numpyview.hxx>
#include <opengm/python/pythonfunction.hxx>

///////////////////////////////////
// RESET?????
///////////////////////////////////
template<class INF,bool HAS_RESET>
class InfResetSuite ;

template<class INF>
class InfResetSuite<INF,true> : public boost::python::def_visitor<InfResetSuite<INF,true> >{
public:
    friend class boost::python::def_visitor_access;
    template <class classT>
    void visit(classT& c) const{
        c.def("reset", &reset) ;
    }

    static void reset(INF & inf){
        inf.reset();
    }
};

template<class INF>
class InfResetSuite<INF,false> : public boost::python::def_visitor<InfResetSuite<INF,false> >{
public:
    friend class boost::python::def_visitor_access;
    template <class classT>
    void visit(classT& c) const{
    }
};

template<class OP,class ACC>
inline std::string semiRingName(){
   std::string opString,accString;
   if(opengm::meta::Compare<OP,opengm::Adder>::value){
      opString="Adder_";
   }
   else if(opengm::meta::Compare<OP,opengm::Multiplier>::value){
      opString="Multiplier_";
   }
   if(opengm::meta::Compare<ACC,opengm::Minimizer>::value){
      opString="Minimizer";
   }
   else if(opengm::meta::Compare<ACC,opengm::Maximizer>::value){
      opString="Maximizer";
   }
   return opString+accString;
}

typedef std::vector<std::string> StringVector;

class InfSetup{
public:
    InfSetup()
    :
        cite(),
        guarantees(),
        limitations("None, this algorithm can be used for any graphical model"),
        notes(),
        algType(),
        dependencies("None, this inference algorithms is implemented in OpenGM by default."),
        hyperParameterKeyWords(),
        hyperParameters(),
        hyperParametersDoc(),
        isDefault(true),
        isParameterFree(false),
        hasInterchangeableParameter(true)
    {

    }
    std::string cite,guarantees,limitations,notes,algType,dependencies,examples;
    StringVector hyperParameterKeyWords,hyperParameters,hyperParametersDoc;
    bool isDefault,isParameterFree,hasInterchangeableParameter;
};

template<
    class INF,
    bool HAS_RESET=true,
    bool HAS_VERBOSE_VISITOR=true,
    bool HAS_PYTHON_VISITOR=true
>
class InfSuite : public  boost::python::def_visitor<InfSuite<INF,HAS_RESET,HAS_VERBOSE_VISITOR,HAS_PYTHON_VISITOR> >
{
public:
    friend class boost::python::def_visitor_access;

    typedef typename INF::GraphicalModelType                    GraphicalModelType;
    typedef typename GraphicalModelType::IndependentFactorType  IndependentFactorType;
    typedef typename INF::Parameter                             ParameterType;
    typedef typename GraphicalModelType::IndexType              IndexType;
    typedef typename GraphicalModelType::LabelType              LabelType;
    typedef typename GraphicalModelType::ValueType              ValueType;
    InfSuite(
        const std::string & algName,                                               // "Icm , Gibbs, LazyFlipper,GraphCut, AlphaBetaSwap"
        const InfSetup & infSetup
    )
    :   algName_(algName),
        infSetup_(infSetup){
    }
    const std::string algName_;
    const InfSetup infSetup_;
    const std::string extraName_;

    template <class classT>
    void visit(classT& c) const{
        std::string className = std::string("_")+algName_;
        for(size_t hp=0;hp<infSetup_.hyperParameters.size();++hp){
            className+=std::string("_");
            className+=infSetup_.hyperParameters[hp];
        }
        const std::string verboseVisitorClassName =std::string("_")+className +std::string("VerboseVisitor");
        const std::string pythonVisitorClassName  =std::string("_")+className + std::string("PythonVisitor");
        c
            // BASIC INTEFACE
            .def( boost::python::init<const GraphicalModelType & ,const ParameterType & >(
                (
                    boost::python::arg("gm"),
                    boost::python::arg("parameter")
                )
            ))
            .def("_arg",&infArg,(
                boost::python::arg("out"),
                boost::python::arg("argNumber")=1)
            )
            .def("_setStartingPoint",&setStartingPoint,(boost::python::arg("labels")))
            .def("_infer_no_visitor", &infer,
                (
                    boost::python::arg("releaseGil")=true
                )
            )
            .def("bound",&bound)
            .def("value",&value)
            .def("graphicalModel",&graphicalModel,boost::python::return_internal_reference<>())
            // OPTIONAL INTERFACE
            // has reset??
            .def(InfResetSuite<INF,HAS_RESET>())
            // visitors
            .def(InfVerboseVisitorSuite<INF,HAS_VERBOSE_VISITOR>(verboseVisitorClassName))
            .def(InfPythonVisitorSuite <INF,HAS_PYTHON_VISITOR>(pythonVisitorClassName) )

            // STRING
            .def("_algName",     &stringFromArg,(boost::python::arg("_dont_use_me_")=algName_ )).staticmethod("_algName")
            // DOCSTRING RELATED
            .def("_cite",        &stringFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.cite         )).staticmethod("_cite")
            .def("_guarantees",  &stringFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.guarantees   )).staticmethod("_guarantees")
            .def("_limitations", &stringFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.limitations  )).staticmethod("_limitations")
            .def("_notes",       &stringFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.notes        )).staticmethod("_notes")
            .def("_algType",     &stringFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.algType      )).staticmethod("_algType")
            .def("_dependencies",&stringFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.dependencies )).staticmethod("_dependencies")
            .def("_examples",    &stringFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.examples     )).staticmethod("_examples")
            // BOOL
            .def("_isParameterFree",            &boolFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.isParameterFree             )).staticmethod("_isParameterFree")
            .def("_isDefault",                  &boolFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.isDefault                   )).staticmethod("_isDefault")
            .def("_hasInterchangeableParameter",&boolFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.hasInterchangeableParameter )).staticmethod("_hasInterchangeableParameter")

            // stringvector
            .def("_hyperParameterKeywords", &stringVectorFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.hyperParameterKeyWords )).staticmethod("_hyperParameterKeywords")
            .def("_hyperParameters",        &stringVectorFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.hyperParameters        )).staticmethod("_hyperParameters")
            .def("_hyperParametersDoc",     &stringVectorFromArg,(boost::python::arg("_dont_use_me_")=infSetup_.hyperParametersDoc     )).staticmethod("_hyperParametersDoc")

            // PARAMETER
            .def("_parameter",&getParameter).staticmethod("_parameter")
        ;

    }

    static const typename INF::GraphicalModelType & graphicalModel(const INF & inf){
        return inf.graphicalModel();
    }

    static ValueType bound(const INF & inf){
        return inf.bound();
    }

    static ValueType value(const INF & inf){
        return inf.value();
    }

    static std::string stringFromArg(const std::string & arg){
        return arg;
    }

    static StringVector stringVectorFromArg(const StringVector & arg){
        return arg;
    }

    static bool boolFromArg(const bool arg){
        return arg;
    }

    static ParameterType getParameter(){
        return ParameterType();
    }

    static opengm::InferenceTermination infer(INF & inf,const bool releaseGil){
        opengm::InferenceTermination result;
        if(releaseGil){
            releaseGIL rgil;
            result= inf.infer();
        }
        else{
            result= inf.infer();
        }
        return result;
    }

    static opengm::InferenceTermination infArg(const INF & inf,std::vector<LabelType> & arg,const size_t argnr){
        if(arg.size()<inf.graphicalModel().numberOfVariables()){
            arg.resize(inf.graphicalModel().numberOfVariables());
        }
        return inf.arg(arg,argnr);
    }

    static void setStartingPoint(INF & inf,const std::vector<LabelType> & start){
        inf.setStartingPoint(start.begin());
    }
};

#endif // INF_DEF_VISITOR
<|endoftext|>


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

#ifndef _CANVAS_ELAPSEDTIME_HXX
#define _CANVAS_ELAPSEDTIME_HXX

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#include "boost/shared_ptr.hpp"

namespace canvas
{
    namespace tools
    {
        /** Calculate elapsed time.

            This class provides several time-measurement and
            -management functions. In its simplest use-case, it
            measures the time from its creation.
         */
        class ElapsedTime
        {
        public:
            /** Create a new ElapsedTime object

                The moment of construction starts the time
                measurement. That means, a subsequent getElapsedTime()
                call will return the time difference between object
                creation and getElapsedTime() call.
             */
            ElapsedTime();

            /** Creates a new ElapsedTime object based on another
                timer.

                The moment of construction starts the time
                measurement. That means, a subsequent getElapsedTime()
                call will return the time difference between object
                creation and getElapsedTime() call. All time values
                are not taken from the system's time base, but from
                the provided timer.
             */
            ElapsedTime( ::boost::shared_ptr<ElapsedTime> const & pTimeBase );

            /** Gets this timer's base timer.
             */
            ::boost::shared_ptr<ElapsedTime> const & getTimeBase() const;

            /** Reset the time

                The instance of the reset() call starts the time
                measurement from scratch. That means, a subsequent
                getElapsedTime() call will return the time difference
                between reset() and getElapsedTime() call.
             */
            void reset();

            /** Query the elapsed time

                This method returns the elapsed time in seconds
                between either the construction of this object, or the
                last reset() call, if any (but see the time modulation
                methods below, for means to modify the otherwise
                continuous flow of time).

                @return the elapsed time in seconds.
             */
            double getElapsedTime() const;

            /** Pauses the running timer.

                This method stops the time, as returned by this
                object, until continueTimer() is called. During this
                period, getElapsedTime() will always return the same
                time value (i.e. the instant when pauseTimer() was
                called).
             */
            void pauseTimer();

            /** Continues the paused timer.

                This method re-enables the time flow, that is, time
                starts running again for clients calling
                getElapsedTime(). The (subtle) difference to the
                holdTimer/releaseTimer() methods below is, that there
                is no perceived time 'jump' between the pauseTimer()
                call and the continueTimer() call, i.e. the time
                starts over with the same value it has stopped on
                pauseTimer().
             */
            void continueTimer();

            /** Adjusts the timer, hold and pause times.

                This method modifies the time as returned by this
                object by the specified amount. This affects the time
                as returned by getElapsedTime(), regardless of the
                mode (e.g. paused, or on hold).

                @param fOffset
                This value will be added to the current time, i.e. the
                next call to getElapsedTime() (when performed
                immediately) will be adjusted by fOffset.

                @param bLimitToLastQueriedTime
                Limits the given offset to the time that has been
                taken via getElapsedTime()
            */
            void adjustTimer( double fOffset,
                              bool bLimitToLastQueriedTime = true );

            /** Holds the current time.

                This call makes the timer hold the current time
                (e.g. getElapsedTime() will return the time when
                holdTimer() was called), while the underlying time is
                running on. When releaseTimer() is called, the time
                will 'jump' to the then-current, underlying time. This
                is equivalent to pressing the "interim time" button on
                a stop watch, which shows this stopped time, while the
                clock keeps running internally.
            */
            void holdTimer();

            /** Releases a held timer.

                After this call, the timer again returns the running
                time on getElapsedTime().
             */
            void releaseTimer();

        private:
            static double getSystemTime();
            double getCurrentTime() const;
            double getElapsedTimeImpl() const; // does not set m_fLastQueriedTime

            const ::boost::shared_ptr<ElapsedTime>  m_pTimeBase;

            /// To validate adjustTimer() calls with bLimitToLastQueriedTime=true
            mutable double                          m_fLastQueriedTime;

            /// Start time, from which the difference to the time base is returned
            double                                  m_fStartTime;

            /// Instant, when last pause or hold started, relative to m_fStartTime
            double                                  m_fFrozenTime;

            /// True, when in pause mode
            bool                                    m_bInPauseMode;

            /// True, when in hold mode
            bool                                    m_bInHoldMode;
        };

    }
}

#endif /* _CANVAS_ELAPSEDTIME_HXX */
<commit_msg>INTEGRATION: CWS presfixes09 (1.5.38); FILE MERGED 2006/03/15 13:43:02 thb 1.5.38.1: #i49357# Cleaned up include guards; added method to convert to system window coordinates (to account for VCL's pseudo windows)<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: elapsedtime.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-13 14:34:54 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef INCLUDED_CANVAS_ELAPSEDTIME_HXX
#define INCLUDED_CANVAS_ELAPSEDTIME_HXX

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#include "boost/shared_ptr.hpp"

namespace canvas
{
    namespace tools
    {
        /** Calculate elapsed time.

            This class provides several time-measurement and
            -management functions. In its simplest use-case, it
            measures the time from its creation.
         */
        class ElapsedTime
        {
        public:
            /** Create a new ElapsedTime object

                The moment of construction starts the time
                measurement. That means, a subsequent getElapsedTime()
                call will return the time difference between object
                creation and getElapsedTime() call.
             */
            ElapsedTime();

            /** Creates a new ElapsedTime object based on another
                timer.

                The moment of construction starts the time
                measurement. That means, a subsequent getElapsedTime()
                call will return the time difference between object
                creation and getElapsedTime() call. All time values
                are not taken from the system's time base, but from
                the provided timer.
             */
            ElapsedTime( ::boost::shared_ptr<ElapsedTime> const & pTimeBase );

            /** Gets this timer's base timer.
             */
            ::boost::shared_ptr<ElapsedTime> const & getTimeBase() const;

            /** Reset the time

                The instance of the reset() call starts the time
                measurement from scratch. That means, a subsequent
                getElapsedTime() call will return the time difference
                between reset() and getElapsedTime() call.
             */
            void reset();

            /** Query the elapsed time

                This method returns the elapsed time in seconds
                between either the construction of this object, or the
                last reset() call, if any (but see the time modulation
                methods below, for means to modify the otherwise
                continuous flow of time).

                @return the elapsed time in seconds.
             */
            double getElapsedTime() const;

            /** Pauses the running timer.

                This method stops the time, as returned by this
                object, until continueTimer() is called. During this
                period, getElapsedTime() will always return the same
                time value (i.e. the instant when pauseTimer() was
                called).
             */
            void pauseTimer();

            /** Continues the paused timer.

                This method re-enables the time flow, that is, time
                starts running again for clients calling
                getElapsedTime(). The (subtle) difference to the
                holdTimer/releaseTimer() methods below is, that there
                is no perceived time 'jump' between the pauseTimer()
                call and the continueTimer() call, i.e. the time
                starts over with the same value it has stopped on
                pauseTimer().
             */
            void continueTimer();

            /** Adjusts the timer, hold and pause times.

                This method modifies the time as returned by this
                object by the specified amount. This affects the time
                as returned by getElapsedTime(), regardless of the
                mode (e.g. paused, or on hold).

                @param fOffset
                This value will be added to the current time, i.e. the
                next call to getElapsedTime() (when performed
                immediately) will be adjusted by fOffset.

                @param bLimitToLastQueriedTime
                Limits the given offset to the time that has been
                taken via getElapsedTime()
            */
            void adjustTimer( double fOffset,
                              bool bLimitToLastQueriedTime = true );

            /** Holds the current time.

                This call makes the timer hold the current time
                (e.g. getElapsedTime() will return the time when
                holdTimer() was called), while the underlying time is
                running on. When releaseTimer() is called, the time
                will 'jump' to the then-current, underlying time. This
                is equivalent to pressing the "interim time" button on
                a stop watch, which shows this stopped time, while the
                clock keeps running internally.
            */
            void holdTimer();

            /** Releases a held timer.

                After this call, the timer again returns the running
                time on getElapsedTime().
             */
            void releaseTimer();

        private:
            static double getSystemTime();
            double getCurrentTime() const;
            double getElapsedTimeImpl() const; // does not set m_fLastQueriedTime

            const ::boost::shared_ptr<ElapsedTime>  m_pTimeBase;

            /// To validate adjustTimer() calls with bLimitToLastQueriedTime=true
            mutable double                          m_fLastQueriedTime;

            /// Start time, from which the difference to the time base is returned
            double                                  m_fStartTime;

            /// Instant, when last pause or hold started, relative to m_fStartTime
            double                                  m_fFrozenTime;

            /// True, when in pause mode
            bool                                    m_bInPauseMode;

            /// True, when in hold mode
            bool                                    m_bInHoldMode;
        };

    }
}

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


<commit_before>/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#pragma once

#include "core/reactor.hh"
#include "core/iostream.hh"
#include "core/distributed.hh"
#include "core/print.hh"
#include "core/sstring.hh"
#include "net/api.hh"
#include "util/serialization.hh"
#include "gms/inet_address.hh"
#include "rpc/rpc.hh"
#include <unordered_map>
#include "db/config.hh"
#include "frozen_mutation.hh"
#include "db/serializer.hh"

namespace net {

/* All verb handler identifiers */
enum class messaging_verb : int32_t {
    MUTATION,
    MUTATION_DONE,
    BINARY, // Deprecated
    READ_REPAIR,
    READ,
    READ_DATA,
    READ_DIGEST,
    REQUEST_RESPONSE, // client-initiated reads and writes
    STREAM_INITIATE, // Deprecated
    STREAM_INITIATE_DONE, // Deprecated
    STREAM_REPLY, // Deprecated
    STREAM_REQUEST, // Deprecated
    RANGE_SLICE,
    BOOTSTRAP_TOKEN, // Deprecated
    TREE_REQUEST, // Deprecated
    TREE_RESPONSE, // Deprecated
    JOIN, // Deprecated
    GOSSIP_DIGEST_SYN,
    GOSSIP_DIGEST_ACK,
    GOSSIP_DIGEST_ACK2,
    DEFINITIONS_ANNOUNCE, // Deprecated
    DEFINITIONS_UPDATE,
    TRUNCATE,
    SCHEMA_CHECK,
    INDEX_SCAN, // Deprecated
    REPLICATION_FINISHED,
    INTERNAL_RESPONSE, // responses to internal calls
    COUNTER_MUTATION,
    STREAMING_REPAIR_REQUEST, // Deprecated
    STREAMING_REPAIR_RESPONSE, // Deprecated
    SNAPSHOT, // Similar to nt snapshot
    MIGRATION_REQUEST,
    GOSSIP_SHUTDOWN,
    _TRACE,
    ECHO,
    REPAIR_MESSAGE,
    PAXOS_PREPARE,
    PAXOS_PROPOSE,
    PAXOS_COMMIT,
    PAGED_RANGE,
    UNUSED_1,
    UNUSED_2,
    UNUSED_3,
    // Used by streaming
    STREAM_INIT_MESSAGE,
    PREPARE_MESSAGE,
    STREAM_MUTATION,
    INCOMING_FILE_MESSAGE,
    OUTGOING_FILE_MESSAGE,
    RECEIVED_MESSAGE,
    RETRY_MESSAGE,
    COMPLETE_MESSAGE,
    SESSION_FAILED_MESSAGE,
    LAST,
};

} // namespace net

namespace std {
template <>
class hash<net::messaging_verb> {
public:
    size_t operator()(const net::messaging_verb& x) const {
        return hash<int32_t>()(int32_t(x));
    }
};
} // namespace std

namespace net {

future<> ser_messaging_verb(output_stream<char>& out, messaging_verb& v);
future<> des_messaging_verb(input_stream<char>& in, messaging_verb& v);
future<> ser_sstring(output_stream<char>& out, sstring& v);
future<> des_sstring(input_stream<char>& in, sstring& v);
future<> ser_frozen_mutation(output_stream<char>& out, const frozen_mutation& v);
future<> des_frozen_mutation(input_stream<char>& in, frozen_mutation& v);

// NOTE: operator(input_stream<char>&, T&) takes a reference to uninitialized
//       T object and should use placement new in case T is non POD
struct serializer {
    template<typename T>
    inline future<T> read_integral(input_stream<char>& in) {
        static_assert(std::is_integral<T>::value, "T should be integral");

        return in.read_exactly(sizeof(T)).then([] (temporary_buffer<char> buf) {
            if (buf.size() != sizeof(T)) {
                throw rpc::closed_error();
            }
            return make_ready_future<T>(net::ntoh(*unaligned_cast<T*>(buf.get())));
        });
    }

    // For integer type
    template<typename T>
    inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<std::is_integral<std::remove_reference_t<T>>::value, void*> = nullptr) {
        auto v_ = net::hton(v);
        return out.write(reinterpret_cast<const char*>(&v_), sizeof(T));
    }
    template<typename T>
    inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<std::is_integral<T>::value, void*> = nullptr) {
        return in.read_exactly(sizeof(v)).then([&v] (temporary_buffer<char> buf) mutable {
            if (buf.size() != sizeof(v)) {
                throw rpc::closed_error();
            }
            v = net::ntoh(*reinterpret_cast<const net::packed<T>*>(buf.get()));
        });
    }

    // For vectors
    template<typename T>
    inline auto operator()(output_stream<char>& out, std::vector<T>& v) {
        return operator()(out, v.size()).then([&out, &v, this] {
            return do_for_each(v.begin(), v.end(), [&out, this] (T& e) {
                return operator()(out, e);
            });
        });
    }
    template<typename T>
    inline auto operator()(input_stream<char>& in, std::vector<T>& v) {
        using size_type = typename  std::vector<T>::size_type;
        return read_integral<size_type>(in).then([&v, &in, this] (size_type c) {
            new (&v) std::vector<T>;
            v.reserve(c);
            union U {
                U(){}
                ~U(){}
                U(U&&) {}
                T v;
            };
            return do_with(U(), [c, &v, &in, this] (U& u) {
                return do_until([c = c] () mutable {return !c--;}, [&v, &in, &u, this] () mutable {
                    return operator()(in, u.v).then([&u, &v] {
                        v.emplace_back(std::move(u.v));
                    });
                });
            });
        });
    }

    // For messaging_verb
    inline auto operator()(output_stream<char>& out, messaging_verb& v) {
        return ser_messaging_verb(out, v);
    }
    inline auto operator()(input_stream<char>& in, messaging_verb& v) {
        return des_messaging_verb(in, v);
    }

    // For sstring
    inline auto operator()(output_stream<char>& out, sstring& v) {
        return ser_sstring(out, v);
    }
    inline auto operator()(input_stream<char>& in, sstring& v) {
        return des_sstring(in, v);
    }

    // For frozen_mutation
    inline auto operator()(output_stream<char>& out, const frozen_mutation& v) {
        return ser_frozen_mutation(out, v);
    }
    inline auto operator()(output_stream<char>& out, frozen_mutation& v) {
        return operator()(out, const_cast<const frozen_mutation&>(v));
    }
    inline auto operator()(input_stream<char>& in, frozen_mutation& v) {
        return des_frozen_mutation(in, v);
    }

    // For complex types which have serialize()/deserialize(),  e.g. gms::gossip_digest_syn, gms::gossip_digest_ack2
    template<typename T>
    inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<!std::is_integral<std::remove_reference_t<T>>::value &&
                                                                             !std::is_enum<std::remove_reference_t<T>>::value, void*> = nullptr) {
        auto sz = serialize_int32_size + v.serialized_size();
        bytes b(bytes::initialized_later(), sz);
        auto _out = b.begin();
        serialize_int32(_out, int32_t(sz - serialize_int32_size));
        v.serialize(_out);
        return out.write(reinterpret_cast<const char*>(b.c_str()), sz);
    }
    template<typename T>
    inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<!std::is_integral<T>::value &&
                                                                          !std::is_enum<T>::value, void*> = nullptr) {
        return in.read_exactly(serialize_int32_size).then([&in, &v] (temporary_buffer<char> buf) mutable {
            if (buf.size() != serialize_int32_size) {
                throw rpc::closed_error();
            }
            size_t sz = net::ntoh(*reinterpret_cast<const net::packed<int32_t>*>(buf.get()));
            return in.read_exactly(sz).then([sz, &v] (temporary_buffer<char> buf) mutable {
                if (buf.size() != sz) {
                    throw rpc::closed_error();
                }
                bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), sz);
                new (&v) T(T::deserialize(bv));
                assert(bv.size() == 0);
                return make_ready_future<>();
            });
        });
    }
};

class messaging_service {
public:
    // FIXME: messaging service versioning
    static constexpr int32_t current_version = 0;

    struct shard_id {
        gms::inet_address addr;
        uint32_t cpu_id;
        friend inline bool operator==(const shard_id& x, const shard_id& y) {
            return x.addr == y.addr && x.cpu_id == y.cpu_id ;
        }
        friend inline bool operator<(const shard_id& x, const shard_id& y) {
            if (x.addr < y.addr) {
                return true;
            } else if (y.addr < x.addr) {
                return false;
            } else {
                return x.cpu_id < y.cpu_id;
            }
        }
        friend inline std::ostream& operator<<(std::ostream& os, const shard_id& x) {
            return os << x.addr << ":" << x.cpu_id;
        }
        struct hash {
            size_t operator()(const shard_id& id) const {
                return std::hash<uint32_t>()(id.cpu_id) + std::hash<uint32_t>()(id.addr.raw_addr());
            }
        };
    };
    struct shard_info {
        shard_info(std::unique_ptr<rpc::protocol<serializer, messaging_verb>::client>&& client)
            : rpc_client(std::move(client)) {
        }
        std::unique_ptr<rpc::protocol<serializer, messaging_verb>::client> rpc_client;
    };

    void foreach_client(std::function<void(const messaging_service::shard_id& id,
                    const messaging_service::shard_info& info)> f) const {
        for (auto i = _clients.cbegin(); i != _clients.cend(); i++) {
            f(i->first, i->second);
        }
    }

    void increment_dropped_messages(messaging_verb verb) {
        _dropped_messages[static_cast<int32_t>(verb)]++;
    }

    uint64_t get_dropped_messages(messaging_verb verb) const {
        return _dropped_messages[static_cast<int32_t>(verb)];
    }

    const uint64_t* get_dropped_messages() const {
        return _dropped_messages;
    }

    int32_t get_raw_version(const gms::inet_address& endpoint) const {
        // FIXME: messaging service versioning
        return current_version;
    }

    bool knows_version(const gms::inet_address& endpoint) const {
        // FIXME: messaging service versioning
        return true;
    }

private:
    static constexpr uint16_t _default_port = 7000;
    gms::inet_address _listen_address;
    uint16_t _port;
    rpc::protocol<serializer, messaging_verb> _rpc;
    rpc::protocol<serializer, messaging_verb>::server _server;
    std::unordered_map<shard_id, shard_info, shard_id::hash> _clients;
    uint64_t _dropped_messages[static_cast<int32_t>(messaging_verb::LAST)] = {};
public:
    messaging_service(gms::inet_address ip = gms::inet_address("0.0.0.0"))
        : _listen_address(ip)
        , _port(_default_port)
        , _rpc(serializer{})
        , _server(_rpc, ipv4_addr{_listen_address.raw_addr(), _port}) {
    }
public:
    uint16_t port() {
        return _port;
    }
    auto listen_address() {
        return _listen_address;
    }
    future<> stop() {
        return when_all(_server.stop(),
            parallel_for_each(_clients, [](std::pair<const shard_id, shard_info>& c) {
                return c.second.rpc_client->stop();
            })
        ).discard_result();
    }

    static auto no_wait() {
        return rpc::no_wait;
    }
public:
    // Register a handler (a callback lambda) for verb
    template <typename Func>
    void register_handler(messaging_verb verb, Func&& func) {
        _rpc.register_handler(verb, std::move(func));
    }

    // Send a message for verb
    template <typename MsgIn, typename... MsgOut>
    auto send_message(messaging_verb verb, shard_id id, MsgOut&&... msg) {
        auto& rpc_client = get_rpc_client(id);
        auto rpc_handler = _rpc.make_client<MsgIn(MsgOut...)>(verb);
        return rpc_handler(rpc_client, std::forward<MsgOut>(msg)...).then_wrapped([this, id, verb] (auto&& f) {
            try {
                if (f.failed()) {
                    this->increment_dropped_messages(verb);
                    f.get();
                    assert(false); // never reached
                }
                return std::move(f);
            } catch(...) {
                // FIXME: we need to distinguish between a transport error and
                // a server error.
                // remove_rpc_client(id);
                throw;
            }
        });
    }

    template <typename... MsgOut>
    auto send_message_oneway(messaging_verb verb, shard_id id, MsgOut&&... msg) {
        return send_message<rpc::no_wait_type>(std::move(verb), std::move(id), std::forward<MsgOut>(msg)...);
    }
private:
    // Return rpc::protocol::client for a shard which is a ip + cpuid pair.
    rpc::protocol<serializer, messaging_verb>::client& get_rpc_client(shard_id id) {
        auto it = _clients.find(id);
        if (it == _clients.end()) {
            auto remote_addr = ipv4_addr(id.addr.raw_addr(), _port);
            auto client = std::make_unique<rpc::protocol<serializer, messaging_verb>::client>(_rpc, remote_addr, ipv4_addr{_listen_address.raw_addr(), 0});
            it = _clients.emplace(id, shard_info(std::move(client))).first;
            return *it->second.rpc_client;
        } else {
            return *it->second.rpc_client;
        }
    }

    void remove_rpc_client(shard_id id) {
        _clients.erase(id);
    }
};

extern distributed<messaging_service> _the_messaging_service;

inline distributed<messaging_service>& get_messaging_service() {
    return _the_messaging_service;
}

inline messaging_service& get_local_messaging_service() {
    return _the_messaging_service.local();
}

future<> init_messaging_service(sstring listen_address, db::config::seed_provider_type seed_provider);
} // namespace net
<commit_msg>messaging_service: Add adaptors for types having db::serializer<><commit_after>/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#pragma once

#include "core/reactor.hh"
#include "core/iostream.hh"
#include "core/distributed.hh"
#include "core/print.hh"
#include "core/sstring.hh"
#include "net/api.hh"
#include "util/serialization.hh"
#include "gms/inet_address.hh"
#include "rpc/rpc.hh"
#include <unordered_map>
#include "db/config.hh"
#include "frozen_mutation.hh"
#include "db/serializer.hh"

namespace net {

/* All verb handler identifiers */
enum class messaging_verb : int32_t {
    MUTATION,
    MUTATION_DONE,
    BINARY, // Deprecated
    READ_REPAIR,
    READ,
    READ_DATA,
    READ_DIGEST,
    REQUEST_RESPONSE, // client-initiated reads and writes
    STREAM_INITIATE, // Deprecated
    STREAM_INITIATE_DONE, // Deprecated
    STREAM_REPLY, // Deprecated
    STREAM_REQUEST, // Deprecated
    RANGE_SLICE,
    BOOTSTRAP_TOKEN, // Deprecated
    TREE_REQUEST, // Deprecated
    TREE_RESPONSE, // Deprecated
    JOIN, // Deprecated
    GOSSIP_DIGEST_SYN,
    GOSSIP_DIGEST_ACK,
    GOSSIP_DIGEST_ACK2,
    DEFINITIONS_ANNOUNCE, // Deprecated
    DEFINITIONS_UPDATE,
    TRUNCATE,
    SCHEMA_CHECK,
    INDEX_SCAN, // Deprecated
    REPLICATION_FINISHED,
    INTERNAL_RESPONSE, // responses to internal calls
    COUNTER_MUTATION,
    STREAMING_REPAIR_REQUEST, // Deprecated
    STREAMING_REPAIR_RESPONSE, // Deprecated
    SNAPSHOT, // Similar to nt snapshot
    MIGRATION_REQUEST,
    GOSSIP_SHUTDOWN,
    _TRACE,
    ECHO,
    REPAIR_MESSAGE,
    PAXOS_PREPARE,
    PAXOS_PROPOSE,
    PAXOS_COMMIT,
    PAGED_RANGE,
    UNUSED_1,
    UNUSED_2,
    UNUSED_3,
    // Used by streaming
    STREAM_INIT_MESSAGE,
    PREPARE_MESSAGE,
    STREAM_MUTATION,
    INCOMING_FILE_MESSAGE,
    OUTGOING_FILE_MESSAGE,
    RECEIVED_MESSAGE,
    RETRY_MESSAGE,
    COMPLETE_MESSAGE,
    SESSION_FAILED_MESSAGE,
    LAST,
};

} // namespace net

namespace std {
template <>
class hash<net::messaging_verb> {
public:
    size_t operator()(const net::messaging_verb& x) const {
        return hash<int32_t>()(int32_t(x));
    }
};
} // namespace std

namespace net {

future<> ser_messaging_verb(output_stream<char>& out, messaging_verb& v);
future<> des_messaging_verb(input_stream<char>& in, messaging_verb& v);
future<> ser_sstring(output_stream<char>& out, sstring& v);
future<> des_sstring(input_stream<char>& in, sstring& v);
future<> ser_frozen_mutation(output_stream<char>& out, const frozen_mutation& v);
future<> des_frozen_mutation(input_stream<char>& in, frozen_mutation& v);

// NOTE: operator(input_stream<char>&, T&) takes a reference to uninitialized
//       T object and should use placement new in case T is non POD
struct serializer {
    template<typename T>
    inline future<T> read_integral(input_stream<char>& in) {
        static_assert(std::is_integral<T>::value, "T should be integral");

        return in.read_exactly(sizeof(T)).then([] (temporary_buffer<char> buf) {
            if (buf.size() != sizeof(T)) {
                throw rpc::closed_error();
            }
            return make_ready_future<T>(net::ntoh(*unaligned_cast<T*>(buf.get())));
        });
    }

    // Adaptor for writing objects having db::serializer<>
    template<typename Serializable>
    inline future<> write_serializable(output_stream<char>& out, const Serializable& v) {
        db::serializer<Serializable> ser(v);
        bytes b(bytes::initialized_later(), ser.size() + data_output::serialized_size<uint32_t>());
        data_output d_out(b);
        d_out.write<uint32_t>(ser.size());
        ser.write(d_out);
        return out.write(reinterpret_cast<const char*>(b.c_str()), b.size());
    }

    // Adaptor for reading objects having db::serializer<>
    template<typename Serializable>
    inline future<> read_serializable(input_stream<char>& in, Serializable& v) {
        return read_integral<uint32_t>(in).then([&in, &v] (auto sz) mutable {
            return in.read_exactly(sz).then([sz, &v] (temporary_buffer<char> buf) mutable {
                if (buf.size() != sz) {
                    throw rpc::closed_error();
                }
                bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), sz);
                data_input in(bv);
                db::serializer<Serializable>::read(v, in);
            });
        });
    }

    // For integer type
    template<typename T>
    inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<std::is_integral<std::remove_reference_t<T>>::value, void*> = nullptr) {
        auto v_ = net::hton(v);
        return out.write(reinterpret_cast<const char*>(&v_), sizeof(T));
    }
    template<typename T>
    inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<std::is_integral<T>::value, void*> = nullptr) {
        return in.read_exactly(sizeof(v)).then([&v] (temporary_buffer<char> buf) mutable {
            if (buf.size() != sizeof(v)) {
                throw rpc::closed_error();
            }
            v = net::ntoh(*reinterpret_cast<const net::packed<T>*>(buf.get()));
        });
    }

    // For vectors
    template<typename T>
    inline auto operator()(output_stream<char>& out, std::vector<T>& v) {
        return operator()(out, v.size()).then([&out, &v, this] {
            return do_for_each(v.begin(), v.end(), [&out, this] (T& e) {
                return operator()(out, e);
            });
        });
    }
    template<typename T>
    inline auto operator()(input_stream<char>& in, std::vector<T>& v) {
        using size_type = typename  std::vector<T>::size_type;
        return read_integral<size_type>(in).then([&v, &in, this] (size_type c) {
            new (&v) std::vector<T>;
            v.reserve(c);
            union U {
                U(){}
                ~U(){}
                U(U&&) {}
                T v;
            };
            return do_with(U(), [c, &v, &in, this] (U& u) {
                return do_until([c = c] () mutable {return !c--;}, [&v, &in, &u, this] () mutable {
                    return operator()(in, u.v).then([&u, &v] {
                        v.emplace_back(std::move(u.v));
                    });
                });
            });
        });
    }

    // For messaging_verb
    inline auto operator()(output_stream<char>& out, messaging_verb& v) {
        return ser_messaging_verb(out, v);
    }
    inline auto operator()(input_stream<char>& in, messaging_verb& v) {
        return des_messaging_verb(in, v);
    }

    // For sstring
    inline auto operator()(output_stream<char>& out, sstring& v) {
        return ser_sstring(out, v);
    }
    inline auto operator()(input_stream<char>& in, sstring& v) {
        return des_sstring(in, v);
    }

    // For frozen_mutation
    inline auto operator()(output_stream<char>& out, const frozen_mutation& v) {
        return ser_frozen_mutation(out, v);
    }
    inline auto operator()(output_stream<char>& out, frozen_mutation& v) {
        return operator()(out, const_cast<const frozen_mutation&>(v));
    }
    inline auto operator()(input_stream<char>& in, frozen_mutation& v) {
        return des_frozen_mutation(in, v);
    }

    // For complex types which have serialize()/deserialize(),  e.g. gms::gossip_digest_syn, gms::gossip_digest_ack2
    template<typename T>
    inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<!std::is_integral<std::remove_reference_t<T>>::value &&
                                                                             !std::is_enum<std::remove_reference_t<T>>::value, void*> = nullptr) {
        auto sz = serialize_int32_size + v.serialized_size();
        bytes b(bytes::initialized_later(), sz);
        auto _out = b.begin();
        serialize_int32(_out, int32_t(sz - serialize_int32_size));
        v.serialize(_out);
        return out.write(reinterpret_cast<const char*>(b.c_str()), sz);
    }
    template<typename T>
    inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<!std::is_integral<T>::value &&
                                                                          !std::is_enum<T>::value, void*> = nullptr) {
        return in.read_exactly(serialize_int32_size).then([&in, &v] (temporary_buffer<char> buf) mutable {
            if (buf.size() != serialize_int32_size) {
                throw rpc::closed_error();
            }
            size_t sz = net::ntoh(*reinterpret_cast<const net::packed<int32_t>*>(buf.get()));
            return in.read_exactly(sz).then([sz, &v] (temporary_buffer<char> buf) mutable {
                if (buf.size() != sz) {
                    throw rpc::closed_error();
                }
                bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), sz);
                new (&v) T(T::deserialize(bv));
                assert(bv.size() == 0);
                return make_ready_future<>();
            });
        });
    }
};

class messaging_service {
public:
    // FIXME: messaging service versioning
    static constexpr int32_t current_version = 0;

    struct shard_id {
        gms::inet_address addr;
        uint32_t cpu_id;
        friend inline bool operator==(const shard_id& x, const shard_id& y) {
            return x.addr == y.addr && x.cpu_id == y.cpu_id ;
        }
        friend inline bool operator<(const shard_id& x, const shard_id& y) {
            if (x.addr < y.addr) {
                return true;
            } else if (y.addr < x.addr) {
                return false;
            } else {
                return x.cpu_id < y.cpu_id;
            }
        }
        friend inline std::ostream& operator<<(std::ostream& os, const shard_id& x) {
            return os << x.addr << ":" << x.cpu_id;
        }
        struct hash {
            size_t operator()(const shard_id& id) const {
                return std::hash<uint32_t>()(id.cpu_id) + std::hash<uint32_t>()(id.addr.raw_addr());
            }
        };
    };
    struct shard_info {
        shard_info(std::unique_ptr<rpc::protocol<serializer, messaging_verb>::client>&& client)
            : rpc_client(std::move(client)) {
        }
        std::unique_ptr<rpc::protocol<serializer, messaging_verb>::client> rpc_client;
    };

    void foreach_client(std::function<void(const messaging_service::shard_id& id,
                    const messaging_service::shard_info& info)> f) const {
        for (auto i = _clients.cbegin(); i != _clients.cend(); i++) {
            f(i->first, i->second);
        }
    }

    void increment_dropped_messages(messaging_verb verb) {
        _dropped_messages[static_cast<int32_t>(verb)]++;
    }

    uint64_t get_dropped_messages(messaging_verb verb) const {
        return _dropped_messages[static_cast<int32_t>(verb)];
    }

    const uint64_t* get_dropped_messages() const {
        return _dropped_messages;
    }

    int32_t get_raw_version(const gms::inet_address& endpoint) const {
        // FIXME: messaging service versioning
        return current_version;
    }

    bool knows_version(const gms::inet_address& endpoint) const {
        // FIXME: messaging service versioning
        return true;
    }

private:
    static constexpr uint16_t _default_port = 7000;
    gms::inet_address _listen_address;
    uint16_t _port;
    rpc::protocol<serializer, messaging_verb> _rpc;
    rpc::protocol<serializer, messaging_verb>::server _server;
    std::unordered_map<shard_id, shard_info, shard_id::hash> _clients;
    uint64_t _dropped_messages[static_cast<int32_t>(messaging_verb::LAST)] = {};
public:
    messaging_service(gms::inet_address ip = gms::inet_address("0.0.0.0"))
        : _listen_address(ip)
        , _port(_default_port)
        , _rpc(serializer{})
        , _server(_rpc, ipv4_addr{_listen_address.raw_addr(), _port}) {
    }
public:
    uint16_t port() {
        return _port;
    }
    auto listen_address() {
        return _listen_address;
    }
    future<> stop() {
        return when_all(_server.stop(),
            parallel_for_each(_clients, [](std::pair<const shard_id, shard_info>& c) {
                return c.second.rpc_client->stop();
            })
        ).discard_result();
    }

    static auto no_wait() {
        return rpc::no_wait;
    }
public:
    // Register a handler (a callback lambda) for verb
    template <typename Func>
    void register_handler(messaging_verb verb, Func&& func) {
        _rpc.register_handler(verb, std::move(func));
    }

    // Send a message for verb
    template <typename MsgIn, typename... MsgOut>
    auto send_message(messaging_verb verb, shard_id id, MsgOut&&... msg) {
        auto& rpc_client = get_rpc_client(id);
        auto rpc_handler = _rpc.make_client<MsgIn(MsgOut...)>(verb);
        return rpc_handler(rpc_client, std::forward<MsgOut>(msg)...).then_wrapped([this, id, verb] (auto&& f) {
            try {
                if (f.failed()) {
                    this->increment_dropped_messages(verb);
                    f.get();
                    assert(false); // never reached
                }
                return std::move(f);
            } catch(...) {
                // FIXME: we need to distinguish between a transport error and
                // a server error.
                // remove_rpc_client(id);
                throw;
            }
        });
    }

    template <typename... MsgOut>
    auto send_message_oneway(messaging_verb verb, shard_id id, MsgOut&&... msg) {
        return send_message<rpc::no_wait_type>(std::move(verb), std::move(id), std::forward<MsgOut>(msg)...);
    }
private:
    // Return rpc::protocol::client for a shard which is a ip + cpuid pair.
    rpc::protocol<serializer, messaging_verb>::client& get_rpc_client(shard_id id) {
        auto it = _clients.find(id);
        if (it == _clients.end()) {
            auto remote_addr = ipv4_addr(id.addr.raw_addr(), _port);
            auto client = std::make_unique<rpc::protocol<serializer, messaging_verb>::client>(_rpc, remote_addr, ipv4_addr{_listen_address.raw_addr(), 0});
            it = _clients.emplace(id, shard_info(std::move(client))).first;
            return *it->second.rpc_client;
        } else {
            return *it->second.rpc_client;
        }
    }

    void remove_rpc_client(shard_id id) {
        _clients.erase(id);
    }
};

extern distributed<messaging_service> _the_messaging_service;

inline distributed<messaging_service>& get_messaging_service() {
    return _the_messaging_service;
}

inline messaging_service& get_local_messaging_service() {
    return _the_messaging_service.local();
}

future<> init_messaging_service(sstring listen_address, db::config::seed_provider_type seed_provider);
} // namespace net
<|endoftext|>


<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009      Andrew Manson <g.real.ate@gmail.com>
//

#include "GeoLineStringGraphicsItem.h"

#include "GeoDataLineString.h"
#include "GeoDataLineStyle.h"
#include "GeoPainter.h"
#include "ViewportParams.h"
#include "GeoDataStyle.h"

namespace Marble
{

GeoLineStringGraphicsItem::GeoLineStringGraphicsItem( const GeoDataFeature *feature, const GeoDataLineString* lineString )
        : GeoGraphicsItem( feature ),
          m_lineString( lineString )
{
}

void GeoLineStringGraphicsItem::setLineString( const GeoDataLineString* lineString )
{
    m_lineString = lineString;
}

const GeoDataLatLonAltBox& GeoLineStringGraphicsItem::latLonAltBox() const
{
    return m_lineString->latLonAltBox();
}

void GeoLineStringGraphicsItem::paint( GeoPainter* painter, const ViewportParams* viewport )
{
    if ( !style() )
    {
        painter->save();
        painter->setPen( QPen() );
        painter->drawPolyline( *m_lineString );
        painter->restore();
        return;
    }

    if(style()->lineStyle().paintedColor() == Qt::transparent)
        return;

    painter->save();
    QPen currentPen = painter->pen();

    if ( currentPen.color() != style()->lineStyle().paintedColor() )
        currentPen.setColor( style()->lineStyle().paintedColor() );

    if ( currentPen.widthF() != style()->lineStyle().width() ||
            style()->lineStyle().physicalWidth() != 0.0 )
    {
        if ( float( viewport->radius() ) / EARTH_RADIUS * style()->lineStyle().physicalWidth() < style()->lineStyle().width() )
            currentPen.setWidthF( style()->lineStyle().width() );
        else
            currentPen.setWidthF( float( viewport->radius() ) / EARTH_RADIUS * style()->lineStyle().physicalWidth() );
    }

    if ( currentPen.capStyle() != style()->lineStyle().capStyle() )
        currentPen.setCapStyle( style()->lineStyle().capStyle() );

    if ( currentPen.style() != style()->lineStyle().penStyle() )
        currentPen.setStyle( style()->lineStyle().penStyle() );

    if ( style()->lineStyle().penStyle() == Qt::CustomDashLine )
        currentPen.setDashPattern( style()->lineStyle().dashPattern() );

    if ( painter->mapQuality() != Marble::HighQuality
            && painter->mapQuality() != Marble::PrintQuality )
    {
        QColor penColor = currentPen.color();
        penColor.setAlpha( 255 );
        currentPen.setColor( penColor );
    }

    if ( painter->pen() != currentPen ) painter->setPen( currentPen );
    if ( style()->lineStyle().background() )
    {
        QBrush brush = painter->background();
        brush.setColor( style()->polyStyle().paintedColor() );
        painter->setBackground( brush );

        painter->setBackgroundMode( Qt::OpaqueMode );
    }
    painter->drawPolyline( *m_lineString );
    painter->restore();
}

}
<commit_msg>no need to optimize for extremely rare corner cases<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009      Andrew Manson <g.real.ate@gmail.com>
//

#include "GeoLineStringGraphicsItem.h"

#include "GeoDataLineString.h"
#include "GeoDataLineStyle.h"
#include "GeoPainter.h"
#include "ViewportParams.h"
#include "GeoDataStyle.h"

namespace Marble
{

GeoLineStringGraphicsItem::GeoLineStringGraphicsItem( const GeoDataFeature *feature, const GeoDataLineString* lineString )
        : GeoGraphicsItem( feature ),
          m_lineString( lineString )
{
}

void GeoLineStringGraphicsItem::setLineString( const GeoDataLineString* lineString )
{
    m_lineString = lineString;
}

const GeoDataLatLonAltBox& GeoLineStringGraphicsItem::latLonAltBox() const
{
    return m_lineString->latLonAltBox();
}

void GeoLineStringGraphicsItem::paint( GeoPainter* painter, const ViewportParams* viewport )
{
    if ( !style() )
    {
        painter->save();
        painter->setPen( QPen() );
        painter->drawPolyline( *m_lineString );
        painter->restore();
        return;
    }

    painter->save();
    QPen currentPen = painter->pen();

    if ( currentPen.color() != style()->lineStyle().paintedColor() )
        currentPen.setColor( style()->lineStyle().paintedColor() );

    if ( currentPen.widthF() != style()->lineStyle().width() ||
            style()->lineStyle().physicalWidth() != 0.0 )
    {
        if ( float( viewport->radius() ) / EARTH_RADIUS * style()->lineStyle().physicalWidth() < style()->lineStyle().width() )
            currentPen.setWidthF( style()->lineStyle().width() );
        else
            currentPen.setWidthF( float( viewport->radius() ) / EARTH_RADIUS * style()->lineStyle().physicalWidth() );
    }

    if ( currentPen.capStyle() != style()->lineStyle().capStyle() )
        currentPen.setCapStyle( style()->lineStyle().capStyle() );

    if ( currentPen.style() != style()->lineStyle().penStyle() )
        currentPen.setStyle( style()->lineStyle().penStyle() );

    if ( style()->lineStyle().penStyle() == Qt::CustomDashLine )
        currentPen.setDashPattern( style()->lineStyle().dashPattern() );

    if ( painter->mapQuality() != Marble::HighQuality
            && painter->mapQuality() != Marble::PrintQuality )
    {
        QColor penColor = currentPen.color();
        penColor.setAlpha( 255 );
        currentPen.setColor( penColor );
    }

    if ( painter->pen() != currentPen ) painter->setPen( currentPen );
    if ( style()->lineStyle().background() )
    {
        QBrush brush = painter->background();
        brush.setColor( style()->polyStyle().paintedColor() );
        painter->setBackground( brush );

        painter->setBackgroundMode( Qt::OpaqueMode );
    }
    painter->drawPolyline( *m_lineString );
    painter->restore();
}

}
<|endoftext|>


<commit_before>/*
    This file is part of KAddressBook.
    Copyright (c) 2002 Tobias Koenig <tokoe@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <qcombobox.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qpushbutton.h>
#include <qtooltip.h>
#include <qwhatsthis.h>

#include <kdialog.h>
#include <klineedit.h>
#include <klocale.h>

#include "incsearchwidget.h"

IncSearchWidget::IncSearchWidget( QWidget *parent, const char *name )
    : QWidget( parent, name )
{
  QHBoxLayout *layout = new QHBoxLayout( this, 2, KDialog::spacingHint() );

  QLabel *label = new QLabel( i18n( "Search:" ), this );
  label->setAlignment( QLabel::AlignVCenter | QLabel::AlignRight );
  layout->addWidget( label );

  mSearchText = new KLineEdit( this );
  QWhatsThis::add( mSearchText, i18n( "The incremental search
Enter some text here will start the search for the contact, which matches the search pattern best. The part of the contact, which will be used for matching, depends on the field selection." ) );
  label->setBuddy( mSearchText );
  layout->addWidget( mSearchText );

  mFieldCombo = new QComboBox( false, this );
  layout->addWidget( mFieldCombo );

  QPushButton *button = new QPushButton( i18n( "Reset" ), this );
  layout->addWidget( button );

  QToolTip::add( mFieldCombo, i18n( "Select incremental search field" ) );
  QWhatsThis::add( mFieldCombo, i18n( "Here you can choose the field, which shall be used for incremental search." ) );

  connect( mSearchText, SIGNAL( textChanged( const QString& ) ),
           SLOT( announceDoSearch() ) );
  connect( mSearchText, SIGNAL( returnPressed() ),
           SLOT( announceDoSearch() ) );
  connect( mFieldCombo, SIGNAL( activated( const QString& ) ),
           SLOT( announceDoSearch() ) );
  connect( button, SIGNAL( clicked() ), SIGNAL( doReset() ) );
  connect( button, SIGNAL( clicked() ),
           mSearchText, SLOT( clear() ) );
  connect( button, SIGNAL( clicked() ),
           SLOT( announceDoSearch() ) );

  initFields();

  setFocusProxy( mSearchText );
}

IncSearchWidget::~IncSearchWidget()
{
}

void IncSearchWidget::announceDoSearch()
{
  emit doSearch( mSearchText->text() );
}

void IncSearchWidget::initFields()
{
  mFieldList = KABC::Field::allFields();

  mFieldCombo->clear();
  mFieldCombo->insertItem( i18n( "All Fields" ) );

  KABC::Field::List::ConstIterator it;
  for ( it = mFieldList.begin(); it != mFieldList.end(); ++it )
    mFieldCombo->insertItem( (*it)->label() );

  announceDoSearch();
}

KABC::Field *IncSearchWidget::currentField() const
{
  if ( mFieldCombo->currentItem() == -1 || mFieldCombo->currentItem() == 0 )
    return 0;  // for error or 'use all fields'
  else
    return mFieldList[ mFieldCombo->currentItem() - 1 ];
}

void IncSearchWidget::setCurrentItem( int pos )
{
  mFieldCombo->setCurrentItem( pos );
}

int IncSearchWidget::currentItem() const
{
  return mFieldCombo->currentItem();
}

#include "incsearchwidget.moc"
<commit_msg>Replaced the 'Reset' button by a nicer one...<commit_after>/*
    This file is part of KAddressBook.
    Copyright (c) 2002 Tobias Koenig <tokoe@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <qcombobox.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qpushbutton.h>
#include <qtooltip.h>
#include <qwhatsthis.h>

#include <kdialog.h>
#include <kiconloader.h>
#include <klineedit.h>
#include <klocale.h>

#include "incsearchwidget.h"

IncSearchWidget::IncSearchWidget( QWidget *parent, const char *name )
    : QWidget( parent, name )
{
  QHBoxLayout *layout = new QHBoxLayout( this, 2, KDialog::spacingHint() );

  QLabel *label = new QLabel( i18n( "Search:" ), this );
  label->setAlignment( QLabel::AlignVCenter | QLabel::AlignRight );
  layout->addWidget( label );

  mSearchText = new KLineEdit( this );
  QWhatsThis::add( mSearchText, i18n( "The incremental search
Enter some text here will start the search for the contact, which matches the search pattern best. The part of the contact, which will be used for matching, depends on the field selection." ) );
  label->setBuddy( mSearchText );
  layout->addWidget( mSearchText );

  QPushButton *button = new QPushButton( this );
  button->setAutoDefault( false );
  button->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ) );
  button->setPixmap( SmallIcon( "clear_left" ) );
  QToolTip::add( button, i18n( "Reset" ) );
  layout->addWidget( button );

  mFieldCombo = new QComboBox( false, this );
  layout->addWidget( mFieldCombo );

  QToolTip::add( mFieldCombo, i18n( "Select incremental search field" ) );
  QWhatsThis::add( mFieldCombo, i18n( "Here you can choose the field, which shall be used for incremental search." ) );

  connect( mSearchText, SIGNAL( textChanged( const QString& ) ),
           SLOT( announceDoSearch() ) );
  connect( mSearchText, SIGNAL( returnPressed() ),
           SLOT( announceDoSearch() ) );
  connect( mFieldCombo, SIGNAL( activated( const QString& ) ),
           SLOT( announceDoSearch() ) );
  connect( button, SIGNAL( clicked() ), SIGNAL( doReset() ) );
  connect( button, SIGNAL( clicked() ),
           mSearchText, SLOT( clear() ) );
  connect( button, SIGNAL( clicked() ),
           SLOT( announceDoSearch() ) );

  initFields();

  setFocusProxy( mSearchText );
}

IncSearchWidget::~IncSearchWidget()
{
}

void IncSearchWidget::announceDoSearch()
{
  emit doSearch( mSearchText->text() );
}

void IncSearchWidget::initFields()
{
  mFieldList = KABC::Field::allFields();

  mFieldCombo->clear();
  mFieldCombo->insertItem( i18n( "All Fields" ) );

  KABC::Field::List::ConstIterator it;
  for ( it = mFieldList.begin(); it != mFieldList.end(); ++it )
    mFieldCombo->insertItem( (*it)->label() );

  announceDoSearch();
}

KABC::Field *IncSearchWidget::currentField() const
{
  if ( mFieldCombo->currentItem() == -1 || mFieldCombo->currentItem() == 0 )
    return 0;  // for error or 'use all fields'
  else
    return mFieldList[ mFieldCombo->currentItem() - 1 ];
}

void IncSearchWidget::setCurrentItem( int pos )
{
  mFieldCombo->setCurrentItem( pos );
}

int IncSearchWidget::currentItem() const
{
  return mFieldCombo->currentItem();
}

#include "incsearchwidget.moc"
<|endoftext|>


<commit_before>#include "GroupTreeCtrl.h"
#include "MultiSpritesImpl.h"
#include "GroupTreeImpl.h"
#include "GroupTreeIO.h"

#include "dataset/Group.h"
#include "dataset/ISprite.h"

#include <sstream>
#include <queue>
#include <wx/menu.h>

namespace d2d
{

BEGIN_EVENT_TABLE(GroupTreeCtrl, wxTreeCtrl)
	EVT_TREE_ITEM_RIGHT_CLICK(ID_GROUP_TREE_CTRL, GroupTreeCtrl::OnItemRClick)
	EVT_TREE_ITEM_MENU(ID_GROUP_TREE_CTRL, GroupTreeCtrl::OnItemMenu)
	EVT_TREE_ITEM_ACTIVATED(ID_GROUP_TREE_CTRL, GroupTreeCtrl::OnItemActivated)
	EVT_TREE_BEGIN_DRAG(ID_GROUP_TREE_CTRL, GroupTreeCtrl::OnBeginDrag)
	EVT_TREE_END_DRAG(ID_GROUP_TREE_CTRL, GroupTreeCtrl::OnEndDrag)
END_EVENT_TABLE()

GroupTreeCtrl::GroupTreeCtrl(wxWindow* parent, MultiSpritesImpl* sprite_impl)
	: wxTreeCtrl(parent, ID_GROUP_TREE_CTRL, wxDefaultPosition, wxDefaultSize,
	wxTR_EDIT_LABELS | wxTR_HIDE_ROOT)
	, m_sprite_impl(sprite_impl)
	, m_remove_open(true)
{
	m_root = AddRoot("Root");
}

void GroupTreeCtrl::StoreToFile(Json::Value& value) const
{
	Traverse(GroupTreeImpl::StoreVisitor(this, value));
}

void GroupTreeCtrl::LoadFromFile(const Json::Value& value)
{
	GroupTreeIO io(this, m_sprite_impl);
	io.Load(value);
}

void GroupTreeCtrl::Traverse(IGroupTreeVisitor& visitor) const
{
	Traverse(m_root, visitor);
}

wxTreeItemId GroupTreeCtrl::AddNode()
{
	static int s_num = 0;

	std::ostringstream ss;
	ss << "Group" << s_num++;
	std::string text = ss.str();

	return AddNode(text);
}

wxTreeItemId GroupTreeCtrl::AddNode(const std::string& name)
{
	GroupTreeItem* data = new GroupTreeItem(new Group(name));

	wxTreeItemId id = GetFocusedItem();
	if (id.IsOk()) {
		data->SetId(id);
		return AddNode(id, name, data);
	} else {
		data->SetId(m_root);
		return AddNode(m_root, name, data);
	}
}

wxTreeItemId GroupTreeCtrl::AddNode(const std::string& name, wxTreeItemId parent)
{
	GroupTreeItem* data = new GroupTreeItem(new Group(name));
	return AddNode(parent, name, data);
}

void GroupTreeCtrl::DelNode()
{
	wxTreeItemId id = GetFocusedItem();
	if (id.IsOk()) {
		Delete(id);
	}
}

wxTreeItemId GroupTreeCtrl::AddSprite(wxTreeItemId parent, d2d::ISprite* spr)
{
	if (!parent.IsOk()) {
		return m_root;
	}

	GroupTreeItem* data = (GroupTreeItem*)GetItemData(parent);
	if (!data) {
		return m_root;
	}

	Group* group = data->m_group;
	if (!group) {
		return m_root;
	}

	bool ok = group->Insert(spr);
	if (ok) {
		GroupTreeItem* data = new GroupTreeItem(spr);
		return AddNode(parent, spr->name, data);
	} else {
		return m_root;
	}
}

void GroupTreeCtrl::Clear()
{
	if (!IsEmpty()) {
		CollapseAndReset(m_root);
	}
}

void GroupTreeCtrl::Remove(ISprite* sprite)
{
	if (m_remove_open) {
		Traverse(GroupTreeImpl::RemoveVisitor(this, sprite));
	}
}

void GroupTreeCtrl::Visible(wxTreeItemId id, bool visible)
{
	Traverse(id, GroupTreeImpl::SetVisibleVisitor(this, visible));
}

void GroupTreeCtrl::Editable(wxTreeItemId id, bool editable)
{
	Traverse(id, GroupTreeImpl::SetEditableVisitor(this, editable));
}

wxTreeItemId GroupTreeCtrl::AddNode(wxTreeItemId parent, const std::string& name, GroupTreeItem* data)
{
	wxTreeItemId id = AppendItem(parent, name, -1, -1, data);
	ExpandAll();
	return id;
}

void GroupTreeCtrl::OnItemRClick(wxTreeEvent& event)
{
	wxTreeItemId itemId = event.GetItem();

	GroupTreeItem* item = (GroupTreeItem*)GetItemData(itemId);

	event.Skip();
}

void GroupTreeCtrl::OnItemMenu(wxTreeEvent& event)
{
	wxTreeItemId id = event.GetItem();
	if (!id.IsOk()) {
		return;
	}

	wxPoint clientpt = event.GetPoint();
	wxPoint screenpt = ClientToScreen(clientpt);
	ShowMenu(id, clientpt);
	event.Skip();
}

void GroupTreeCtrl::OnItemActivated(wxTreeEvent& event)
{
	wxTreeItemId id = event.GetItem();
	SpriteSelection* selection = m_sprite_impl->getSpriteSelection();
	selection->Clear();
	Traverse(id, GroupTreeImpl::SelectVisitor(this, selection));
}

void GroupTreeCtrl::OnBeginDrag(wxTreeEvent& event)
{
	m_dragged_item = event.GetItem();
	event.Allow();
}

void GroupTreeCtrl::OnEndDrag(wxTreeEvent& event)
{
	wxTreeItemId item_src = m_dragged_item,
		item_dst = event.GetItem();
	if (!item_dst.IsOk()) {
		return;
	}

	wxLogDebug("Drag from %s to %s", GetItemText(item_src), GetItemText(item_dst));

	// old info
	GroupTreeItem* data = (GroupTreeItem*)GetItemData(item_src);
	std::string name = GetItemText(item_src);
	// insert
 	wxTreeItemId new_item = AppendItem(item_dst, name, -1, -1, data->Clone());
	ExpandAll();
	// copy older's children
	Traverse(item_src, GroupTreeImpl::CopyPasteVisitor(this, item_src, new_item));
	// remove
	Delete(item_src);
	// sort
	ReorderSprites();
}

void GroupTreeCtrl::OnMenuAddSprites(wxCommandEvent& event)
{
	if (!m_on_menu_id.IsOk()) {
		return;
	}

	GroupTreeItem* data = (GroupTreeItem*)GetItemData(m_on_menu_id);
	if (!data) {
		return;
	}

	Group* group = data->m_group;
	if (!group) {
		return;
	}

	SpriteSelection* selection = m_sprite_impl->getSpriteSelection();
	std::vector<ISprite*> sprites;
	selection->Traverse(FetchAllVisitor<ISprite>(sprites));
	for (int i = 0, n = sprites.size(); i < n; ++i) {
		ISprite* spr = sprites[i];
		bool ok = group->Insert(spr);
		if (ok) {
			GroupTreeItem* data = new GroupTreeItem(spr);
			AddNode(m_on_menu_id, spr->name, data);
		}
	}
}

void GroupTreeCtrl::OnMenuClear(wxCommandEvent& event)
{
	if (!m_on_menu_id.IsOk()) {
		return;
	}

	Group* group = ((GroupTreeItem*)GetItemData(m_on_menu_id))->m_group;
	if (!group) {
		return;
	}

	group->Clear();
	CollapseAndReset(m_on_menu_id);
}

void GroupTreeCtrl::OnMenuVisible(wxCommandEvent& event)
{
	Traverse(m_on_menu_id, GroupTreeImpl::VisibleVisitor(this));
}

void GroupTreeCtrl::OnMenuEditable(wxCommandEvent& event)
{
	Traverse(m_on_menu_id, GroupTreeImpl::EditableVisitor(this));
}

void GroupTreeCtrl::ReorderSprites()
{
	std::vector<ISprite*> sprites;
	Traverse(m_root, GroupTreeImpl::GetSpritesVisitor(this, sprites));
	for (int i = 0, n = sprites.size(); i < n; ++i) {
		ISprite* spr = sprites[i];
		m_remove_open = false;
		m_sprite_impl->removeSprite(spr);
		m_remove_open = true;
		m_sprite_impl->insertSprite(spr);
	}
}

void GroupTreeCtrl::ShowMenu(wxTreeItemId id, const wxPoint& pt)
{
	m_on_menu_id = id;

	wxMenu menu;

	menu.Append(ID_MENU_ADD, wxT("&Add Sprites"));
	Bind(wxEVT_COMMAND_MENU_SELECTED, &GroupTreeCtrl::OnMenuAddSprites, this, ID_MENU_ADD);

	menu.Append(ID_MENU_CLEAR, wxT("&Clear Sprites"));
	Bind(wxEVT_COMMAND_MENU_SELECTED, &GroupTreeCtrl::OnMenuClear, this, ID_MENU_CLEAR);

	menu.AppendSeparator();

	menu.AppendCheckItem(ID_MENU_VISIBLE, wxT("&Visible"));
	Bind(wxEVT_COMMAND_MENU_SELECTED, &GroupTreeCtrl::OnMenuVisible, this, ID_MENU_VISIBLE);

	menu.AppendCheckItem(ID_MENU_EDITABLE, wxT("&Editable"));
	Bind(wxEVT_COMMAND_MENU_SELECTED, &GroupTreeCtrl::OnMenuEditable, this, ID_MENU_EDITABLE);

	PopupMenu(&menu, pt);
}

void GroupTreeCtrl::Traverse(wxTreeItemId id, IGroupTreeVisitor& visitor) const
{
	std::queue<wxTreeItemId> buf;
	buf.push(id);
	while (!buf.empty()) {
		wxTreeItemId item = buf.front(); buf.pop();

		wxTreeItemIdValue cookie;
		wxTreeItemId id = GetFirstChild(item, cookie);
		if (id.IsOk()) {
			if (item != id) {
				visitor.VisitNonleaf(item);
			}

			while (id.IsOk()) {
				buf.push(id);
				id = GetNextSibling(id);
			}
		} else {
			visitor.VisitLeaf(item);
		}
	}
}

}<commit_msg>[FIXED] Group里高层（新建的层）在上面<commit_after>#include "GroupTreeCtrl.h"
#include "MultiSpritesImpl.h"
#include "GroupTreeImpl.h"
#include "GroupTreeIO.h"

#include "dataset/Group.h"
#include "dataset/ISprite.h"

#include <sstream>
#include <queue>
#include <wx/menu.h>

namespace d2d
{

BEGIN_EVENT_TABLE(GroupTreeCtrl, wxTreeCtrl)
	EVT_TREE_ITEM_RIGHT_CLICK(ID_GROUP_TREE_CTRL, GroupTreeCtrl::OnItemRClick)
	EVT_TREE_ITEM_MENU(ID_GROUP_TREE_CTRL, GroupTreeCtrl::OnItemMenu)
	EVT_TREE_ITEM_ACTIVATED(ID_GROUP_TREE_CTRL, GroupTreeCtrl::OnItemActivated)
	EVT_TREE_BEGIN_DRAG(ID_GROUP_TREE_CTRL, GroupTreeCtrl::OnBeginDrag)
	EVT_TREE_END_DRAG(ID_GROUP_TREE_CTRL, GroupTreeCtrl::OnEndDrag)
END_EVENT_TABLE()

GroupTreeCtrl::GroupTreeCtrl(wxWindow* parent, MultiSpritesImpl* sprite_impl)
	: wxTreeCtrl(parent, ID_GROUP_TREE_CTRL, wxDefaultPosition, wxDefaultSize,
	wxTR_EDIT_LABELS | wxTR_HIDE_ROOT)
	, m_sprite_impl(sprite_impl)
	, m_remove_open(true)
{
	m_root = AddRoot("Root");
}

void GroupTreeCtrl::StoreToFile(Json::Value& value) const
{
	Traverse(GroupTreeImpl::StoreVisitor(this, value));
}

void GroupTreeCtrl::LoadFromFile(const Json::Value& value)
{
	GroupTreeIO io(this, m_sprite_impl);
	io.Load(value);
}

void GroupTreeCtrl::Traverse(IGroupTreeVisitor& visitor) const
{
	Traverse(m_root, visitor);
}

wxTreeItemId GroupTreeCtrl::AddNode()
{
	static int s_num = 0;

	std::ostringstream ss;
	ss << "Group" << s_num++;
	std::string text = ss.str();

	return AddNode(text);
}

wxTreeItemId GroupTreeCtrl::AddNode(const std::string& name)
{
	GroupTreeItem* data = new GroupTreeItem(new Group(name));

	wxTreeItemId id = GetFocusedItem();
	if (id.IsOk()) {
		data->SetId(id);
		return AddNode(id, name, data);
	} else {
		data->SetId(m_root);
		return AddNode(m_root, name, data);
	}
}

wxTreeItemId GroupTreeCtrl::AddNode(const std::string& name, wxTreeItemId parent)
{
	GroupTreeItem* data = new GroupTreeItem(new Group(name));
	return AddNode(parent, name, data);
}

void GroupTreeCtrl::DelNode()
{
	wxTreeItemId id = GetFocusedItem();
	if (id.IsOk()) {
		Delete(id);
	}
}

wxTreeItemId GroupTreeCtrl::AddSprite(wxTreeItemId parent, d2d::ISprite* spr)
{
	if (!parent.IsOk()) {
		return m_root;
	}

	GroupTreeItem* data = (GroupTreeItem*)GetItemData(parent);
	if (!data) {
		return m_root;
	}

	Group* group = data->m_group;
	if (!group) {
		return m_root;
	}

	bool ok = group->Insert(spr);
	if (ok) {
		GroupTreeItem* data = new GroupTreeItem(spr);
		return AddNode(parent, spr->name, data);
	} else {
		return m_root;
	}
}

void GroupTreeCtrl::Clear()
{
	if (!IsEmpty()) {
		CollapseAndReset(m_root);
	}
}

void GroupTreeCtrl::Remove(ISprite* sprite)
{
	if (m_remove_open) {
		Traverse(GroupTreeImpl::RemoveVisitor(this, sprite));
	}
}

void GroupTreeCtrl::Visible(wxTreeItemId id, bool visible)
{
	Traverse(id, GroupTreeImpl::SetVisibleVisitor(this, visible));
}

void GroupTreeCtrl::Editable(wxTreeItemId id, bool editable)
{
	Traverse(id, GroupTreeImpl::SetEditableVisitor(this, editable));
}

wxTreeItemId GroupTreeCtrl::AddNode(wxTreeItemId parent, const std::string& name, GroupTreeItem* data)
{
	wxTreeItemId id = InsertItem(parent, 0, name, -1, -1, data);
	ExpandAll();
	return id;
}

void GroupTreeCtrl::OnItemRClick(wxTreeEvent& event)
{
	wxTreeItemId itemId = event.GetItem();

	GroupTreeItem* item = (GroupTreeItem*)GetItemData(itemId);

	event.Skip();
}

void GroupTreeCtrl::OnItemMenu(wxTreeEvent& event)
{
	wxTreeItemId id = event.GetItem();
	if (!id.IsOk()) {
		return;
	}

	wxPoint clientpt = event.GetPoint();
	wxPoint screenpt = ClientToScreen(clientpt);
	ShowMenu(id, clientpt);
	event.Skip();
}

void GroupTreeCtrl::OnItemActivated(wxTreeEvent& event)
{
	wxTreeItemId id = event.GetItem();
	SpriteSelection* selection = m_sprite_impl->getSpriteSelection();
	selection->Clear();
	Traverse(id, GroupTreeImpl::SelectVisitor(this, selection));
}

void GroupTreeCtrl::OnBeginDrag(wxTreeEvent& event)
{
	m_dragged_item = event.GetItem();
	event.Allow();
}

void GroupTreeCtrl::OnEndDrag(wxTreeEvent& event)
{
	wxTreeItemId item_src = m_dragged_item,
		item_dst = event.GetItem();
	if (!item_dst.IsOk()) {
		return;
	}

	wxLogDebug("Drag from %s to %s", GetItemText(item_src), GetItemText(item_dst));

	// old info
	GroupTreeItem* data = (GroupTreeItem*)GetItemData(item_src);
	std::string name = GetItemText(item_src);
	// insert
	wxTreeItemId new_item = InsertItem(item_dst, 0, name, -1, -1, data->Clone());
	ExpandAll();
	// copy older's children
	Traverse(item_src, GroupTreeImpl::CopyPasteVisitor(this, item_src, new_item));
	// remove
	Delete(item_src);
	// sort
	ReorderSprites();
}

void GroupTreeCtrl::OnMenuAddSprites(wxCommandEvent& event)
{
	if (!m_on_menu_id.IsOk()) {
		return;
	}

	GroupTreeItem* data = (GroupTreeItem*)GetItemData(m_on_menu_id);
	if (!data) {
		return;
	}

	Group* group = data->m_group;
	if (!group) {
		return;
	}

	SpriteSelection* selection = m_sprite_impl->getSpriteSelection();
	std::vector<ISprite*> sprites;
	selection->Traverse(FetchAllVisitor<ISprite>(sprites));
	for (int i = 0, n = sprites.size(); i < n; ++i) {
		ISprite* spr = sprites[i];
		bool ok = group->Insert(spr);
		if (ok) {
			GroupTreeItem* data = new GroupTreeItem(spr);
			AddNode(m_on_menu_id, spr->name, data);
		}
	}
}

void GroupTreeCtrl::OnMenuClear(wxCommandEvent& event)
{
	if (!m_on_menu_id.IsOk()) {
		return;
	}

	Group* group = ((GroupTreeItem*)GetItemData(m_on_menu_id))->m_group;
	if (!group) {
		return;
	}

	group->Clear();
	CollapseAndReset(m_on_menu_id);
}

void GroupTreeCtrl::OnMenuVisible(wxCommandEvent& event)
{
	Traverse(m_on_menu_id, GroupTreeImpl::VisibleVisitor(this));
}

void GroupTreeCtrl::OnMenuEditable(wxCommandEvent& event)
{
	Traverse(m_on_menu_id, GroupTreeImpl::EditableVisitor(this));
}

void GroupTreeCtrl::ReorderSprites()
{
	std::vector<ISprite*> sprites;
	Traverse(m_root, GroupTreeImpl::GetSpritesVisitor(this, sprites));
	for (int i = 0, n = sprites.size(); i < n; ++i) {
		ISprite* spr = sprites[i];
		m_remove_open = false;
		m_sprite_impl->removeSprite(spr);
		m_remove_open = true;
		m_sprite_impl->insertSprite(spr);
	}
}

void GroupTreeCtrl::ShowMenu(wxTreeItemId id, const wxPoint& pt)
{
	m_on_menu_id = id;

	wxMenu menu;

	menu.Append(ID_MENU_ADD, wxT("&Add Sprites"));
	Bind(wxEVT_COMMAND_MENU_SELECTED, &GroupTreeCtrl::OnMenuAddSprites, this, ID_MENU_ADD);

	menu.Append(ID_MENU_CLEAR, wxT("&Clear Sprites"));
	Bind(wxEVT_COMMAND_MENU_SELECTED, &GroupTreeCtrl::OnMenuClear, this, ID_MENU_CLEAR);

	menu.AppendSeparator();

	menu.AppendCheckItem(ID_MENU_VISIBLE, wxT("&Visible"));
	Bind(wxEVT_COMMAND_MENU_SELECTED, &GroupTreeCtrl::OnMenuVisible, this, ID_MENU_VISIBLE);

	menu.AppendCheckItem(ID_MENU_EDITABLE, wxT("&Editable"));
	Bind(wxEVT_COMMAND_MENU_SELECTED, &GroupTreeCtrl::OnMenuEditable, this, ID_MENU_EDITABLE);

	PopupMenu(&menu, pt);
}

void GroupTreeCtrl::Traverse(wxTreeItemId id, IGroupTreeVisitor& visitor) const
{
	std::queue<wxTreeItemId> buf;
	buf.push(id);
	while (!buf.empty()) {
		wxTreeItemId item = buf.front(); buf.pop();

		wxTreeItemIdValue cookie;
		wxTreeItemId id = GetFirstChild(item, cookie);
		if (id.IsOk()) {
			if (item != id) {
				visitor.VisitNonleaf(item);
			}

			while (id.IsOk()) {
				buf.push(id);
				id = GetNextSibling(id);
			}
		} else {
			visitor.VisitLeaf(item);
		}
	}
}

}<|endoftext|>


<commit_before>#include "stdafx.h"
#include "CommandHack.h"

CommandHack::CommandHack()
{
}

CommandHack::~CommandHack()
{
}

bool CommandHack::ShouldRunThisCommand(ParsedCommand* Parsed)
{
	return (Parsed->Words->at(0) == "hack");
}

void CommandHack::Run(ParsedCommand* Parsed)
{
	Sleep(10000);
	this->Crack();
}

string* CommandHack::GetName()
{
	return new string("Hack");
}

string* CommandHack::GetHelp()
{
	return new string("In 10 seconds, it tries to hack into whatever input box the user is hovering over.");
}

void CommandHack::Attempt(string* attempt)
{
	register char next;
	register unsigned int size = attempt->size();
	register unsigned int i = 0;

	while (i != size)
	{
		next = attempt->at(i);
		ip.type = INPUT_KEYBOARD;
		ip.ki.time = 0;
		ip.ki.dwFlags = KEYEVENTF_UNICODE; // Specify the key as a Unicode character
		ip.ki.wScan = next; // Which key press to simulate
		ip.ki.wVk = 0;
		ip.ki.dwExtraInfo = 0;
		SendInput(1, &ip, sizeof(INPUT));
		ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release1*
		SendInput(1, &ip, sizeof(INPUT));

		++i;
	}
	////Enter
	//ip.type = INPUT_KEYBOARD;
	//ip.ki.time = 0;
	//ip.ki.dwFlags = KEYEVENTF_UNICODE; // Specify the key as a Unicode character
	//ip.ki.wScan = VK_RETURN; // Which key press to simulate
	//ip.ki.wVk = 0;
	//ip.ki.dwExtraInfo = 0;
	//SendInput(1, &ip, sizeof(INPUT));
	//ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release1*
	//SendInput(1, &ip, sizeof(INPUT));

	keybd_event(VK_RETURN, '5A', 0, 0);
	keybd_event(VK_RETURN, '5A', KEYEVENTF_KEYUP, 0);

	register unsigned __int8 ab = -20;

	while (ab != this->Length)
	{
		keybd_event(VK_BACK, '66', 0, 0);
		keybd_event(VK_BACK, '66', KEYEVENTF_KEYUP, 0);
		//ip.type = INPUT_KEYBOARD;
		//ip.ki.time = 0;
		//ip.ki.dwFlags = KEYEVENTF_UNICODE; // Specify the key as a Unicode character
		//ip.ki.wScan = VK_BACK; // Which key press to simulate
		//ip.ki.wVk = 0;
		//ip.ki.dwExtraInfo = 0;
		//SendInput(1, &ip, sizeof(INPUT));
		//ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release1*
		//SendInput(1, &ip, sizeof(INPUT));
		++ab;
	}
}

void CommandHack::Crack()
{
	//32-137
	//Acquire common characters.
	register unsigned __int8 i = 32;
	while (i != 128)
	{
		this->Chars[i - 32] = i;
		++i;
	}

	i = 1;
	string* Attemptter = new string("");
	while (i != 128)
	{
		this->Length = i;
		// Keep growing till I get it right
		this->makeCombinations(Attemptter, i);
		++i;
	}

	ToDelete->push_back(Attemptter);
}
void CommandHack::makeCombinations(string* s, unsigned __int8 length)
{
	if (length == 0) // when length has been reached
	{
		this->Attempt(s); // print it out
		Sleep(100);
		return;
	}
	register string appended;

	for (register unsigned __int8 i = 0; i < 96; i++) // iterate through alphabet
	{
		// Create new string with next character
		// Call generate again until string has reached it's length
		appended = *s + this->Chars[i];
		this->makeCombinations(&appended, length - 1);
	}
}
<commit_msg>Commit.<commit_after>#include "stdafx.h"
#include "CommandHack.h"

CommandHack::CommandHack()
{
}

CommandHack::~CommandHack()
{
}

bool CommandHack::ShouldRunThisCommand(ParsedCommand* Parsed)
{
	return (Parsed->Words->at(0) == "hack");
}

void CommandHack::Run(ParsedCommand* Parsed)
{
	Sleep(10000);
	this->Crack();
}

string* CommandHack::GetName()
{
	return new string("Hack");
}

string* CommandHack::GetHelp()
{
	return new string("In 10 seconds, it tries to hack into whatever input box the user is hovering over.");
}

void CommandHack::Attempt(string* attempt)
{
	Console->WriteLine(attempt);
	register char next;
	register unsigned int size = attempt->size();
	register unsigned int i = 0;

	while (i != size)
	{
		next = attempt->at(i);
		ip.type = INPUT_KEYBOARD;
		ip.ki.time = 0;
		ip.ki.dwFlags = KEYEVENTF_UNICODE; // Specify the key as a Unicode character
		ip.ki.wScan = next; // Which key press to simulate
		ip.ki.wVk = 0;
		ip.ki.dwExtraInfo = 0;
		SendInput(1, &ip, sizeof(INPUT));
		ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release1*
		SendInput(1, &ip, sizeof(INPUT));

		++i;
	}
	////Enter
	//ip.type = INPUT_KEYBOARD;
	//ip.ki.time = 0;
	//ip.ki.dwFlags = KEYEVENTF_UNICODE; // Specify the key as a Unicode character
	//ip.ki.wScan = VK_RETURN; // Which key press to simulate
	//ip.ki.wVk = 0;
	//ip.ki.dwExtraInfo = 0;
	//SendInput(1, &ip, sizeof(INPUT));
	//ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release1*
	//SendInput(1, &ip, sizeof(INPUT));

	keybd_event(VK_RETURN, '5A', 0, 0);
	keybd_event(VK_RETURN, '5A', KEYEVENTF_KEYUP, 0);

	register unsigned __int8 ab = -20;

	while (ab != this->Length)
	{
		keybd_event(VK_BACK, '66', 0, 0);
		keybd_event(VK_BACK, '66', KEYEVENTF_KEYUP, 0);
		//ip.type = INPUT_KEYBOARD;
		//ip.ki.time = 0;
		//ip.ki.dwFlags = KEYEVENTF_UNICODE; // Specify the key as a Unicode character
		//ip.ki.wScan = VK_BACK; // Which key press to simulate
		//ip.ki.wVk = 0;
		//ip.ki.dwExtraInfo = 0;
		//SendInput(1, &ip, sizeof(INPUT));
		//ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release1*
		//SendInput(1, &ip, sizeof(INPUT));
		++ab;
	}
}

void CommandHack::Crack()
{
	//32-137
	//Acquire common characters.
	register unsigned __int8 i = 32;
	while (i != 128)
	{
		this->Chars[i - 32] = i;
		++i;
	}

	i = 1;
	string* Attemptter = new string("");
	while (i != 128)
	{
		this->Length = i;
		// Keep growing till I get it right
		this->makeCombinations(Attemptter, i);
		++i;
	}

	ToDelete->push_back(Attemptter);
}
void CommandHack::makeCombinations(string* s, unsigned __int8 length)
{
	if (length == 0) // when length has been reached
	{
		this->Attempt(s); // print it out
		Sleep(10);
		return;
	}
	register string appended;

	for (register unsigned __int8 i = 0; i < 96; i++) // iterate through alphabet
	{
		// Create new string with next character
		// Call generate again until string has reached it's length
		appended = *s + this->Chars[i];
		this->makeCombinations(&appended, length - 1);
	}
}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2021.  All rights reserved
 */
#ifndef _Stroika_Foundation_Execution_WhenTimeExceeded_inl_
#define _Stroika_Foundation_Execution_WhenTimeExceeded_inl_ 1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */

namespace Stroika::Foundation::Execution {

    /*
     ********************************************************************************
     ************************ Execution::WhenTimeExceeded ***************************
     ********************************************************************************
     */
    inline WhenTimeExceeded::WhenTimeExceeded (Time::DurationSecondsType callIfTakesLongerThan, nullptr_t f)
        : fRunIfTakesTooLong_{nullptr}
    {
    }
    inline WhenTimeExceeded::WhenTimeExceeded (Time::DurationSecondsType callIfTakesLongerThan, const function<void (Time::DurationSecondsType)>& f)
        : fStartedAt_{Time::GetTickCount ()}
        , fCallIfTakesLongerThan_{callIfTakesLongerThan}
        , fRunIfTakesTooLong_{f}
    {
    }
    inline WhenTimeExceeded::~WhenTimeExceeded ()
    {
        if (fRunIfTakesTooLong_ != nullptr) {
            Time::DurationSecondsType timeTaken = Time::GetTickCount () - fStartedAt_;
            if (timeTaken >= fCallIfTakesLongerThan_) {
                IgnoreExceptionsForCall (fRunIfTakesTooLong_ (timeTaken));
            }
        }
    }

}

#endif /*_Stroika_Foundation_Execution_WhenTimeExceeded_inl_*/
<commit_msg> WhenTimeExceeded regression cleanup - warnings and tweaks<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2021.  All rights reserved
 */
#ifndef _Stroika_Foundation_Execution_WhenTimeExceeded_inl_
#define _Stroika_Foundation_Execution_WhenTimeExceeded_inl_ 1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */

namespace Stroika::Foundation::Execution {

    /*
     ********************************************************************************
     ************************ Execution::WhenTimeExceeded ***************************
     ********************************************************************************
     */
    inline WhenTimeExceeded::WhenTimeExceeded ([[maybe_unused]] Time::DurationSecondsType callIfTakesLongerThan, [[maybe_unused]] nullptr_t f)
        : fRunIfTakesTooLong_{nullptr}
    {
    }
    inline WhenTimeExceeded::WhenTimeExceeded (Time::DurationSecondsType callIfTakesLongerThan, const function<void (Time::DurationSecondsType)>& f)
        : fCallIfTakesLongerThan_{callIfTakesLongerThan}
        , fRunIfTakesTooLong_{f}
    {
        if (f != nullptr) {
            fStartedAt_ = Time::GetTickCount ();
        }
    }
    inline WhenTimeExceeded::~WhenTimeExceeded ()
    {
        if (fRunIfTakesTooLong_ != nullptr) {
            Time::DurationSecondsType timeTaken = Time::GetTickCount () - fStartedAt_;
            if (timeTaken >= fCallIfTakesLongerThan_) {
                IgnoreExceptionsForCall (fRunIfTakesTooLong_ (timeTaken));
            }
        }
    }

}

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