<commit_before>/**
 * CFunction
 *
 * Created for Copasi by Stefan Hoops
 * (C) Stefan Hoops 2001
 */

#define COPASI_TRACE_CONSTRUCTION
#include "copasi.h"
#include "CFunctionParameter.h"
#include "CFunctionParameters.h"
#include "CFunction.h"

CFunction::CFunction()
{
  CONSTRUCTOR_TRACE;
  mReversible = TriUnspecified;
}

CFunction::CFunction(const CFunction & src)
{
  CONSTRUCTOR_TRACE;
  mType = src.mType;
  mName = src.mName;
  mDescription = src.mDescription;
  mReversible = src.mReversible;
  mUsageDescriptions = CCopasiVectorNS < CUsageRange > (src.mUsageDescriptions);
  mParameters = CFunctionParameters(src.mParameters);
}

CFunction::~CFunction()
{
  cleanup();
  DESTRUCTOR_TRACE;
}

void CFunction::cleanup()
{
  mUsageDescriptions.cleanup();
  mParameters.cleanup();
}

void CFunction::load(CReadConfig & configBuffer,
                     CReadConfig::Mode mode)
{
  cleanup();

  if (configBuffer.getVersion() < "4")
    {
      C_INT32 Type;
      CUsageRange UsageDescription;

      mode = CReadConfig::SEARCH;
      configBuffer.getVariable("User-defined", "C_INT32", &Type, mode);

      switch (Type)
        {
        case 1:
          mType = CFunction::UserDefined;
          break;

        default:
          fatalError();
        }

      configBuffer.getVariable("Reversible", "C_INT32", &mReversible);

      configBuffer.getVariable("Substrates", "C_INT32", &Type);
      UsageDescription.setUsage("SUBSTRATES");
      UsageDescription.setLow(Type);
      mUsageDescriptions.add(UsageDescription);

      configBuffer.getVariable("Products", "C_INT32", &Type);
      UsageDescription.setUsage("PRODUCTS");
      UsageDescription.setLow(Type);
      mUsageDescriptions.add(UsageDescription);

      mode = CReadConfig::SEARCH;
    }
  else
    {
      configBuffer.getVariable("FunctionType", "C_INT32", &mType, mode);
      mode = CReadConfig::NEXT;
    }

  configBuffer.getVariable("FunctionName", "string", &mName, mode);
  configBuffer.getVariable("Description", "string", &mDescription);

  if (configBuffer.getVersion() >= "4")
    {
      unsigned C_INT32 Size;
      configBuffer.getVariable("Reversible", "C_INT32", &mReversible);
      configBuffer.getVariable("UsageDescriptionSize", "C_INT32", &Size);
      mUsageDescriptions.load(configBuffer, Size);
      mParameters.load(configBuffer);
    }

  // For older file version the parameters have to be build from information
  // dependend on the function type. Luckilly, only user defined functions are
  // the only ones occuring in those files.
}

void CFunction::save(CWriteConfig & configBuffer)
{
  configBuffer.setVariable("FunctionType", "C_INT32", &mType);
  configBuffer.setVariable("FunctionName", "string", &mName);
  configBuffer.setVariable("Description", "string", &mDescription);
  configBuffer.setVariable("Reversible", "C_INT32", &mReversible);

  unsigned C_INT32 Size = mUsageDescriptions.size();
  configBuffer.setVariable("UsageDescriptionSize", "C_INT32", &Size);
  mUsageDescriptions.save(configBuffer);
  mParameters.save(configBuffer);
}

void CFunction::saveOld(CWriteConfig & configBuffer)
{
  C_INT32 dummy, i, sizem, sizep;
  unsigned C_INT32 pos;
  string tmpstr1, tmpstr2;

  if (mType == UserDefined)
    dummy = 1;
  else
    dummy = 0;
  configBuffer.setVariable("UDKType", "string", &mName);
  configBuffer.setVariable("User-defined", "C_INT32", &dummy);
  configBuffer.setVariable("Reversible", "C_INT32", &mReversible);
  dummy = mUsageDescriptions["SUBSTRATES"]->getLow();
  configBuffer.setVariable("Substrates", "C_INT32", &dummy);
  dummy = mUsageDescriptions["PRODUCTS"]->getLow();
  configBuffer.setVariable("Products", "C_INT32", &dummy);
  sizem = mParameters.getUsageRanges()["MODIFIER"]->getLow();
  configBuffer.setVariable("Modifiers", "C_INT32", &sizem);
  sizep = mParameters.getUsageRanges()["PARAMETER"]->getLow();
  configBuffer.setVariable("Constants", "C_INT32", &sizep);
  for (i = 0, pos = 0; i < sizem; i++)
    {
      tmpstr1 = mParameters.getParameterByUsage("MODIFIER", pos).getName();
      tmpstr2 = StringPrint("Modifier%d", i);
      configBuffer.setVariable(tmpstr2, "string", &tmpstr1);
    }
  for (i = 0, pos = 0; i < sizep; i++)
    {
      tmpstr1 = mParameters.getParameterByUsage("PARAMETER", pos).getName();
      tmpstr2 = StringPrint("Paramter%d", i);
      configBuffer.setVariable(tmpstr2, "string", &tmpstr1);
    }
  configBuffer.setVariable("FunctionName", "string", &mName);
  configBuffer.setVariable("Description", "string", &mDescription);

  //  unsigned C_INT32 Size = mUsageDescriptions.size();
  //  configBuffer.setVariable("UsageDescriptionSize", "C_INT32", &Size);
  //  mUsageDescriptions.save(configBuffer);
  //  mParameters.save(configBuffer);
}

void CFunction::setName(const string& name)
{
  mName = name;
}

const string & CFunction::getName() const
  {
    return mName;
  }

void CFunction::setDescription(const string & description)
{
  mDescription = description;
}

const string & CFunction::getDescription() const
  {
    return mDescription;
  }

void CFunction::setType(const CFunction::Type & type)
{
  mType = type;
}

const CFunction::Type & CFunction::getType() const
  {
    return mType;
  }

void CFunction::setReversible(const TriLogic & reversible)
{
  mReversible = reversible;
}

const TriLogic & CFunction::isReversible() const
  {
    return mReversible;
  }

CFunctionParameters & CFunction::getParameters()
{
  return mParameters;
}

CCopasiVectorNS < CUsageRange > & CFunction::getUsageDescriptions()
{
  return mUsageDescriptions;
}

unsigned C_INT32 CFunction::getParameterPosition(const string & name)
{
  return mParameters[0] - mParameters[name];
}

C_FLOAT64 CFunction::calcValue(const CCallParameters & callParameters) const
  {
    return 0.0;
  }

void CFunction::addUsage(const string& usage, C_INT32 low, C_INT32 high)
{
  CUsageRange *u;
  u = new CUsageRange();
  u->setUsage(usage);
  u->setLow(low);
  u->setHigh(high);
  mUsageDescriptions.add(u);
}

void CFunction::addParameter(const string & name, const CFunctionParameter::DataType & type,
                             const string & usage)
{
  mParameters.add(name, type, usage);
}
<commit_msg>fixed a bug in saveOld()<commit_after>/**
 * CFunction
 *
 * Created for Copasi by Stefan Hoops
 * (C) Stefan Hoops 2001
 */

#define COPASI_TRACE_CONSTRUCTION
#include "copasi.h"
#include "CFunctionParameter.h"
#include "CFunctionParameters.h"
#include "CFunction.h"

CFunction::CFunction()
{
  CONSTRUCTOR_TRACE;
  mReversible = TriUnspecified;
}

CFunction::CFunction(const CFunction & src)
{
  CONSTRUCTOR_TRACE;
  mType = src.mType;
  mName = src.mName;
  mDescription = src.mDescription;
  mReversible = src.mReversible;
  mUsageDescriptions = CCopasiVectorNS < CUsageRange > (src.mUsageDescriptions);
  mParameters = CFunctionParameters(src.mParameters);
}

CFunction::~CFunction()
{
  cleanup();
  DESTRUCTOR_TRACE;
}

void CFunction::cleanup()
{
  mUsageDescriptions.cleanup();
  mParameters.cleanup();
}

void CFunction::load(CReadConfig & configBuffer,
                     CReadConfig::Mode mode)
{
  cleanup();

  if (configBuffer.getVersion() < "4")
    {
      C_INT32 Type;
      CUsageRange UsageDescription;

      mode = CReadConfig::SEARCH;
      configBuffer.getVariable("User-defined", "C_INT32", &Type, mode);

      switch (Type)
        {
        case 1:
          mType = CFunction::UserDefined;
          break;

        default:
          fatalError();
        }

      configBuffer.getVariable("Reversible", "C_INT32", &mReversible);

      configBuffer.getVariable("Substrates", "C_INT32", &Type);
      UsageDescription.setUsage("SUBSTRATES");
      UsageDescription.setLow(Type);
      mUsageDescriptions.add(UsageDescription);

      configBuffer.getVariable("Products", "C_INT32", &Type);
      UsageDescription.setUsage("PRODUCTS");
      UsageDescription.setLow(Type);
      mUsageDescriptions.add(UsageDescription);

      mode = CReadConfig::SEARCH;
    }
  else
    {
      configBuffer.getVariable("FunctionType", "C_INT32", &mType, mode);
      mode = CReadConfig::NEXT;
    }

  configBuffer.getVariable("FunctionName", "string", &mName, mode);
  configBuffer.getVariable("Description", "string", &mDescription);

  if (configBuffer.getVersion() >= "4")
    {
      unsigned C_INT32 Size;
      configBuffer.getVariable("Reversible", "C_INT32", &mReversible);
      configBuffer.getVariable("UsageDescriptionSize", "C_INT32", &Size);
      mUsageDescriptions.load(configBuffer, Size);
      mParameters.load(configBuffer);
    }

  // For older file version the parameters have to be build from information
  // dependend on the function type. Luckilly, only user defined functions are
  // the only ones occuring in those files.
}

void CFunction::save(CWriteConfig & configBuffer)
{
  configBuffer.setVariable("FunctionType", "C_INT32", &mType);
  configBuffer.setVariable("FunctionName", "string", &mName);
  configBuffer.setVariable("Description", "string", &mDescription);
  configBuffer.setVariable("Reversible", "C_INT32", &mReversible);

  unsigned C_INT32 Size = mUsageDescriptions.size();
  configBuffer.setVariable("UsageDescriptionSize", "C_INT32", &Size);
  mUsageDescriptions.save(configBuffer);
  mParameters.save(configBuffer);
}

void CFunction::saveOld(CWriteConfig & configBuffer)
{
  C_INT32 dummy, i, sizem, sizep;
  unsigned C_INT32 pos;
  string tmpstr1, tmpstr2;
  CCopasiVectorNS < CUsageRange > tmpusage;

  if (mType == UserDefined)
    dummy = 1;
  else
    dummy = 0;
  configBuffer.setVariable("UDKType", "string", &mName);
  configBuffer.setVariable("User-defined", "C_INT32", &dummy);
  configBuffer.setVariable("Reversible", "C_INT32", &mReversible);
  dummy = mUsageDescriptions["SUBSTRATES"]->getLow();
  configBuffer.setVariable("Substrates", "C_INT32", &dummy);
  dummy = mUsageDescriptions["PRODUCTS"]->getLow();
  configBuffer.setVariable("Products", "C_INT32", &dummy);
  tmpusage = mParameters.getUsageRanges();
  i = tmpusage.getIndex("MODIFIER");
  if (i == -1)
    sizem = 0;
  else
    sizem = tmpusage[i]->getLow();
  configBuffer.setVariable("Modifiers", "C_INT32", &sizem);
  sizep = mParameters.getUsageRanges()["PARAMETER"]->getLow();
  configBuffer.setVariable("Constants", "C_INT32", &sizep);
  for (i = 0, pos = 0; i < sizem; i++)
    {
      tmpstr1 = mParameters.getParameterByUsage("MODIFIER", pos).getName();
      tmpstr2 = StringPrint("Modifier%d", i);
      configBuffer.setVariable(tmpstr2, "string", &tmpstr1);
    }
  for (i = 0, pos = 0; i < sizep; i++)
    {
      tmpstr1 = mParameters.getParameterByUsage("PARAMETER", pos).getName();
      tmpstr2 = StringPrint("Paramter%d", i);
      configBuffer.setVariable(tmpstr2, "string", &tmpstr1);
    }
  configBuffer.setVariable("FunctionName", "string", &mName);
  configBuffer.setVariable("Description", "string", &mDescription);

  //  unsigned C_INT32 Size = mUsageDescriptions.size();
  //  configBuffer.setVariable("UsageDescriptionSize", "C_INT32", &Size);
  //  mUsageDescriptions.save(configBuffer);
  //  mParameters.save(configBuffer);
}

void CFunction::setName(const string& name)
{
  mName = name;
}

const string & CFunction::getName() const
  {
    return mName;
  }

void CFunction::setDescription(const string & description)
{
  mDescription = description;
}

const string & CFunction::getDescription() const
  {
    return mDescription;
  }

void CFunction::setType(const CFunction::Type & type)
{
  mType = type;
}

const CFunction::Type & CFunction::getType() const
  {
    return mType;
  }

void CFunction::setReversible(const TriLogic & reversible)
{
  mReversible = reversible;
}

const TriLogic & CFunction::isReversible() const
  {
    return mReversible;
  }

CFunctionParameters & CFunction::getParameters()
{
  return mParameters;
}

CCopasiVectorNS < CUsageRange > & CFunction::getUsageDescriptions()
{
  return mUsageDescriptions;
}

unsigned C_INT32 CFunction::getParameterPosition(const string & name)
{
  return mParameters[0] - mParameters[name];
}

C_FLOAT64 CFunction::calcValue(const CCallParameters & callParameters) const
  {
    return 0.0;
  }

void CFunction::addUsage(const string& usage, C_INT32 low, C_INT32 high)
{
  CUsageRange *u;
  u = new CUsageRange();
  u->setUsage(usage);
  u->setLow(low);
  u->setHigh(high);
  mUsageDescriptions.add(u);
}

void CFunction::addParameter(const string & name, const CFunctionParameter::DataType & type,
                             const string & usage)
{
  mParameters.add(name, type, usage);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: postit.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2008-02-19 13:34:29 $
 *
 *  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 _POSTIT_HXX
#define _POSTIT_HXX

#ifndef _WINDOW_HXX
#include <vcl/window.hxx>
#endif

#ifndef _SDR_OVERLAY_OVERLAYOBJECT_HXX
#include <svx/sdr/overlay/overlayobject.hxx>
#endif

//TODO: move to cxx
// does not work with forward declaration, why??
#ifndef _LINEINFO_HXX
#include <vcl/lineinfo.hxx>
#endif

#ifndef _BGFX_POLYGON_B2DPOLYGON_HXX
#include <basegfx/polygon/b2dpolygon.hxx>
#endif

class SwPostItMgr;
class SwPostItField;
class SwFmtFld;
class OutlinerView;
class Outliner;
class ScrollBar;
class SwEditWin;
class SwView;
class SwPostIt;
class Edit;
class MultiLineEdit;
class SwRect;
class PopupMenu;

class SwPostItAnkor: public sdr::overlay::OverlayObjectWithBasePosition
{
    protected:
        /*                        6------------7
             1                   /
            /4\ ---------------5
           2 - 3
        */

        basegfx::B2DPoint                       maSecondPosition;
        basegfx::B2DPoint                       maThirdPosition;
        basegfx::B2DPoint                       maFourthPosition;
        basegfx::B2DPoint                       maFifthPosition;
        basegfx::B2DPoint                       maSixthPosition;
        basegfx::B2DPoint                       maSeventhPosition;

    private:
        // object's geometry
        basegfx::B2DPolygon                     maTriangle;
        basegfx::B2DPolygon                     maLine;
        basegfx::B2DPolygon                     maLineTop;
        LineInfo                                mLineInfo;
        unsigned long                           mHeight;
        bool                                    mbShadowedEffect;
    protected:
        // helpers to fill and reset geometry
        void implEnsureGeometry();
        void implResetGeometry();

        // helpers to paint geometry
        void implDrawGeometry(OutputDevice& rOutputDevice, Color aColor, double fOffX, double fOffY);
        Color implBlendColor(const Color aOriginal, sal_Int16 nChange);

        virtual void drawGeometry(OutputDevice& rOutputDevice);
        virtual void createBaseRange(OutputDevice& rOutputDevice);

    public:
        SwPostItAnkor(const basegfx::B2DPoint& rBasePos,
                        const basegfx::B2DPoint& rSecondPos,
                        const basegfx::B2DPoint& rThirdPos,
                        const basegfx::B2DPoint& rFourthPos,
                        const basegfx::B2DPoint& rFifthPos,
                        const basegfx::B2DPoint& rSixthPos,
                        const basegfx::B2DPoint& rSeventhPos,
                        Color aBaseColor,
                        const LineInfo &aLineInfo,
                        bool bShadowedEffect);
        virtual ~SwPostItAnkor();

        const basegfx::B2DPoint& GetSecondPosition() const { return maSecondPosition; }
        const basegfx::B2DPoint& GetThirdPosition() const { return maThirdPosition; }
        const basegfx::B2DPoint& GetFourthPosition() const { return maFourthPosition; }
        const basegfx::B2DPoint& GetFifthPosition() const { return maFifthPosition; }
        const basegfx::B2DPoint& GetSixthPosition() const { return maSixthPosition; }
        const basegfx::B2DPoint& GetSeventhPosition() const { return maSeventhPosition; }

        void SetAllPosition(const basegfx::B2DPoint& rPoint1, const basegfx::B2DPoint& rPoint2, const basegfx::B2DPoint& rPoint3,
            const basegfx::B2DPoint& rPoint4, const basegfx::B2DPoint& rPoint5, const basegfx::B2DPoint& rPoint6, const basegfx::B2DPoint& rPoint7);
        void SetColorLineInfo(Color aBaseColor,const LineInfo& aLineInfo);
        void SetSecondPosition(const basegfx::B2DPoint& rNew);
        void SetThirdPosition(const basegfx::B2DPoint& rNew);
        void SetFourthPosition(const basegfx::B2DPoint& rNew);
        void SetFifthPosition(const basegfx::B2DPoint& rNew);
        void SetSixthPosition(const basegfx::B2DPoint& rNew);
        void SetSeventhPosition(const basegfx::B2DPoint& rNew);

        void SetLineInfo(const LineInfo &aLineInfo);

        void SetHeight(const unsigned long aHeight) {mHeight = aHeight;};

        bool getShadowedEffect() const { return mbShadowedEffect; }
        void setShadowedEffect(bool bNew);

        //sal_Bool isHit(const basegfx::B2DPoint& rPos, double fTol) const;
        // transform object coordinates. Transforms maBasePosition
        // and invalidates on change
        virtual void transform(const basegfx::B2DHomMatrix& rMatrix);
};

class PostItTxt : public Window
{
    private:
        OutlinerView*   mpOutlinerView;
        SwPostIt*       mpPostIt;

        Color           mColorDark;
        Color           mColorLight;
        bool            mMouseOver;
        BOOL            mbShowPopup;

    protected:
        virtual void    Paint( const Rectangle& rRect);
        virtual void    KeyInput( const KeyEvent& rKeyEvt );
        virtual void    MouseMove( const MouseEvent& rMEvt );
        virtual void    MouseButtonDown( const MouseEvent& rMEvt );
        virtual void    MouseButtonUp( const MouseEvent& rMEvt );
        virtual void    Command( const CommandEvent& rCEvt );
        virtual void    DataChanged( const DataChangedEvent& aData);
        virtual void    LoseFocus();
    public:
        virtual void    GetFocus();
        void            SetColor(Color &aColorDark,Color &aColorLight);

    public:
            PostItTxt(Window* pParent, WinBits nBits);
            ~PostItTxt();

            void    SetTextView( OutlinerView* aEditView ) {    mpOutlinerView = aEditView; }
            DECL_LINK( WindowEventListener, VclSimpleEvent* );
};

class SwPostIt : public Window
{
    private:
        SwView*         mpView;
        sdr::overlay::OverlayManager* pOverlayManager;
        OutlinerView*   mpOutlinerView;
        Outliner*       mpOutliner;
        PostItTxt*      mpPostItTxt;
        MultiLineEdit*  mpMeta;
        ScrollBar*      mpVScrollbar;
        SwFmtFld*       mpFmtFld;
        SwPostItField*  mpFld;
        SwPostItAnkor*  mpAnkor;
        SwPostItMgr*    mpMgr;
        bool            mbMeta;
        bool            mbReadonly;
        Color           mColorAnkor;
        Color           mColorDark;
        Color           mColorLight;
        basegfx::B2DPolygon aPopupTriangle;
        Rectangle       mRectMetaButton;
        PopupMenu*      mpButtonPopup;
        sal_Int32       mnEventId;
        bool            mbMarginSide;

    protected:

        virtual void    DataChanged( const DataChangedEvent& aEvent);
        virtual void    LoseFocus();
        virtual void    MouseButtonDown( const MouseEvent& rMEvt );
        virtual void    Paint( const Rectangle& rRect);
        virtual void    Resize();
        virtual void    GetFocus();

        DECL_LINK(ScrollHdl, ScrollBar*);
        void            InitControls();

    public:
        SwPostIt( Window* pParent, WinBits nBits,SwFmtFld* aField,SwPostItMgr* aMgr,bool bMarginSide);
        ~SwPostIt();

        void    SetSizePixel( const Size& rNewSize );
        void    SetPosSizePixelRect( long nX, long nY,long nWidth, long nHeight,const SwRect &aRect,const long PageBorder, USHORT nFlags = WINDOW_POSSIZE_ALL );
        void    TranslateTopPosition(const long aAmount);

        void    MetaInfo(const bool bMeta);
        void    SetPostItText();

        PostItTxt*      PostItText()    { return mpPostItTxt;}
        ScrollBar*      Scrollbar()     { return mpVScrollbar;}
        SwPostItAnkor*  Ankor()         { return mpAnkor;}
        OutlinerView*   View()          { return mpOutlinerView;}
        SwView*         DocView()       { return mpView;}
        Outliner*       Engine()        { return mpOutliner;}
        SwPostItMgr*    Mgr()           { return mpMgr; }
        SwEditWin*      EditWin();

        long            GetPostItTextHeight();
        void            UpdateData();

        void            SwitchToPostIt(USHORT aDirection);
        void            SwitchToFieldPos(bool bAfter = true);

        void            ExecuteCommand(USHORT aSlot);
        void            Delete(USHORT aType);
        void            Hide(USHORT aType);
        void            DoResize() { Resize(); }

        void            ShowAnkorOnly(const Point &aPoint);
        void            ShowNote();
        void            HideNote();

        void            ResetAttributes();

        void            SetReadonly(BOOL bSet);
        BOOL            IsReadOnly()        { return mbReadonly;}

        void            SetColor(Color &aColorDark,Color &aColorLight, Color &aColorAnkor);
        Color           ColorDark();
        Color           ColorLight();
        Color           ColorAnkor();

        void            Rescale();

        sal_Int32       GetMetaHeight();
        sal_Int32       GetMinimumSizeWithMeta();
        sal_Int32       GetMinimumSizeWithoutMeta();
        sal_Int32       GetMetaButtonAreaWidth();
        sal_Int32       GetScrollbarWidth();

        void            SetSpellChecking(bool bEnable);

        /*
        //void          ClearModifyFlag()   { mpOutliner->SetModified(); }
        //BOOL          IsModified() const  { return mpOutliner->IsModified();}

        void            SetStartLine(USHORT nLine){nStartLine = nLine;}

        virtual void    Command( const CommandEvent& rCEvt );
        void            HandleWheelCommand( const CommandEvent& rCEvt );

        void            SetTextEncoding(rtl_TextEncoding eEncoding);
        */
};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.78); FILE MERGED 2008/04/01 15:56:17 thb 1.2.78.2: #i85898# Stripping all external header guards 2008/03/31 16:52:40 rt 1.2.78.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: postit.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _POSTIT_HXX
#define _POSTIT_HXX

#include <vcl/window.hxx>
#include <svx/sdr/overlay/overlayobject.hxx>

//TODO: move to cxx
// does not work with forward declaration, why??
#ifndef _LINEINFO_HXX
#include <vcl/lineinfo.hxx>
#endif
#include <basegfx/polygon/b2dpolygon.hxx>

class SwPostItMgr;
class SwPostItField;
class SwFmtFld;
class OutlinerView;
class Outliner;
class ScrollBar;
class SwEditWin;
class SwView;
class SwPostIt;
class Edit;
class MultiLineEdit;
class SwRect;
class PopupMenu;

class SwPostItAnkor: public sdr::overlay::OverlayObjectWithBasePosition
{
    protected:
        /*                        6------------7
             1                   /
            /4\ ---------------5
           2 - 3
        */

        basegfx::B2DPoint                       maSecondPosition;
        basegfx::B2DPoint                       maThirdPosition;
        basegfx::B2DPoint                       maFourthPosition;
        basegfx::B2DPoint                       maFifthPosition;
        basegfx::B2DPoint                       maSixthPosition;
        basegfx::B2DPoint                       maSeventhPosition;

    private:
        // object's geometry
        basegfx::B2DPolygon                     maTriangle;
        basegfx::B2DPolygon                     maLine;
        basegfx::B2DPolygon                     maLineTop;
        LineInfo                                mLineInfo;
        unsigned long                           mHeight;
        bool                                    mbShadowedEffect;
    protected:
        // helpers to fill and reset geometry
        void implEnsureGeometry();
        void implResetGeometry();

        // helpers to paint geometry
        void implDrawGeometry(OutputDevice& rOutputDevice, Color aColor, double fOffX, double fOffY);
        Color implBlendColor(const Color aOriginal, sal_Int16 nChange);

        virtual void drawGeometry(OutputDevice& rOutputDevice);
        virtual void createBaseRange(OutputDevice& rOutputDevice);

    public:
        SwPostItAnkor(const basegfx::B2DPoint& rBasePos,
                        const basegfx::B2DPoint& rSecondPos,
                        const basegfx::B2DPoint& rThirdPos,
                        const basegfx::B2DPoint& rFourthPos,
                        const basegfx::B2DPoint& rFifthPos,
                        const basegfx::B2DPoint& rSixthPos,
                        const basegfx::B2DPoint& rSeventhPos,
                        Color aBaseColor,
                        const LineInfo &aLineInfo,
                        bool bShadowedEffect);
        virtual ~SwPostItAnkor();

        const basegfx::B2DPoint& GetSecondPosition() const { return maSecondPosition; }
        const basegfx::B2DPoint& GetThirdPosition() const { return maThirdPosition; }
        const basegfx::B2DPoint& GetFourthPosition() const { return maFourthPosition; }
        const basegfx::B2DPoint& GetFifthPosition() const { return maFifthPosition; }
        const basegfx::B2DPoint& GetSixthPosition() const { return maSixthPosition; }
        const basegfx::B2DPoint& GetSeventhPosition() const { return maSeventhPosition; }

        void SetAllPosition(const basegfx::B2DPoint& rPoint1, const basegfx::B2DPoint& rPoint2, const basegfx::B2DPoint& rPoint3,
            const basegfx::B2DPoint& rPoint4, const basegfx::B2DPoint& rPoint5, const basegfx::B2DPoint& rPoint6, const basegfx::B2DPoint& rPoint7);
        void SetColorLineInfo(Color aBaseColor,const LineInfo& aLineInfo);
        void SetSecondPosition(const basegfx::B2DPoint& rNew);
        void SetThirdPosition(const basegfx::B2DPoint& rNew);
        void SetFourthPosition(const basegfx::B2DPoint& rNew);
        void SetFifthPosition(const basegfx::B2DPoint& rNew);
        void SetSixthPosition(const basegfx::B2DPoint& rNew);
        void SetSeventhPosition(const basegfx::B2DPoint& rNew);

        void SetLineInfo(const LineInfo &aLineInfo);

        void SetHeight(const unsigned long aHeight) {mHeight = aHeight;};

        bool getShadowedEffect() const { return mbShadowedEffect; }
        void setShadowedEffect(bool bNew);

        //sal_Bool isHit(const basegfx::B2DPoint& rPos, double fTol) const;
        // transform object coordinates. Transforms maBasePosition
        // and invalidates on change
        virtual void transform(const basegfx::B2DHomMatrix& rMatrix);
};

class PostItTxt : public Window
{
    private:
        OutlinerView*   mpOutlinerView;
        SwPostIt*       mpPostIt;

        Color           mColorDark;
        Color           mColorLight;
        bool            mMouseOver;
        BOOL            mbShowPopup;

    protected:
        virtual void    Paint( const Rectangle& rRect);
        virtual void    KeyInput( const KeyEvent& rKeyEvt );
        virtual void    MouseMove( const MouseEvent& rMEvt );
        virtual void    MouseButtonDown( const MouseEvent& rMEvt );
        virtual void    MouseButtonUp( const MouseEvent& rMEvt );
        virtual void    Command( const CommandEvent& rCEvt );
        virtual void    DataChanged( const DataChangedEvent& aData);
        virtual void    LoseFocus();
    public:
        virtual void    GetFocus();
        void            SetColor(Color &aColorDark,Color &aColorLight);

    public:
            PostItTxt(Window* pParent, WinBits nBits);
            ~PostItTxt();

            void    SetTextView( OutlinerView* aEditView ) {    mpOutlinerView = aEditView; }
            DECL_LINK( WindowEventListener, VclSimpleEvent* );
};

class SwPostIt : public Window
{
    private:
        SwView*         mpView;
        sdr::overlay::OverlayManager* pOverlayManager;
        OutlinerView*   mpOutlinerView;
        Outliner*       mpOutliner;
        PostItTxt*      mpPostItTxt;
        MultiLineEdit*  mpMeta;
        ScrollBar*      mpVScrollbar;
        SwFmtFld*       mpFmtFld;
        SwPostItField*  mpFld;
        SwPostItAnkor*  mpAnkor;
        SwPostItMgr*    mpMgr;
        bool            mbMeta;
        bool            mbReadonly;
        Color           mColorAnkor;
        Color           mColorDark;
        Color           mColorLight;
        basegfx::B2DPolygon aPopupTriangle;
        Rectangle       mRectMetaButton;
        PopupMenu*      mpButtonPopup;
        sal_Int32       mnEventId;
        bool            mbMarginSide;

    protected:

        virtual void    DataChanged( const DataChangedEvent& aEvent);
        virtual void    LoseFocus();
        virtual void    MouseButtonDown( const MouseEvent& rMEvt );
        virtual void    Paint( const Rectangle& rRect);
        virtual void    Resize();
        virtual void    GetFocus();

        DECL_LINK(ScrollHdl, ScrollBar*);
        void            InitControls();

    public:
        SwPostIt( Window* pParent, WinBits nBits,SwFmtFld* aField,SwPostItMgr* aMgr,bool bMarginSide);
        ~SwPostIt();

        void    SetSizePixel( const Size& rNewSize );
        void    SetPosSizePixelRect( long nX, long nY,long nWidth, long nHeight,const SwRect &aRect,const long PageBorder, USHORT nFlags = WINDOW_POSSIZE_ALL );
        void    TranslateTopPosition(const long aAmount);

        void    MetaInfo(const bool bMeta);
        void    SetPostItText();

        PostItTxt*      PostItText()    { return mpPostItTxt;}
        ScrollBar*      Scrollbar()     { return mpVScrollbar;}
        SwPostItAnkor*  Ankor()         { return mpAnkor;}
        OutlinerView*   View()          { return mpOutlinerView;}
        SwView*         DocView()       { return mpView;}
        Outliner*       Engine()        { return mpOutliner;}
        SwPostItMgr*    Mgr()           { return mpMgr; }
        SwEditWin*      EditWin();

        long            GetPostItTextHeight();
        void            UpdateData();

        void            SwitchToPostIt(USHORT aDirection);
        void            SwitchToFieldPos(bool bAfter = true);

        void            ExecuteCommand(USHORT aSlot);
        void            Delete(USHORT aType);
        void            Hide(USHORT aType);
        void            DoResize() { Resize(); }

        void            ShowAnkorOnly(const Point &aPoint);
        void            ShowNote();
        void            HideNote();

        void            ResetAttributes();

        void            SetReadonly(BOOL bSet);
        BOOL            IsReadOnly()        { return mbReadonly;}

        void            SetColor(Color &aColorDark,Color &aColorLight, Color &aColorAnkor);
        Color           ColorDark();
        Color           ColorLight();
        Color           ColorAnkor();

        void            Rescale();

        sal_Int32       GetMetaHeight();
        sal_Int32       GetMinimumSizeWithMeta();
        sal_Int32       GetMinimumSizeWithoutMeta();
        sal_Int32       GetMetaButtonAreaWidth();
        sal_Int32       GetScrollbarWidth();

        void            SetSpellChecking(bool bEnable);

        /*
        //void          ClearModifyFlag()   { mpOutliner->SetModified(); }
        //BOOL          IsModified() const  { return mpOutliner->IsModified();}

        void            SetStartLine(USHORT nLine){nStartLine = nLine;}

        virtual void    Command( const CommandEvent& rCEvt );
        void            HandleWheelCommand( const CommandEvent& rCEvt );

        void            SetTextEncoding(rtl_TextEncoding eEncoding);
        */
};

#endif
<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2013-2014 winlin

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

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

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

#ifndef SRS_CORE_HPP
#define SRS_CORE_HPP

/*
#include <srs_core.hpp>
*/

/**
* the core provides the common defined macros, utilities,
* user must include the srs_core.hpp before any header, or maybe
* build failed.
*/

// for int64_t print using PRId64 format.
#ifndef __STDC_FORMAT_MACROS
    #define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>

#include <assert.h>
#define srs_assert(expression) assert(expression)

#include <stddef.h>
#include <sys/types.h>

#include <st.h>

// generated by configure.
#include <srs_auto_headers.hpp>

// free the p and set to NULL.
// p must be a T*.
#define srs_freep(p) \
	if (p) { \
		delete p; \
		p = NULL; \
	} \
	(void)0
// free the p which represents a array
#define srs_freepa(p) \
	if (p) { \
		delete[] p; \
		p = NULL; \
	} \
	(void)0

// current release version
#define RTMP_SIG_SRS_VERSION "0.9.0"
// server info.
#define RTMP_SIG_SRS_KEY "srs"
#define RTMP_SIG_SRS_ROLE "origin server"
#define RTMP_SIG_SRS_NAME RTMP_SIG_SRS_KEY"(simple rtmp server)"
#define RTMP_SIG_SRS_URL "https://"RTMP_SIG_SRS_URL_SHORT
#define RTMP_SIG_SRS_URL_SHORT "github.com/winlinvip/simple-rtmp-server"
#define RTMP_SIG_SRS_WEB "http://blog.csdn.net/win_lin"
#define RTMP_SIG_SRS_EMAIL "winlin@vip.126.com"
#define RTMP_SIG_SRS_LICENSE "The MIT License (MIT)"
#define RTMP_SIG_SRS_COPYRIGHT "Copyright (c) 2013-2014 winlin"
#define RTMP_SIG_SRS_PRIMARY_AUTHROS "winlin,wenjiegit"

// compare
#define srs_min(a, b) (((a) < (b))? (a) : (b))
#define srs_max(a, b) (((a) < (b))? (b) : (a))

// get current system time in ms, use cache to avoid performance problem
extern int64_t srs_get_system_time_ms();
// the deamon st-thread will update it.
extern void srs_update_system_time_ms();

// signal defines.
#define SIGNAL_RELOAD SIGHUP

#include <string>
// replace utility
extern std::string srs_replace(std::string str, std::string old_str, std::string new_str);
// dns resolve utility, return the resolved ip address.
extern std::string srs_dns_resolve(std::string host);
// resolve the vhost in query string
// @param app, may contains the vhost in query string format:
// 		app?vhost=request_vhost
//		app...vhost...request_vhost
extern void srs_vhost_resolve(std::string& vhost, std::string& app);

// close the netfd, and close the underlayer fd.
extern void srs_close_stfd(st_netfd_t& stfd);

/**
* disable copy constructor of class
*/
#define disable_default_copy(className)\
    private:\
        /** \
        * disable the copy constructor and operator=, donot allow directly copy. \
        */ \
        className(const className&); \
        className& operator= (const className&)

#endif<commit_msg>change version to 0.9.1<commit_after>/*
The MIT License (MIT)

Copyright (c) 2013-2014 winlin

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

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

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

#ifndef SRS_CORE_HPP
#define SRS_CORE_HPP

/*
#include <srs_core.hpp>
*/

/**
* the core provides the common defined macros, utilities,
* user must include the srs_core.hpp before any header, or maybe
* build failed.
*/

// for int64_t print using PRId64 format.
#ifndef __STDC_FORMAT_MACROS
    #define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>

#include <assert.h>
#define srs_assert(expression) assert(expression)

#include <stddef.h>
#include <sys/types.h>

#include <st.h>

// generated by configure.
#include <srs_auto_headers.hpp>

// free the p and set to NULL.
// p must be a T*.
#define srs_freep(p) \
	if (p) { \
		delete p; \
		p = NULL; \
	} \
	(void)0
// free the p which represents a array
#define srs_freepa(p) \
	if (p) { \
		delete[] p; \
		p = NULL; \
	} \
	(void)0

// current release version
#define RTMP_SIG_SRS_VERSION "0.9.1"
// server info.
#define RTMP_SIG_SRS_KEY "srs"
#define RTMP_SIG_SRS_ROLE "origin server"
#define RTMP_SIG_SRS_NAME RTMP_SIG_SRS_KEY"(simple rtmp server)"
#define RTMP_SIG_SRS_URL "https://"RTMP_SIG_SRS_URL_SHORT
#define RTMP_SIG_SRS_URL_SHORT "github.com/winlinvip/simple-rtmp-server"
#define RTMP_SIG_SRS_WEB "http://blog.csdn.net/win_lin"
#define RTMP_SIG_SRS_EMAIL "winlin@vip.126.com"
#define RTMP_SIG_SRS_LICENSE "The MIT License (MIT)"
#define RTMP_SIG_SRS_COPYRIGHT "Copyright (c) 2013-2014 winlin"
#define RTMP_SIG_SRS_PRIMARY_AUTHROS "winlin,wenjiegit"

// compare
#define srs_min(a, b) (((a) < (b))? (a) : (b))
#define srs_max(a, b) (((a) < (b))? (b) : (a))

// get current system time in ms, use cache to avoid performance problem
extern int64_t srs_get_system_time_ms();
// the deamon st-thread will update it.
extern void srs_update_system_time_ms();

// signal defines.
#define SIGNAL_RELOAD SIGHUP

#include <string>
// replace utility
extern std::string srs_replace(std::string str, std::string old_str, std::string new_str);
// dns resolve utility, return the resolved ip address.
extern std::string srs_dns_resolve(std::string host);
// resolve the vhost in query string
// @param app, may contains the vhost in query string format:
// 		app?vhost=request_vhost
//		app...vhost...request_vhost
extern void srs_vhost_resolve(std::string& vhost, std::string& app);

// close the netfd, and close the underlayer fd.
extern void srs_close_stfd(st_netfd_t& stfd);

/**
* disable copy constructor of class
*/
#define disable_default_copy(className)\
    private:\
        /** \
        * disable the copy constructor and operator=, donot allow directly copy. \
        */ \
        className(const className&); \
        className& operator= (const className&)

#endif<|endoftext|>


<commit_before>/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 11/25/2018, 12:14:31 PM
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
const ll M = 1000000007;

int T;
ll a[310];
ll DP[310][1000];

ll cnt(ll i, ll l)
{
  if (0 <= l && l <= a[i])
  {
    return 1;
  }
  else
  {
    return 0;
  }
}

int main()
{
  cin >> T;
  for (auto i = 1; i <= T; i++)
  {
    cin >> a[i];
  }
  for (auto i = 0; i < 1000; i++)
  {
    DP[0][i] = 0;
  }
  DP[0][0] = 1;
  for (auto i = 1; i <= T; i++)
  {
    for (auto j = 0; j < 1000; j++)
    {
      DP[i][j] = 0;
      for (auto k = 0; k <= min(2 * j, 999); k++)
      {
        DP[i][j] += DP[i - 1][k] * cnt(i, 2 * j - k);
        DP[i][j] %= M;
      }
    }
  }
  for (auto i = 0; i < 4; i++)
  {
    for (auto j = 0; j < 100; j++)
    {
      cerr << "DP[" << i << "][" << j << "] = " << DP[i][j] << endl;
    }
  }
  ll ans = 0;
  for (auto i = 1; i <= T; i++)
  {
    if (a[i] > 0)
    {
      ans++;
    }
  }
  for (auto i = 1; i <= T; i++)
  {
    ans += DP[i][1];
    ans %= M;
  }
  cout << ans << endl;
}<commit_msg>tried E.cpp to 'E'<commit_after>/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 11/25/2018, 12:14:31 PM
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
const ll M = 1000000007;

int T;
ll a[310];
ll DP[310][1000];

ll cnt(ll i, ll l)
{
  if (0 <= l && l <= a[i])
  {
    return 1;
  }
  else
  {
    return 0;
  }
}

int main()
{
  cin >> T;
  for (auto i = 1; i <= T; i++)
  {
    cin >> a[i];
  }
  for (auto i = 0; i < 1000; i++)
  {
    DP[0][i] = 0;
  }
  DP[0][0] = 1;
  for (auto i = 1; i <= T; i++)
  {
    for (auto j = 0; j < 1000; j++)
    {
      DP[i][j] = 0;
      for (auto k = 0; k <= min(2 * j, 999); k++)
      {
        DP[i][j] += DP[i - 1][k] * cnt(i, 2 * j - k);
        DP[i][j] %= M;
      }
    }
  }
  for (auto i = 0; i < T; i++)
  {
    for (auto j = 0; j < 1000; j++)
    {
      cerr << "DP[" << i << "][" << j << "] = " << DP[i][j] << endl;
    }
  }
  ll ans = 0;
  for (auto i = 1; i <= T; i++)
  {
    if (a[i] > 0)
    {
      ans++;
    }
  }
  for (auto i = 1; i <= T; i++)
  {
    ans += DP[i][1];
    ans %= M;
  }
  cout << ans << endl;
}<|endoftext|>


<commit_before>AliPhysicsSelectionTask* AddTaskPhysicsSelection(Bool_t mCAnalysisFlag = kFALSE, Bool_t deprecatedFlag = kTRUE, UInt_t computeBG = 0, Bool_t useSpecialOutput=kFALSE)
{
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskPhysicsSelection", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskPhysicsSelection", "This task requires an input event handler");
    return NULL;
  }

  AliVEventHandler *inputHandler=mgr->GetInputEventHandler();

  TString inputDataType = inputHandler->GetDataType(); // can be "ESD" or "AOD"

  // Configure analysis
  //===========================================================================
  AliPhysicsSelectionTask *task = new AliPhysicsSelectionTask();
  task->SetUseSpecialOutput(useSpecialOutput); // RS: optionally use special output
  // this makes physics selection to work using AliMultiInputEventHandler
  if (inputHandler && (inputHandler->IsA() == AliMultiInputEventHandler::Class())) {
    AliMultiInputEventHandler *multiInputHandler=(AliMultiInputEventHandler*)inputHandler;
    AliInputEventHandler *ih = multiInputHandler->GetFirstInputEventHandler();
    if (!ih) {
      ::Error("AddTaskPhysicsSelection","ESD or AOD input handler is missing");
      return NULL;
    }
    ih->SetEventSelection(multiInputHandler->GetEventSelection());
    inputDataType = ih->GetDataType(); // can be "ESD" or "AOD"
  }

  mgr->AddTask(task);

  AliPhysicsSelection* physSel = task->GetPhysicsSelection();
  if (mCAnalysisFlag)
    physSel->SetAnalyzeMC();
  if (computeBG)
    physSel->SetComputeBG(computeBG);

  if(!deprecatedFlag)
    AliFatal("The BG ID flag is deprecated. Please use the OADB to configure the cuts");

  AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("cstatsout",
                TList::Class(),
                AliAnalysisManager::kOutputContainer,
                "EventStat_temp.root");
  //
  if (useSpecialOutput) coutput1->SetSpecialOutput(); // RS: optionally use special output
  //
  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task,1,coutput1);

  return task;
}
<commit_msg>Reverted "new AliPhysicsSelectionTask()" call to "new AliPhysicsSelectionTask("")"<commit_after>AliPhysicsSelectionTask* AddTaskPhysicsSelection(Bool_t mCAnalysisFlag = kFALSE, Bool_t deprecatedFlag = kTRUE, UInt_t computeBG = 0, Bool_t useSpecialOutput=kFALSE)
{
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskPhysicsSelection", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskPhysicsSelection", "This task requires an input event handler");
    return NULL;
  }

  AliVEventHandler *inputHandler=mgr->GetInputEventHandler();

  TString inputDataType = inputHandler->GetDataType(); // can be "ESD" or "AOD"

  // Configure analysis
  //===========================================================================
  AliPhysicsSelectionTask *task = new AliPhysicsSelectionTask("");
  task->SetUseSpecialOutput(useSpecialOutput); // RS: optionally use special output
  // this makes physics selection to work using AliMultiInputEventHandler
  if (inputHandler && (inputHandler->IsA() == AliMultiInputEventHandler::Class())) {
    AliMultiInputEventHandler *multiInputHandler=(AliMultiInputEventHandler*)inputHandler;
    AliInputEventHandler *ih = multiInputHandler->GetFirstInputEventHandler();
    if (!ih) {
      ::Error("AddTaskPhysicsSelection","ESD or AOD input handler is missing");
      return NULL;
    }
    ih->SetEventSelection(multiInputHandler->GetEventSelection());
    inputDataType = ih->GetDataType(); // can be "ESD" or "AOD"
  }

  mgr->AddTask(task);

  AliPhysicsSelection* physSel = task->GetPhysicsSelection();
  if (mCAnalysisFlag)
    physSel->SetAnalyzeMC();
  if (computeBG)
    physSel->SetComputeBG(computeBG);

  if(!deprecatedFlag)
    AliFatal("The BG ID flag is deprecated. Please use the OADB to configure the cuts");

  AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("cstatsout",
                TList::Class(),
                AliAnalysisManager::kOutputContainer,
                "EventStat_temp.root");
  //
  if (useSpecialOutput) coutput1->SetSpecialOutput(); // RS: optionally use special output
  //
  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task,1,coutput1);

  return task;
}
<|endoftext|>


<commit_before>#include <cassert>
#include <cstring>
#include <iostream>

#include "Packet.h"
#include "VpnPacket.h"

// #define HOSTGATOR

int open_raw_socket_for_listening() {
	static constexpr auto AF_PACKET = 17;
	static constexpr auto PF_PACKET = AF_PACKET;
	static constexpr auto SOCK_RAW_ = 3;
	static constexpr auto ETH_P_ALL = 0x0003;
	int sd_incoming = socket(PF_PACKET, SOCK_RAW_, htons(ETH_P_ALL));
	return sd_incoming;
}

int main() {
	int sd_incoming = open_raw_socket_for_listening();
	if (sd_incoming == -1) {
		std::cerr << "Error while opening raw socket: socket() error " << errno << ": " << strerror(errno) << std::endl;
		exit(1);
	}
	std::cout << "Listening on the wire..." << std::endl;
	while (true) {
		// Raw packet capture
		uint8_t buffer[Ip::IP_MAXPACKET];
		socklen_t size;
		struct sockaddr_in from;
		socklen_t fromlen = sizeof(from);
		size = recvfrom(sd_incoming, reinterpret_cast<char*>(buffer), sizeof(buffer), 0, reinterpret_cast<struct sockaddr*>(&from), &fromlen);
		// std::cout << std::endl << "Receiving " << size << " bytes" << std::endl;

		// There are two possible cases:
		//    1. In HostGator VPS, we receive IP packets (layer 3).
		//    2. In Linux box, we receive DataLink packets (layer 2).
		// So it is better to use IP packets since it works everywhere.
		Ip* ip;

#ifdef HOSTGATOR
		// Layer 3: IP packet
		ip = reinterpret_cast<Ip*>(buffer);
#else
		{
			// Layer 2: Ethernet packet
			Eth* eth = reinterpret_cast<Eth*>(buffer);
			eth->print_header();
			eth->print_header_raw();
			if (ntohs(eth->h_proto) != Eth::ETH_P_IP) continue;

			// Layer 3: IP packet
			ip = reinterpret_cast<Ip*>(eth->payload());
			size -= eth->header_len();
		}
#endif // HOSTGATOR

		// Layer 3
		ip->print_header();
		ip->print_header_raw();
		{
			// Verify that our IP checksum algorithm is correct
			uint16_t original_checksum = ip->check;
			ip->check = 0;
			ip->check = ip->checksum();
			if (ip->check != original_checksum) {
				std::cerr << "IP checksum does not match " << original_checksum << " != " << ip->check << std::endl;
			}
		}

		// Layer 4
		switch (ip->protocol) {
		case Ip::IPPROTO_TCP:
		{
			Tcp* tcp = reinterpret_cast<Tcp*>(ip->payload());
			// Skip processing SSH packets
			if (ntohs(tcp->source) == 22 || ntohs(tcp->dest) == 22) {
				continue;
			}
			tcp->print_header();
			tcp->print_header_raw();
			std::cout << "Payload:" << std::endl;
			Util::print_raw(tcp->payload(), ip->total_len() - ip->header_len() - tcp->header_len());
			{
				// Verify that our TCP checksum algorithm is correct
				// How to disable checksum offloading: ethtool -K eth0 rx off tx off   (https://stackoverflow.com/questions/15538786/how-is-tcps-checksum-calculated-when-we-use-tcpdump-to-capture-packets-which-we)
				int len = ip->total_len() - ip->header_len();
				uint16_t original_checksum = tcp->check;
				tcp->check = 0;
				tcp->check = tcp->checksum(len, ip->saddr, ip->daddr);
				if (tcp->check != original_checksum) {
					std::cerr << "TCP checksum does not match " << original_checksum << " != " << tcp->check << std::endl;
				}
			}
			std::cout << std::endl;
			break;
		}

		case Ip::IPPROTO_UDP:
		{
			Udp* udp = reinterpret_cast<Udp*>(ip->payload());
			udp->print_header();
			udp->print_header_raw();
			std::cout << "Payload:" << std::endl;
			udp->print_payload_raw();
			// std::cout << "Payload:" << std::endl;
			// Util::print_raw(udp->payload(), ip->total_len() - ip->header_len() - udp->header_len());
			{
				// Verify that our UDP checksum algorithm is correct
				int len = ip->total_len() - ip->header_len();
				uint16_t original_checksum = udp->check;
				udp->check = 0;
				udp->check = udp->checksum(len, ip->saddr, ip->daddr);
				if (udp->check != original_checksum) {
					std::cerr << "UDP checksum does not match " << original_checksum << " != " << udp->check << std::endl;
				}
			}
			std::cout << std::endl;
			break;
		}

		case Ip::IPPROTO_ICMP:
		{
			Icmp* icmp = reinterpret_cast<Icmp*>(ip->payload());
			icmp->print_header();
			{
				// Verify that our ICMP checksum algorithm is correct
				int len = ip->total_len() - ip->header_len();
				uint16_t original_checksum = icmp->check;
				icmp->check = 0;
				icmp->check = icmp->checksum(len);
				if (icmp->check != original_checksum) {
					std::cerr << "ICMP checksum does not match " << original_checksum << " != " << icmp->check << std::endl;
				}
			}
			std::cout << std::endl;
			break;
		}

		default:
			// Ignore non TCP, UDP or ICMP packet
			continue;
		}
	}
	return 0;
}
<commit_msg>Print known packets only<commit_after>#include <cassert>
#include <cstring>
#include <iostream>

#include "Packet.h"
#include "VpnPacket.h"

// #define HOSTGATOR

int open_raw_socket_for_listening() {
	static constexpr auto AF_PACKET = 17;
	static constexpr auto PF_PACKET = AF_PACKET;
	static constexpr auto SOCK_RAW_ = 3;
	static constexpr auto ETH_P_ALL = 0x0003;
	int sd_incoming = socket(PF_PACKET, SOCK_RAW_, htons(ETH_P_ALL));
	return sd_incoming;
}

int main() {
	int sd_incoming = open_raw_socket_for_listening();
	if (sd_incoming == -1) {
		std::cerr << "Error while opening raw socket: socket() error " << errno << ": " << strerror(errno) << std::endl;
		exit(1);
	}
	std::cout << "Listening on the wire..." << std::endl;
	while (true) {
		// Raw packet capture
		uint8_t buffer[Ip::IP_MAXPACKET];
		socklen_t size;
		struct sockaddr_in from;
		socklen_t fromlen = sizeof(from);
		size = recvfrom(sd_incoming, reinterpret_cast<char*>(buffer), sizeof(buffer), 0, reinterpret_cast<struct sockaddr*>(&from), &fromlen);
		// std::cout << std::endl << "Receiving " << size << " bytes" << std::endl;

		// There are two possible cases:
		//    1. In HostGator VPS, we receive IP packets (layer 3).
		//    2. In Linux box, we receive DataLink packets (layer 2).
		// So it is better to use IP packets since it works everywhere.
		Ip* ip;

#ifdef HOSTGATOR
		// Layer 3: IP packet
		ip = reinterpret_cast<Ip*>(buffer);
#else
		{
			// Layer 2: Ethernet packet
			Eth* eth = reinterpret_cast<Eth*>(buffer);
			// eth->print_header();
			// eth->print_header_raw();
			if (ntohs(eth->h_proto) != Eth::ETH_P_IP) continue;

			// Layer 3: IP packet
			ip = reinterpret_cast<Ip*>(eth->payload());
			size -= eth->header_len();
		}
#endif // HOSTGATOR

		// Layer 3
		{
			// Verify that our IP checksum algorithm is correct
			uint16_t original_checksum = ip->check;
			ip->check = 0;
			ip->check = ip->checksum();
			if (ip->check != original_checksum) {
				std::cerr << "IP checksum does not match " << original_checksum << " != " << ip->check << std::endl;
			}
		}

		// Layer 4
		switch (ip->protocol) {
		case Ip::IPPROTO_TCP:
		{
			Tcp* tcp = reinterpret_cast<Tcp*>(ip->payload());
			// Skip processing SSH packets
			if (ntohs(tcp->source) == 22 || ntohs(tcp->dest) == 22) {
				continue;
			}
			ip->print_header();
			ip->print_header_raw();
			tcp->print_header();
			tcp->print_header_raw();
			std::cout << "Payload:" << std::endl;
			Util::print_raw(tcp->payload(), ip->total_len() - ip->header_len() - tcp->header_len());
			{
				// Verify that our TCP checksum algorithm is correct
				// How to disable checksum offloading: ethtool -K eth0 rx off tx off   (https://stackoverflow.com/questions/15538786/how-is-tcps-checksum-calculated-when-we-use-tcpdump-to-capture-packets-which-we)
				int len = ip->total_len() - ip->header_len();
				uint16_t original_checksum = tcp->check;
				tcp->check = 0;
				tcp->check = tcp->checksum(len, ip->saddr, ip->daddr);
				if (tcp->check != original_checksum) {
					std::cerr << "TCP checksum does not match " << original_checksum << " != " << tcp->check << std::endl;
				}
			}
			std::cout << std::endl;
			break;
		}

		case Ip::IPPROTO_UDP:
		{
			Udp* udp = reinterpret_cast<Udp*>(ip->payload());
			ip->print_header();
			ip->print_header_raw();
			udp->print_header();
			udp->print_header_raw();
			std::cout << "Payload:" << std::endl;
			udp->print_payload_raw();
			// std::cout << "Payload:" << std::endl;
			// Util::print_raw(udp->payload(), ip->total_len() - ip->header_len() - udp->header_len());
			{
				// Verify that our UDP checksum algorithm is correct
				int len = ip->total_len() - ip->header_len();
				uint16_t original_checksum = udp->check;
				udp->check = 0;
				udp->check = udp->checksum(len, ip->saddr, ip->daddr);
				if (udp->check != original_checksum) {
					std::cerr << "UDP checksum does not match " << original_checksum << " != " << udp->check << std::endl;
				}
			}
			std::cout << std::endl;
			break;
		}

		case Ip::IPPROTO_ICMP:
		{
			Icmp* icmp = reinterpret_cast<Icmp*>(ip->payload());
			ip->print_header();
			ip->print_header_raw();
			icmp->print_header();
			{
				// Verify that our ICMP checksum algorithm is correct
				int len = ip->total_len() - ip->header_len();
				uint16_t original_checksum = icmp->check;
				icmp->check = 0;
				icmp->check = icmp->checksum(len);
				if (icmp->check != original_checksum) {
					std::cerr << "ICMP checksum does not match " << original_checksum << " != " << icmp->check << std::endl;
				}
			}
			std::cout << std::endl;
			break;
		}

		default:
			// Ignore non TCP, UDP or ICMP packet
			continue;
		}
	}
	return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008-2009 Manjeet Dahiya
 *
 * Author:
 *	Manjeet Dahiya
 *
 * Source:
 *	http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 */

#include "QXmppStanza.h"
#include "QXmppUtils.h"
#include "QXmppConstants.h"

#include <QDomElement>
#include <QXmlStreamWriter>

uint QXmppStanza::s_uniqeIdNo = 0;

QXmppStanza::Error::Error():
    m_type(static_cast<QXmppStanza::Error::Type>(-1)),
    m_code(0),
    m_condition(static_cast<QXmppStanza::Error::Condition>(-1)),
    m_text("")
{
}

QXmppStanza::Error::Error(Type type, Condition cond, const QString& text):
    m_type(type),
    m_code(0),
    m_condition(cond),
    m_text(text)
{
}

QXmppStanza::Error::Error(const QString& type, const QString& cond,
                          const QString& text):
    m_code(0),
    m_text(text)
{
    setTypeFromStr(type);
    setConditionFromStr(cond);
}

void QXmppStanza::Error::setText(const QString& text)
{
    m_text = text;
}

void QXmppStanza::Error::setCode(int code)
{
    m_code = code;
}

void QXmppStanza::Error::setCondition(QXmppStanza::Error::Condition cond)
{
    m_condition = cond;
}

void QXmppStanza::Error::setType(QXmppStanza::Error::Type type)
{
    m_type = type;
}

QString QXmppStanza::Error::getText() const
{
    return m_text;
}

int QXmppStanza::Error::getCode() const
{
    return m_code;
}

QXmppStanza::Error::Condition QXmppStanza::Error::getCondition() const
{
    return m_condition;
}

QXmppStanza::Error::Type QXmppStanza::Error::getType() const
{
    return m_type;
}

QString QXmppStanza::Error::getTypeStr() const
{
    switch(getType())
    {
    case Cancel:
        return "cancel";
    case Continue:
        return "continue";
    case Modify:
        return "modify";
    case Auth:
        return "auth";
    case Wait:
        return "wait";
    default:
        return "";
    }
}

QString QXmppStanza::Error::getConditionStr() const
{
    switch(getCondition())
    {
    case BadRequest:
        return "bad-request";
    case Conflict:
        return "conflict";
    case FeatureNotImplemented:
        return "feature-not-implemented";
    case Forbidden:
        return "forbidden";
    case Gone:
        return "gone";
    case InternalServerError:
        return "internal-server-error";
    case ItemNotFound:
        return "item-not-found";
    case JidMalformed:
        return "jid-malformed";
    case NotAcceptable:
        return "not-acceptable";
    case NotAllowed:
        return "not-allowed";
    case NotAuthorized:
        return "not-authorized";
    case PaymentRequired:
        return "payment-required";
    case RecipientUnavailable:
        return "recipient-unavailable";
    case Redirect:
        return "redirect";
    case RegistrationRequired:
        return "registration-required";
    case RemoteServerNotFound:
        return "remote-server-not-found";
    case RemoteServerTimeout:
        return "remote-server-timeout";
    case ResourceConstraint:
        return "resource-constraint";
    case ServiceUnavailable:
        return "service-unavailable";
    case SubscriptionRequired:
        return "subscription-required";
    case UndefinedCondition:
        return "undefined-condition";
    case UnexpectedRequest:
        return "unexpected-request";
    default:
        return "";
    }
}

void QXmppStanza::Error::setTypeFromStr(const QString& type)
{
    if(type == "cancel")
        setType(Cancel);
    else if(type == "continue")
        setType(Continue);
    else if(type == "modify")
        setType(Modify);
    else if(type == "auth")
        setType(Auth);
    else if(type == "wait")
        setType(Wait);
    else
        setType(static_cast<QXmppStanza::Error::Type>(-1));
}

void QXmppStanza::Error::setConditionFromStr(const QString& type)
{
    if(type == "bad-request")
        setCondition(BadRequest);
    else if(type == "conflict")
        setCondition(Conflict);
    else if(type == "feature-not-implemented")
        setCondition(FeatureNotImplemented);
    else if(type == "forbidden")
        setCondition(Forbidden);
    else if(type == "gone")
        setCondition(Gone);
    else if(type == "internal-server-error")
        setCondition(InternalServerError);
    else if(type == "item-not-found")
        setCondition(ItemNotFound);
    else if(type == "jid-malformed")
        setCondition(JidMalformed);
    else if(type == "not-acceptable")
        setCondition(NotAcceptable);
    else if(type == "not-allowed")
        setCondition(NotAllowed);
    else if(type == "not-authorized")
        setCondition(NotAuthorized);
    else if(type == "payment-required")
        setCondition(PaymentRequired);
    else if(type == "recipient-unavailable")
        setCondition(RecipientUnavailable);
    else if(type == "redirect")
        setCondition(Redirect);
    else if(type == "registration-required")
        setCondition(RegistrationRequired);
    else if(type == "remote-server-not-found")
        setCondition(RemoteServerNotFound);
    else if(type == "remote-server-timeout")
        setCondition(RemoteServerTimeout);
    else if(type == "resource-constraint")
        setCondition(ResourceConstraint);
    else if(type == "service-unavailable")
        setCondition(ServiceUnavailable);
    else if(type == "subscription-required")
        setCondition(SubscriptionRequired);
    else if(type == "undefined-condition")
        setCondition(UndefinedCondition);
    else if(type == "unexpected-request")
        setCondition(UnexpectedRequest);
    else
        setCondition(static_cast<QXmppStanza::Error::Condition>(-1));
}

void QXmppStanza::Error::toXml( QXmlStreamWriter *writer ) const
{
    QString cond = getConditionStr();
    QString type = getTypeStr();

    if(cond.isEmpty() && type.isEmpty())
        return;

    writer->writeStartElement("error");
    helperToXmlAddAttribute(writer, "type", type);

    if (m_code > 0)
        helperToXmlAddAttribute(writer, "code", QString::number(m_code));

    if(!cond.isEmpty())
    {
        writer->writeStartElement(cond);
        helperToXmlAddAttribute(writer,"xmlns", ns_stanza);
        writer->writeEndElement();
    }
    if(!m_text.isEmpty())
    {
        writer->writeStartElement("text");
        helperToXmlAddAttribute(writer,"xml:lang", "en");
        helperToXmlAddAttribute(writer,"xmlns", ns_stanza);
        writer->writeCharacters(m_text);
        writer->writeEndElement();
    }

    writer->writeEndElement();
}

QXmppStanza::QXmppStanza(const QString& from, const QString& to) : QXmppPacket(),
m_to(to), m_from(from)
{
}

QXmppStanza::~QXmppStanza()
{

}

QString QXmppStanza::getTo() const
{
    return m_to;
}

QString QXmppStanza::getFrom() const
{
    return m_from;
}

QString QXmppStanza::getId() const
{
    return m_id;
}

QString QXmppStanza::getLang() const
{
    return m_lang;
}

void QXmppStanza::setTo(const QString& to)
{
    m_to = to;
}

void QXmppStanza::setFrom(const QString& from)
{
    m_from = from;
}

void QXmppStanza::setId(const QString& id)
{
    m_id = id;
}

void QXmppStanza::setLang(const QString& lang)
{
    m_lang = lang;
}

void QXmppStanza::generateAndSetNextId()
{
    // get back
    ++s_uniqeIdNo;
    m_id = "qxmpp" + QString::number(s_uniqeIdNo);
}

QXmppStanza::Error QXmppStanza::getError() const
{
    return m_error;
}

void QXmppStanza::setError(QXmppStanza::Error& error)
{
    m_error = error;
}

QXmppElementList QXmppStanza::getExtensions() const
{
    return m_extensions;
}

void QXmppStanza::setExtensions(const QXmppElementList &extensions)
{
    m_extensions = extensions;
}

bool QXmppStanza::isErrorStanza()
{
    return !(m_error.getTypeStr().isEmpty() &&
        m_error.getConditionStr().isEmpty());
}

QXmppStanza::Error QXmppStanza::parseError(const QDomElement &errorElement)
{
    QXmppStanza::Error error;

    if(errorElement.isNull())
        return error;

    QString type = errorElement.attribute("type");
    QString text;
    QString cond;
    QDomElement element = errorElement.firstChildElement();
    while(!element.isNull())
    {
        if(element.tagName() == "text")
            text = element.text();
        else if(element.namespaceURI() == ns_stanza)
        {
            cond = element.tagName();
        }
        element = element.nextSiblingElement();
    }

    error.setCode(errorElement.attribute("code").toInt());
    error.setConditionFromStr(cond);
    error.setTypeFromStr(type);
    error.setText(text);
    return error;
}

<commit_msg>fix for compile time warning messages<commit_after>/*
 * Copyright (C) 2008-2009 Manjeet Dahiya
 *
 * Author:
 *	Manjeet Dahiya
 *
 * Source:
 *	http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 */

#include "QXmppStanza.h"
#include "QXmppUtils.h"
#include "QXmppConstants.h"

#include <QDomElement>
#include <QXmlStreamWriter>

uint QXmppStanza::s_uniqeIdNo = 0;

QXmppStanza::Error::Error():
    m_code(0),
    m_type(static_cast<QXmppStanza::Error::Type>(-1)),
    m_condition(static_cast<QXmppStanza::Error::Condition>(-1)),
    m_text("")
{
}

QXmppStanza::Error::Error(Type type, Condition cond, const QString& text):
    m_code(0),
    m_type(type),
    m_condition(cond),
    m_text(text)
{
}

QXmppStanza::Error::Error(const QString& type, const QString& cond,
                          const QString& text):
    m_code(0),
    m_text(text)
{
    setTypeFromStr(type);
    setConditionFromStr(cond);
}

void QXmppStanza::Error::setText(const QString& text)
{
    m_text = text;
}

void QXmppStanza::Error::setCode(int code)
{
    m_code = code;
}

void QXmppStanza::Error::setCondition(QXmppStanza::Error::Condition cond)
{
    m_condition = cond;
}

void QXmppStanza::Error::setType(QXmppStanza::Error::Type type)
{
    m_type = type;
}

QString QXmppStanza::Error::getText() const
{
    return m_text;
}

int QXmppStanza::Error::getCode() const
{
    return m_code;
}

QXmppStanza::Error::Condition QXmppStanza::Error::getCondition() const
{
    return m_condition;
}

QXmppStanza::Error::Type QXmppStanza::Error::getType() const
{
    return m_type;
}

QString QXmppStanza::Error::getTypeStr() const
{
    switch(getType())
    {
    case Cancel:
        return "cancel";
    case Continue:
        return "continue";
    case Modify:
        return "modify";
    case Auth:
        return "auth";
    case Wait:
        return "wait";
    default:
        return "";
    }
}

QString QXmppStanza::Error::getConditionStr() const
{
    switch(getCondition())
    {
    case BadRequest:
        return "bad-request";
    case Conflict:
        return "conflict";
    case FeatureNotImplemented:
        return "feature-not-implemented";
    case Forbidden:
        return "forbidden";
    case Gone:
        return "gone";
    case InternalServerError:
        return "internal-server-error";
    case ItemNotFound:
        return "item-not-found";
    case JidMalformed:
        return "jid-malformed";
    case NotAcceptable:
        return "not-acceptable";
    case NotAllowed:
        return "not-allowed";
    case NotAuthorized:
        return "not-authorized";
    case PaymentRequired:
        return "payment-required";
    case RecipientUnavailable:
        return "recipient-unavailable";
    case Redirect:
        return "redirect";
    case RegistrationRequired:
        return "registration-required";
    case RemoteServerNotFound:
        return "remote-server-not-found";
    case RemoteServerTimeout:
        return "remote-server-timeout";
    case ResourceConstraint:
        return "resource-constraint";
    case ServiceUnavailable:
        return "service-unavailable";
    case SubscriptionRequired:
        return "subscription-required";
    case UndefinedCondition:
        return "undefined-condition";
    case UnexpectedRequest:
        return "unexpected-request";
    default:
        return "";
    }
}

void QXmppStanza::Error::setTypeFromStr(const QString& type)
{
    if(type == "cancel")
        setType(Cancel);
    else if(type == "continue")
        setType(Continue);
    else if(type == "modify")
        setType(Modify);
    else if(type == "auth")
        setType(Auth);
    else if(type == "wait")
        setType(Wait);
    else
        setType(static_cast<QXmppStanza::Error::Type>(-1));
}

void QXmppStanza::Error::setConditionFromStr(const QString& type)
{
    if(type == "bad-request")
        setCondition(BadRequest);
    else if(type == "conflict")
        setCondition(Conflict);
    else if(type == "feature-not-implemented")
        setCondition(FeatureNotImplemented);
    else if(type == "forbidden")
        setCondition(Forbidden);
    else if(type == "gone")
        setCondition(Gone);
    else if(type == "internal-server-error")
        setCondition(InternalServerError);
    else if(type == "item-not-found")
        setCondition(ItemNotFound);
    else if(type == "jid-malformed")
        setCondition(JidMalformed);
    else if(type == "not-acceptable")
        setCondition(NotAcceptable);
    else if(type == "not-allowed")
        setCondition(NotAllowed);
    else if(type == "not-authorized")
        setCondition(NotAuthorized);
    else if(type == "payment-required")
        setCondition(PaymentRequired);
    else if(type == "recipient-unavailable")
        setCondition(RecipientUnavailable);
    else if(type == "redirect")
        setCondition(Redirect);
    else if(type == "registration-required")
        setCondition(RegistrationRequired);
    else if(type == "remote-server-not-found")
        setCondition(RemoteServerNotFound);
    else if(type == "remote-server-timeout")
        setCondition(RemoteServerTimeout);
    else if(type == "resource-constraint")
        setCondition(ResourceConstraint);
    else if(type == "service-unavailable")
        setCondition(ServiceUnavailable);
    else if(type == "subscription-required")
        setCondition(SubscriptionRequired);
    else if(type == "undefined-condition")
        setCondition(UndefinedCondition);
    else if(type == "unexpected-request")
        setCondition(UnexpectedRequest);
    else
        setCondition(static_cast<QXmppStanza::Error::Condition>(-1));
}

void QXmppStanza::Error::toXml( QXmlStreamWriter *writer ) const
{
    QString cond = getConditionStr();
    QString type = getTypeStr();

    if(cond.isEmpty() && type.isEmpty())
        return;

    writer->writeStartElement("error");
    helperToXmlAddAttribute(writer, "type", type);

    if (m_code > 0)
        helperToXmlAddAttribute(writer, "code", QString::number(m_code));

    if(!cond.isEmpty())
    {
        writer->writeStartElement(cond);
        helperToXmlAddAttribute(writer,"xmlns", ns_stanza);
        writer->writeEndElement();
    }
    if(!m_text.isEmpty())
    {
        writer->writeStartElement("text");
        helperToXmlAddAttribute(writer,"xml:lang", "en");
        helperToXmlAddAttribute(writer,"xmlns", ns_stanza);
        writer->writeCharacters(m_text);
        writer->writeEndElement();
    }

    writer->writeEndElement();
}

QXmppStanza::QXmppStanza(const QString& from, const QString& to) : QXmppPacket(),
m_to(to), m_from(from)
{
}

QXmppStanza::~QXmppStanza()
{

}

QString QXmppStanza::getTo() const
{
    return m_to;
}

QString QXmppStanza::getFrom() const
{
    return m_from;
}

QString QXmppStanza::getId() const
{
    return m_id;
}

QString QXmppStanza::getLang() const
{
    return m_lang;
}

void QXmppStanza::setTo(const QString& to)
{
    m_to = to;
}

void QXmppStanza::setFrom(const QString& from)
{
    m_from = from;
}

void QXmppStanza::setId(const QString& id)
{
    m_id = id;
}

void QXmppStanza::setLang(const QString& lang)
{
    m_lang = lang;
}

void QXmppStanza::generateAndSetNextId()
{
    // get back
    ++s_uniqeIdNo;
    m_id = "qxmpp" + QString::number(s_uniqeIdNo);
}

QXmppStanza::Error QXmppStanza::getError() const
{
    return m_error;
}

void QXmppStanza::setError(QXmppStanza::Error& error)
{
    m_error = error;
}

QXmppElementList QXmppStanza::getExtensions() const
{
    return m_extensions;
}

void QXmppStanza::setExtensions(const QXmppElementList &extensions)
{
    m_extensions = extensions;
}

bool QXmppStanza::isErrorStanza()
{
    return !(m_error.getTypeStr().isEmpty() &&
        m_error.getConditionStr().isEmpty());
}

QXmppStanza::Error QXmppStanza::parseError(const QDomElement &errorElement)
{
    QXmppStanza::Error error;

    if(errorElement.isNull())
        return error;

    QString type = errorElement.attribute("type");
    QString text;
    QString cond;
    QDomElement element = errorElement.firstChildElement();
    while(!element.isNull())
    {
        if(element.tagName() == "text")
            text = element.text();
        else if(element.namespaceURI() == ns_stanza)
        {
            cond = element.tagName();
        }
        element = element.nextSiblingElement();
    }

    error.setCode(errorElement.attribute("code").toInt());
    error.setConditionFromStr(cond);
    error.setTypeFromStr(type);
    error.setText(text);
    return error;
}

<|endoftext|>


<commit_before>//	Copyright 2017 Adam Smith
//	Licensed under the Apache License, Version 2.0 (the "License");
//	you may not use this file except in compliance with the License.
//	You may obtain a copy of the License at
//
//	http://www.apache.org/licenses/LICENSE-2.0
//
//	Unless required by applicable law or agreed to in writing, software
//	distributed under the License is distributed on an "AS IS" BASIS,
//	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//	See the License for the specific language governing permissions and
//	limitations under the License.

#include <type_traits>
#include <cstdint>
#include <string>
#include <memory>
#include <vector>

#ifndef ASMITH_REFLECTION_CLASS_HPP
#define ASMITH_REFLECTION_CLASS_HPP

namespace asmith {

	class reflection_variable;
	class reflection_function;
	class reflection_constructor;
	class reflection_destructor;

	class reflection_class {
	public:
		virtual ~reflection_class() {}

		virtual const char* get_name() const = 0;
		virtual size_t get_size() const = 0;
		virtual size_t get_variable_count() const = 0;
		virtual const reflection_variable& get_variable(size_t) const = 0;
		virtual size_t get_function_count() const = 0;
		virtual const reflection_function& get_function(size_t) const = 0;
		virtual size_t get_constructor_count() const = 0;
		virtual const reflection_constructor& get_constructor(size_t) const = 0;
		virtual const reflection_destructor& get_destructor() const = 0;
		virtual size_t get_parent_count() const = 0;
		virtual const reflection_class& get_parent_class(size_t) const = 0;
	};

	class auto_reflection_class : public reflection_class {
	private:
		std::vector<std::shared_ptr<reflection_class>> mParents;
		std::vector<std::shared_ptr<reflection_constructor>> mConstructors;
		std::vector<std::shared_ptr<reflection_variable>> mVariables;
		std::vector<std::shared_ptr<reflection_function>> mFunctions;
		std::shared_ptr<reflection_destructor> mDestructor;
		const std::string mName;
		const size_t mSize;
	public:
		auto_reflection_class(const std::string& aName, const size_t aSize) :
			mName(aName),
			mSize(aSize)
		{}

		//! \todo Add parent_classes, constructors, variables and destructor

		template<class CLASS, class RETURN, class... PARAMS>
		auto_reflection_class& function(const std::string& aName, RETURN(CLASS::*aPtr)(PARAMS...), const size_t aModifiers) {
			mFunctions.push_back(std::shared_ptr<reflection_function>(
				new typedef auto_reflection_function<CLASS, RETURN, PARAMS...>(aName, aPtr, aModifiers);
			));
			return *this;
		}

		// Inherited from reflection_class
		const char* get_name() const override {
			mName.c_str();
		}

		size_t get_size() const override {
			return mSize;
		}

		size_t get_variable_count() const override {
			return mVariables.size();
		}

		const reflection_variable& get_variable(size_t aIndex) const override {
			return *mVariables[aIndex];
		}

		size_t get_function_count() const override {
			return mFunctions.size();
		}

		const reflection_function& get_function(size_t aIndex) const override {
			return *mFunctions[aIndex];
		}

		size_t get_constructor_count() const override {
			return mConstructors.size();
		}

		const reflection_constructor& get_constructor(size_t aIndex) const override {
			return *mConstructors[aIndex];
		}

		const reflection_destructor& get_destructor() const override {
			return *mDestructor;
		}

		size_t get_parent_count() const override {
			return mParents.size();
		}

		const reflection_class& get_parent_class(size_t aIndex) const override {
			return *mParents[aIndex];
		}
	};
}
#endif<commit_msg>Reflect function & parent classes<commit_after>//	Copyright 2017 Adam Smith
//	Licensed under the Apache License, Version 2.0 (the "License");
//	you may not use this file except in compliance with the License.
//	You may obtain a copy of the License at
//
//	http://www.apache.org/licenses/LICENSE-2.0
//
//	Unless required by applicable law or agreed to in writing, software
//	distributed under the License is distributed on an "AS IS" BASIS,
//	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//	See the License for the specific language governing permissions and
//	limitations under the License.

#include <type_traits>
#include <cstdint>
#include <string>
#include <memory>
#include <vector>

#ifndef ASMITH_REFLECTION_CLASS_HPP
#define ASMITH_REFLECTION_CLASS_HPP

namespace asmith {

	class reflection_variable;
	class reflection_function;
	class reflection_constructor;
	class reflection_destructor;

	class reflection_class {
	public:
		virtual ~reflection_class() {}

		virtual const char* get_name() const = 0;
		virtual size_t get_size() const = 0;
		virtual size_t get_variable_count() const = 0;
		virtual const reflection_variable& get_variable(size_t) const = 0;
		virtual size_t get_function_count() const = 0;
		virtual const reflection_function& get_function(size_t) const = 0;
		virtual size_t get_constructor_count() const = 0;
		virtual const reflection_constructor& get_constructor(size_t) const = 0;
		virtual const reflection_destructor& get_destructor() const = 0;
		virtual size_t get_parent_count() const = 0;
		virtual const reflection_class& get_parent_class(size_t) const = 0;
	};

	template<class T>
	const reflection_class& reflect() {
		return T::REFLECTION;
	}

	class auto_reflection_class : public reflection_class {
	private:
		std::vector<const reflection_class*> mParents;
		std::vector<std::shared_ptr<reflection_constructor>> mConstructors;
		std::vector<std::shared_ptr<reflection_variable>> mVariables;
		std::vector<std::shared_ptr<reflection_function>> mFunctions;
		std::shared_ptr<reflection_destructor> mDestructor;
		const std::string mName;
		const size_t mSize;
	public:
		auto_reflection_class(const std::string& aName, const size_t aSize) :
			mName(aName),
			mSize(aSize)
		{}

		//! \todo Add constructors, variables and destructor

		template<class CLASS>
		auto_reflection_class& parent() {
			mFunctions.push_back(&reflect<CLASS>());
			return *this;
		}

		template<class CLASS, class RETURN, class... PARAMS>
		auto_reflection_class& function(const std::string& aName, RETURN(CLASS::*aPtr)(PARAMS...), const size_t aModifiers) {
			mFunctions.push_back(std::shared_ptr<reflection_function>(
				new typedef auto_reflection_function<CLASS, RETURN, PARAMS...>(aName, aPtr, aModifiers);
			));
			return *this;
		}

		// Inherited from reflection_class
		const char* get_name() const override {
			mName.c_str();
		}

		size_t get_size() const override {
			return mSize;
		}

		size_t get_variable_count() const override {
			return mVariables.size();
		}

		const reflection_variable& get_variable(size_t aIndex) const override {
			return *mVariables[aIndex];
		}

		size_t get_function_count() const override {
			return mFunctions.size();
		}

		const reflection_function& get_function(size_t aIndex) const override {
			return *mFunctions[aIndex];
		}

		size_t get_constructor_count() const override {
			return mConstructors.size();
		}

		const reflection_constructor& get_constructor(size_t aIndex) const override {
			return *mConstructors[aIndex];
		}

		const reflection_destructor& get_destructor() const override {
			return *mDestructor;
		}

		size_t get_parent_count() const override {
			return mParents.size();
		}

		const reflection_class& get_parent_class(size_t aIndex) const override {
			return *mParents[aIndex];
		}
	};
}
#endif<|endoftext|>


<commit_before>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_CORE_MAIN_MENU_MAIN_MENU_HPP
#define RJ_CORE_MAIN_MENU_MAIN_MENU_HPP

#include "background.hpp"
#include "component_manager.hpp"
#include "items.hpp"
#include "menu_levels.hpp"
#include "menu_start.hpp"
#include "submenu_manager.hpp"
#include "title.hpp"
#include <rectojump/core/game_window.hpp>
#include <rectojump/core/render.hpp>
#include <rectojump/game/background/background_manager.hpp>
#include <rectojump/game/components/player.hpp>
#include <rectojump/game/factory.hpp>
#include <rectojump/global/common.hpp>
#include <rectojump/global/config_settings.hpp>
#include <rectojump/shared/level_manager/level_manager.hpp>
#include <rectojump/shared/data_manager.hpp>
#include <rectojump/shared/utils.hpp>

#include <SFML/Graphics.hpp>

namespace rj
{
	template<typename Game_Handler>
	class main_menu
	{
		Game_Handler& m_gamehandler;
		game_window& m_gamewindow;
		data_manager& m_datamgr;
		level_manager& m_lvmgr;
		background_manager& m_backgroundmgr;

		sf::Font m_font{m_datamgr.get_as<sf::Font>("Fipps-Regular.otf")};
		const vec2f m_center{/*settings::get_window_size<vec2f>() / 2.f*/}; // TODO: clang frontend crash
		const sf::Color m_def_fontcolor{to_rgb("#797979") /*"#797979"_rgb*/}; // TODO: QTC dont supports that custom literals yet
		const sf::Color m_act_fontcolor{to_rgb("#f15ede") /*"#f15ede"_rgb*/};

		// background
		background<main_menu<Game_Handler>> m_background{*this};

		// components (menus)
		component_manager<main_menu<Game_Handler>> m_componentmgr{*this};
		comp_ptr<menu_start<main_menu<Game_Handler>>> m_start{m_componentmgr.template create_comp<menu_start<main_menu<Game_Handler>>, menu_state::menu_start>()};
		comp_ptr<menu_levels<main_menu<Game_Handler>>> m_levels{m_componentmgr.template create_comp<menu_levels<main_menu<Game_Handler>>, menu_state::menu_levels>()};

		// other components (not menus)
		title m_title;

		// menu state
		submenu_manager<menu_state, menu_state::menu_start> m_submenumgr;
		mlk::event_delegates<menu_state> m_on_menu_switch;

	public:
		main_menu(Game_Handler& gh) :
			m_gamehandler{gh},
			m_gamewindow{gh.get_gamewindow()},
			m_datamgr{gh.get_datamgr()},
			m_lvmgr{gh.get_levelmgr()},
			m_backgroundmgr{gh.get_backgroundmgr()},
			m_center{settings::get_window_size<vec2f>() / 2.f},
			m_title{m_gamehandler.get_render(), m_font, m_center}
		{this->init();}

		void update(dur duration)
		{
			m_submenumgr.update_current_state(duration);
			m_background.update(duration);
			m_title.update(duration);
		}

		void render()
		{
			m_background.render();
			m_submenumgr.render_current_state();
			m_title.render();
		}

		void on_key_up()
		{m_submenumgr.event_up();}

		void on_key_down()
		{m_submenumgr.event_down();}

		void on_key_backspace()
		{
			// activate prev state from submenu
			auto ptr(m_componentmgr.get_comp_from_type(m_submenumgr.get_current_state()));
			if(ptr != nullptr)
				if(ptr->is_accessing_submenu())
				{
					ptr->on_key_backspace();
					return;
				}

			// activate prev state
			this->do_menu_switch_back();
		}

		bool is_active(menu_state s) const noexcept
		{return m_submenumgr.get_current_state() == s;}

		void call_current_itemevent()
		{m_submenumgr.event_current();}

		void do_menu_switch(menu_state s)
		{
			m_submenumgr.switch_state(s);
			m_on_menu_switch[s]();
		}

		void do_menu_switch_back()
		{
			m_submenumgr.activate_prev_state();
			m_on_menu_switch[m_submenumgr.get_current_state()]();
		}

		auto get_gamehandler()
		-> decltype(m_gamehandler)&
		{return m_gamehandler;}

		const sf::Font& get_font() const noexcept
		{return m_font;}

		const vec2f& get_center() const noexcept
		{return m_center;}

		const sf::Color& get_act_fontcolor() const noexcept
		{return m_act_fontcolor;}

		const sf::Color& get_def_fontcolor() const noexcept
		{return m_def_fontcolor;}

	private:
		void init()
		{
			m_submenumgr.add_menu(menu_state::menu_start, m_start);
			m_submenumgr.add_menu(menu_state::menu_levels, m_levels);

			this->setup_events();
			this->setup_interface();
		}

		void setup_events()
		{
			// menu switch
			m_on_menu_switch[menu_state::menu_levels] +=
			[this]{m_title.set_text("Levels");};

			m_on_menu_switch[menu_state::menu_start] +=
			[this]{m_title.set_text("Recto Jump");};

			// start menu:
			// item events:
			m_start->get_items().on_event("play",
			[this]{this->do_menu_switch(menu_state::menu_levels);});

			m_start->get_items().on_event("editor",
			[this]{});

			m_start->get_items().on_event("quit",
			[this]{m_gamewindow.stop();});

			// level menu:
			// item events:
			m_levels->get_items().on_event("lv_download",
			[this]{m_gamehandler.get_popupmgr().create_popup("Not available yet.");});

			// level_squares events:
			m_levels->on_level_load +=
			[this](const level_id& id){m_gamehandler.load_level(id);};
		}

		void setup_interface()
		{

		}
	};
}

#endif // RJ_CORE_MAIN_MENU_MAIN_MENU_HPP
<commit_msg>main_menu: added menu getters<commit_after>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_CORE_MAIN_MENU_MAIN_MENU_HPP
#define RJ_CORE_MAIN_MENU_MAIN_MENU_HPP

#include "background.hpp"
#include "component_manager.hpp"
#include "items.hpp"
#include "menu_levels.hpp"
#include "menu_start.hpp"
#include "submenu_manager.hpp"
#include "title.hpp"
#include <rectojump/core/game_window.hpp>
#include <rectojump/core/render.hpp>
#include <rectojump/game/background/background_manager.hpp>
#include <rectojump/game/components/player.hpp>
#include <rectojump/game/factory.hpp>
#include <rectojump/global/common.hpp>
#include <rectojump/global/config_settings.hpp>
#include <rectojump/shared/level_manager/level_manager.hpp>
#include <rectojump/shared/data_manager.hpp>
#include <rectojump/shared/utils.hpp>

#include <SFML/Graphics.hpp>

namespace rj
{
	template<typename Game_Handler>
	class main_menu
	{
		Game_Handler& m_gamehandler;
		game_window& m_gamewindow;
		data_manager& m_datamgr;
		level_manager& m_lvmgr;
		background_manager& m_backgroundmgr;

		sf::Font m_font{m_datamgr.get_as<sf::Font>("Fipps-Regular.otf")};
		const vec2f m_center{/*settings::get_window_size<vec2f>() / 2.f*/}; // TODO: clang frontend crash
		const sf::Color m_def_fontcolor{to_rgb("#797979") /*"#797979"_rgb*/}; // TODO: QTC dont supports that custom literals yet
		const sf::Color m_act_fontcolor{to_rgb("#f15ede") /*"#f15ede"_rgb*/};

		// background
		background<main_menu<Game_Handler>> m_background{*this};

		// components (menus)
		component_manager<main_menu<Game_Handler>> m_componentmgr{*this};
		comp_ptr<menu_start<main_menu<Game_Handler>>> m_start{m_componentmgr.template create_comp<menu_start<main_menu<Game_Handler>>, menu_state::menu_start>()};
		comp_ptr<menu_levels<main_menu<Game_Handler>>> m_levels{m_componentmgr.template create_comp<menu_levels<main_menu<Game_Handler>>, menu_state::menu_levels>()};

		// other components (not menus)
		title m_title;

		// menu state
		submenu_manager<menu_state, menu_state::menu_start> m_submenumgr;
		mlk::event_delegates<menu_state> m_on_menu_switch;

	public:
		main_menu(Game_Handler& gh) :
			m_gamehandler{gh},
			m_gamewindow{gh.get_gamewindow()},
			m_datamgr{gh.get_datamgr()},
			m_lvmgr{gh.get_levelmgr()},
			m_backgroundmgr{gh.get_backgroundmgr()},
			m_center{settings::get_window_size<vec2f>() / 2.f},
			m_title{m_gamehandler.get_render(), m_font, m_center}
		{this->init();}

		void update(dur duration)
		{
			m_submenumgr.update_current_state(duration);
			m_background.update(duration);
			m_title.update(duration);
		}

		void render()
		{
			m_background.render();
			m_submenumgr.render_current_state();
			m_title.render();
		}

		void on_key_up()
		{m_submenumgr.event_up();}

		void on_key_down()
		{m_submenumgr.event_down();}

		void on_key_backspace()
		{
			// activate prev state from submenu
			auto ptr(m_componentmgr.get_comp_from_type(m_submenumgr.get_current_state()));
			if(ptr != nullptr)
				if(ptr->is_accessing_submenu())
				{
					ptr->on_key_backspace();
					return;
				}

			// activate prev state
			this->do_menu_switch_back();
		}

		bool is_active(menu_state s) const noexcept
		{return m_submenumgr.get_current_state() == s;}

		void call_current_itemevent()
		{m_submenumgr.event_current();}

		void do_menu_switch(menu_state s)
		{
			m_submenumgr.switch_state(s);
			m_on_menu_switch[s]();
		}

		void do_menu_switch_back()
		{
			m_submenumgr.activate_prev_state();
			m_on_menu_switch[m_submenumgr.get_current_state()]();
		}

		auto get_gamehandler() noexcept
		-> decltype(m_gamehandler)&
		{return m_gamehandler;}

		auto get_menu_start() noexcept
		-> decltype(m_start)&
		{return m_start;}

		auto get_menu_levels() noexcept
		-> decltype(m_levels)&
		{return m_levels;}

		const sf::Font& get_font() const noexcept
		{return m_font;}

		const vec2f& get_center() const noexcept
		{return m_center;}

		const sf::Color& get_act_fontcolor() const noexcept
		{return m_act_fontcolor;}

		const sf::Color& get_def_fontcolor() const noexcept
		{return m_def_fontcolor;}

	private:
		void init()
		{
			m_submenumgr.add_menu(menu_state::menu_start, m_start);
			m_submenumgr.add_menu(menu_state::menu_levels, m_levels);

			this->setup_events();
			this->setup_interface();
		}

		void setup_events()
		{
			// menu switch
			m_on_menu_switch[menu_state::menu_levels] +=
			[this]{m_title.set_text("Levels");};

			m_on_menu_switch[menu_state::menu_start] +=
			[this]{m_title.set_text("Recto Jump");};

			// start menu:
			// item events:
			m_start->get_items().on_event("play",
			[this]{this->do_menu_switch(menu_state::menu_levels);});

			m_start->get_items().on_event("editor",
			[this]{});

			m_start->get_items().on_event("quit",
			[this]{m_gamewindow.stop();});

			// level menu:
			// item events:
			m_levels->get_items().on_event("lv_download",
			[this]{m_gamehandler.get_popupmgr().create_popup("Not available yet.");});

			// level_squares events:
			m_levels->on_level_load +=
			[this](const level_id& id){m_gamehandler.load_level(id);};
		}

		void setup_interface()
		{

		}
	};
}

#endif // RJ_CORE_MAIN_MENU_MAIN_MENU_HPP
<|endoftext|>