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

#include "undoopt.hxx"

#ifndef INCLUDED_RTL_INSTANCE_HXX
#include "rtl/instance.hxx"
#endif
#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SFXSMPLHINT_HXX
#include <smplhint.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#include <osl/mutex.hxx>
#include <rtl/logfile.hxx>
#include "itemholder2.hxx"

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

static SvtUndoOptions_Impl* pOptions = NULL;
static sal_Int32           nRefCount = 0;

#define STEPS 0

class SvtUndoOptions_Impl : public utl::ConfigItem, public SfxBroadcaster
{
    sal_Int32               nUndoCount;
    Sequence< rtl::OUString > m_aPropertyNames;

public:
                            SvtUndoOptions_Impl();

    virtual void            Notify( const com::sun::star::uno::Sequence< rtl::OUString >& aPropertyNames );
    virtual void            Commit();
    void                    Load();

    void                    SetUndoCount( sal_Int32 n ) { nUndoCount = n; SetModified();  }
    sal_Int32               GetUndoCount() const        { return nUndoCount; }
};

// -----------------------------------------------------------------------

SvtUndoOptions_Impl::SvtUndoOptions_Impl()
    : ConfigItem( OUString::createFromAscii("Office.Common/Undo") )
    , nUndoCount( 20 )
{
    Load();
}

void SvtUndoOptions_Impl::Commit()
{
    OUString* pNames = m_aPropertyNames.getArray();
    Sequence< Any > aValues( m_aPropertyNames.getLength() );
    Any* pValues = aValues.getArray();
    for ( int nProp = 0; nProp < m_aPropertyNames.getLength(); nProp++ )
    {
        switch ( nProp )
        {
            case STEPS :
                pValues[nProp] <<= nUndoCount;
                break;
            default:
                DBG_ERRORFILE( "invalid index to save a path" );
        }
    }

    PutProperties( m_aPropertyNames, aValues );
    //broadcast changes
    Broadcast(SfxSimpleHint(SFX_HINT_UNDO_OPTIONS_CHANGED));
}

// -----------------------------------------------------------------------
void SvtUndoOptions_Impl::Load()
{
    if(!m_aPropertyNames.getLength())
    {
        static const char* aPropNames[] =
        {
            "Steps",
        };

        const int nCount = sizeof( aPropNames ) / sizeof( const char* );
        m_aPropertyNames.realloc(nCount);
        OUString* pNames = m_aPropertyNames.getArray();
        for ( int i = 0; i < nCount; i++ )
            pNames[i] = OUString::createFromAscii( aPropNames[i] );
        EnableNotification( m_aPropertyNames );
    }

    Sequence< Any > aValues = GetProperties( m_aPropertyNames );
    const Any* pValues = aValues.getConstArray();
    DBG_ASSERT( aValues.getLength() == m_aPropertyNames.getLength(), "GetProperties failed" );
    if ( aValues.getLength() == m_aPropertyNames.getLength() )
    {
        for ( int nProp = 0; nProp < m_aPropertyNames.getLength(); nProp++ )
        {
            DBG_ASSERT( pValues[nProp].hasValue(), "property value missing" );
            if ( pValues[nProp].hasValue() )
            {
                switch ( nProp )
                {
                    case STEPS :
                    {
                        sal_Int32 nTemp;
                        if ( pValues[nProp] >>= nTemp )
                            nUndoCount = nTemp;
                        else
                            DBG_ERROR( "Wrong Type!" );
                        break;
                    }

                    default:
                        DBG_ERROR( "Wrong Type!" );
                        break;
                }
            }
        }
    }
}
// -----------------------------------------------------------------------
void SvtUndoOptions_Impl::Notify( const Sequence<rtl::OUString>& aPropertyNames )
{
    Load();
    //broadcast changes
    Broadcast(SfxSimpleHint(SFX_HINT_UNDO_OPTIONS_CHANGED));
}

// -----------------------------------------------------------------------
namespace
{
    class LocalSingleton : public rtl::Static< osl::Mutex, LocalSingleton >
    {
    };
}

// -----------------------------------------------------------------------
SvtUndoOptions::SvtUndoOptions()
{
    // Global access, must be guarded (multithreading)
    ::osl::MutexGuard aGuard( LocalSingleton::get() );
    if ( !pOptions )
    {
        RTL_LOGFILE_CONTEXT(aLog, "svtools (???) ::SvtUndoOptions_Impl::ctor()");
        pOptions = new SvtUndoOptions_Impl;

        ItemHolder2* pHolder = ItemHolder2::getGlobalItemHolder();
        pHolder->holdConfigItem(E_UNDOOPTIONS);
    }
    ++nRefCount;
    pImp = pOptions;
    StartListening(*pImp);
}

// -----------------------------------------------------------------------

SvtUndoOptions::~SvtUndoOptions()
{
    // Global access, must be guarded (multithreading)
    ::osl::MutexGuard aGuard( LocalSingleton::get() );
    EndListening(*pImp);
    if ( !--nRefCount )
    {
        if ( pOptions->IsModified() )
            pOptions->Commit();
        DELETEZ( pOptions );
    }
}

void SvtUndoOptions::SetUndoCount( sal_Int32 n )
{
    pImp->SetUndoCount( n );
}

sal_Int32 SvtUndoOptions::GetUndoCount() const
{
    return pImp->GetUndoCount();
}

void SvtUndoOptions::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
    vos::OGuard aVclGuard( Application::GetSolarMutex() );
    Broadcast( rHint );
}

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

#include "undoopt.hxx"

#ifndef INCLUDED_RTL_INSTANCE_HXX
#include "rtl/instance.hxx"
#endif
#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SFXSMPLHINT_HXX
#include <smplhint.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#include <osl/mutex.hxx>
#include <rtl/logfile.hxx>
#include "itemholder2.hxx"

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

static SvtUndoOptions_Impl* pOptions = NULL;
static sal_Int32           nRefCount = 0;

#define STEPS 0

class SvtUndoOptions_Impl : public utl::ConfigItem, public SfxBroadcaster
{
    sal_Int32               nUndoCount;
    Sequence< rtl::OUString > m_aPropertyNames;

public:
                            SvtUndoOptions_Impl();

    virtual void            Notify( const com::sun::star::uno::Sequence< rtl::OUString >& aPropertyNames );
    virtual void            Commit();
    void                    Load();

    void                    SetUndoCount( sal_Int32 n ) { nUndoCount = n; SetModified();  }
    sal_Int32               GetUndoCount() const        { return nUndoCount; }
};

// -----------------------------------------------------------------------

SvtUndoOptions_Impl::SvtUndoOptions_Impl()
    : ConfigItem( OUString::createFromAscii("Office.Common/Undo") )
    , nUndoCount( 20 )
{
    Load();
}

void SvtUndoOptions_Impl::Commit()
{
    OUString* pNames = m_aPropertyNames.getArray();
    Sequence< Any > aValues( m_aPropertyNames.getLength() );
    Any* pValues = aValues.getArray();
    for ( int nProp = 0; nProp < m_aPropertyNames.getLength(); nProp++ )
    {
        switch ( nProp )
        {
            case STEPS :
                pValues[nProp] <<= nUndoCount;
                break;
            default:
                DBG_ERRORFILE( "invalid index to save a path" );
        }
    }

    PutProperties( m_aPropertyNames, aValues );
    //broadcast changes
    Broadcast(SfxSimpleHint(SFX_HINT_UNDO_OPTIONS_CHANGED));
}

// -----------------------------------------------------------------------
void SvtUndoOptions_Impl::Load()
{
    if(!m_aPropertyNames.getLength())
    {
        static const char* aPropNames[] =
        {
            "Steps",
        };

        const int nCount = sizeof( aPropNames ) / sizeof( const char* );
        m_aPropertyNames.realloc(nCount);
        OUString* pNames = m_aPropertyNames.getArray();
        for ( int i = 0; i < nCount; i++ )
            pNames[i] = OUString::createFromAscii( aPropNames[i] );
        EnableNotification( m_aPropertyNames );
    }

    Sequence< Any > aValues = GetProperties( m_aPropertyNames );
    const Any* pValues = aValues.getConstArray();
    DBG_ASSERT( aValues.getLength() == m_aPropertyNames.getLength(), "GetProperties failed" );
    if ( aValues.getLength() == m_aPropertyNames.getLength() )
    {
        for ( int nProp = 0; nProp < m_aPropertyNames.getLength(); nProp++ )
        {
            DBG_ASSERT( pValues[nProp].hasValue(), "property value missing" );
            if ( pValues[nProp].hasValue() )
            {
                switch ( nProp )
                {
                    case STEPS :
                    {
                        sal_Int32 nTemp;
                        if ( pValues[nProp] >>= nTemp )
                            nUndoCount = nTemp;
                        else
                            DBG_ERROR( "Wrong Type!" );
                        break;
                    }

                    default:
                        DBG_ERROR( "Wrong Type!" );
                        break;
                }
            }
        }
    }
}
// -----------------------------------------------------------------------
void SvtUndoOptions_Impl::Notify( const Sequence<rtl::OUString>& aPropertyNames )
{
    Load();
    //broadcast changes
    Broadcast(SfxSimpleHint(SFX_HINT_UNDO_OPTIONS_CHANGED));
}

// -----------------------------------------------------------------------
namespace
{
    class LocalSingleton : public rtl::Static< osl::Mutex, LocalSingleton >
    {
    };
}

// -----------------------------------------------------------------------
SvtUndoOptions::SvtUndoOptions()
{
    // Global access, must be guarded (multithreading)
    ::osl::MutexGuard aGuard( LocalSingleton::get() );
    if ( !pOptions )
    {
        RTL_LOGFILE_CONTEXT(aLog, "svtools (???) ::SvtUndoOptions_Impl::ctor()");
        pOptions = new SvtUndoOptions_Impl;

        ItemHolder2* pHolder = ItemHolder2::getGlobalItemHolder();
        pHolder->holdConfigItem(E_UNDOOPTIONS);
    }
    ++nRefCount;
    pImp = pOptions;
    StartListening(*pImp);
}

// -----------------------------------------------------------------------

SvtUndoOptions::~SvtUndoOptions()
{
    // Global access, must be guarded (multithreading)
    ::osl::MutexGuard aGuard( LocalSingleton::get() );
    EndListening(*pImp);
    if ( !--nRefCount )
    {
        if ( pOptions->IsModified() )
            pOptions->Commit();
        DELETEZ( pOptions );
    }
}

void SvtUndoOptions::SetUndoCount( sal_Int32 n )
{
    pImp->SetUndoCount( n );
}

sal_Int32 SvtUndoOptions::GetUndoCount() const
{
    return pImp->GetUndoCount();
}

void SvtUndoOptions::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
    vos::OGuard aVclGuard( Application::GetSolarMutex() );
    Broadcast( rHint );
}

<|endoftext|>


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

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

 #include <limits.h> // USHRT_MAX

 #ifndef _COM_SUN_STAR_SEQUENCE_HXX_
 #include <com/sun/star/uno/Sequence.hxx>
 #endif

 class SwRedline;
 class SwRedlineTbl;
 class SwPaM;
 struct SwPosition;
 class SwStartNode;
 class SwNode;
 class String;

 /** IDocumentRedlineAccess
 */
 class IDocumentRedlineAccess
 {
 public:
    typedef int RedlineMode_t;

    static const RedlineMode_t REDLINE_NONE = 0;// no RedlineMode
    static const RedlineMode_t REDLINE_ON = 0x01;// RedlineMode on
    static const RedlineMode_t REDLINE_IGNORE = 0x02;// ignore Redlines
    static const RedlineMode_t REDLINE_SHOW_INSERT = 0x10;// show all inserts
    static const RedlineMode_t REDLINE_SHOW_DELETE = 0x20;// show all delets
    static const RedlineMode_t REDLINE_SHOW_MASK = REDLINE_SHOW_INSERT | REDLINE_SHOW_DELETE;

    // fuer die interne Verwaltung:
    // die originalen Redlines inclusive des Contents entfernen
    // (ClipBoard/Textbausteine)
    static const RedlineMode_t REDLINE_DELETE_REDLINES = 0x100;
    // beim Loeschen innerhalb ein RedlineObjectes, waehrend des Appends,
    // das DeleteRedline ignorieren
    static const RedlineMode_t REDLINE_IGNOREDELETE_REDLINES = 0x200;
    // don't combine any readlines. This flags is may only used in the Undo.
    static const RedlineMode_t REDLINE_DONTCOMBINE_REDLINES = 0x400;

    typedef int RedlineType_t;

    // die RedlineTypen gehen von 0 bis 127
    static const RedlineType_t REDLINE_INSERT = 0x0;// Inhalt wurde eingefuegt
    static const RedlineType_t REDLINE_DELETE = 0x1;// Inhalt wurde geloescht
    static const RedlineType_t REDLINE_FORMAT = 0x2;// Attributierung wurde angewendet
    static const RedlineType_t REDLINE_TABLE = 0x3;// TabellenStruktur wurde veraendert
    static const RedlineType_t REDLINE_FMTCOLL = 0x4;// FormatVorlage wurde veraendert (Autoformat!)

    // ab 128 koennen Flags hineinverodert werden
    static const RedlineType_t REDLINE_NO_FLAG_MASK = 0x7F;
    static const RedlineType_t REDLINE_FLAG_MASK = 0xFF80;
    static const RedlineType_t REDLINE_FORM_AUTOFMT = 0x80;// kann als Flag im RedlineType stehen

    // Static helper functions
public:
    static int IsShowChanges(const USHORT eM)
    { return (REDLINE_SHOW_INSERT | REDLINE_SHOW_DELETE) == (eM & REDLINE_SHOW_MASK); }

    static int IsHideChanges(const USHORT eM)
    { return REDLINE_SHOW_INSERT == (eM & REDLINE_SHOW_MASK); }

    static int IsShowOriginal(const USHORT eM)
    { return REDLINE_SHOW_DELETE == (eM & REDLINE_SHOW_MASK); }

    static int IsRedlineOn(const USHORT eM)
    { return REDLINE_ON == (eM & (REDLINE_ON | REDLINE_IGNORE )); }

 public:

    /*************************************************
        Query
    *************************************************/

    /** Query the currently set redline mode

        @returns
        the currently set redline mode
    */
     virtual RedlineMode_t GetRedlineMode() const = 0;

    /** Set a new redline mode.

        @param eMode
        [in] the new redline mode.
    */
    virtual void SetRedlineMode_intern(/*[in]*/RedlineMode_t eMode) = 0;

    /** Set a new redline mode.

        @param eMode
        [in] the new redline mode.
    */
    virtual void SetRedlineMode(/*[in]*/RedlineMode_t eMode) = 0;

    /** Query if redlining is on.

        @returns
        </TRUE> if redlining is on </FALSE> otherwise
    */
    virtual bool IsRedlineOn() const = 0;

    /**
    */
    virtual bool IsIgnoreRedline() const = 0;

    /**
    */
    virtual const SwRedlineTbl& GetRedlineTbl() const = 0;

   /*
    */
   virtual bool IsInRedlines(const SwNode& rNode) const = 0;

    /***************************************************
        Manipulation
     ***************************************************/

    /** Append a new redline

        @param pPtr

        @param bCallDelete

        @returns
    */
    virtual bool AppendRedline(/*[in]*/SwRedline* pPtr, /*[in]*/bool bCallDelete) = 0;

    /**
    */
    virtual bool SplitRedline(/*[in]*/const SwPaM& rPam) = 0;

    /**
    */
    virtual bool DeleteRedline(
        /*[in]*/const SwPaM& rPam,
        /*[in]*/bool bSaveInUndo,
        /*[in]*/sal_uInt16 nDelType) = 0;

    /**
    */
    virtual bool DeleteRedline(
        /*[in]*/const SwStartNode& rSection,
        /*[in]*/bool bSaveInUndo,
        /*[in]*/sal_uInt16 nDelType) = 0;

    /**
    */
    virtual sal_uInt16 GetRedlinePos(
        /*[in]*/const SwNode& rNode,
        /*[in]*/sal_uInt16 nType) const = 0;

    virtual void CompressRedlines() = 0;

    /**
    */
    virtual const SwRedline* GetRedline(
        /*[in]*/const SwPosition& rPos,
        /*[in]*/sal_uInt16* pFndPos) const = 0;

    /**
    */
    virtual bool IsRedlineMove() const = 0;

    /**
    */
    virtual void SetRedlineMove(/*[in]*/bool bFlag) = 0;

    /**
    */
    virtual bool AcceptRedline(/*[in]*/sal_uInt16 nPos, /*[in]*/bool bCallDelete) = 0;

    /**
    */
    virtual bool AcceptRedline(/*[in]*/const SwPaM& rPam, /*[in]*/bool bCallDelete) = 0;

    /**
    */
    virtual bool RejectRedline(/*[in]*/sal_uInt16 nPos, /*[in]*/bool bCallDelete) = 0;

    /**
    */
    virtual bool RejectRedline(/*[in]*/const SwPaM& rPam, /*[in]*/bool bCallDelete) = 0;

    /**
    */
    virtual const SwRedline* SelNextRedline(/*[in]*/SwPaM& rPam) const = 0;

    /**
    */
    virtual const SwRedline* SelPrevRedline(/*[in]*/SwPaM& rPam) const = 0;

    // alle Redline invalidieren, die Darstellung hat sich geaendert
    virtual void UpdateRedlineAttr() = 0;

    // legt gegebenenfalls einen neuen Author an
    virtual sal_uInt16 GetRedlineAuthor() = 0;

    // fuer die Reader usw. - neuen Author in die Tabelle eintragen
    virtual sal_uInt16 InsertRedlineAuthor(const String& rAuthor) = 0;

    // Kommentar am Redline an der Position setzen
    virtual bool SetRedlineComment(
        /*[in]*/const SwPaM& rPam,
        /*[in]*/const String& rComment) = 0;

    /**
    */
    virtual const ::com::sun::star::uno::Sequence <sal_Int8>& GetRedlinePassword() const = 0;

    /**
    */
    virtual void SetRedlinePassword(
        /*[in]*/const ::com::sun::star::uno::Sequence <sal_Int8>& rNewPassword) = 0;

 protected:
     virtual ~IDocumentRedlineAccess() {};
 };

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

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

 #include <limits.h> // USHRT_MAX

 #ifndef _COM_SUN_STAR_SEQUENCE_HXX_
 #include <com/sun/star/uno/Sequence.hxx>
 #endif

 class SwRedline;
 class SwRedlineTbl;
 class SwPaM;
 struct SwPosition;
 class SwStartNode;
 class SwNode;
 class String;

 /** IDocumentRedlineAccess
 */
 class IDocumentRedlineAccess
 {
 public:

   enum RedlineMode_t
   {
       REDLINE_NONE = 0, // no RedlineMode
       REDLINE_ON = 0x01,// RedlineMode on
       REDLINE_IGNORE = 0x02,// ignore Redlines
       REDLINE_SHOW_INSERT = 0x10,// show all inserts
       REDLINE_SHOW_DELETE = 0x20,// show all delets
       REDLINE_SHOW_MASK = REDLINE_SHOW_INSERT | REDLINE_SHOW_DELETE,

       // fuer die interne Verwaltung:
       // die originalen Redlines inclusive des Contents entfernen
       // (ClipBoard/Textbausteine)
       REDLINE_DELETE_REDLINES = 0x100,
       // beim Loeschen innerhalb ein RedlineObjectes, waehrend des Appends,
       // das DeleteRedline ignorieren
       REDLINE_IGNOREDELETE_REDLINES = 0x200,
       // don't combine any readlines. This flags is may only used in the Undo.
      REDLINE_DONTCOMBINE_REDLINES = 0x400
   };

   enum RedlineType_t
   {
     // die RedlineTypen gehen von 0 bis 127
     REDLINE_INSERT = 0x0,// Inhalt wurde eingefuegt
     REDLINE_DELETE = 0x1,// Inhalt wurde geloescht
     REDLINE_FORMAT = 0x2,// Attributierung wurde angewendet
     REDLINE_TABLE = 0x3,// TabellenStruktur wurde veraendert
     REDLINE_FMTCOLL = 0x4,// FormatVorlage wurde veraendert (Autoformat!)

     // ab 128 koennen Flags hineinverodert werden
     REDLINE_NO_FLAG_MASK = 0x7F,
     REDLINE_FLAG_MASK = 0xFF80,
     REDLINE_FORM_AUTOFMT = 0x80// kann als Flag im RedlineType stehen
   };

    // Static helper functions
public:
    static int IsShowChanges(const USHORT eM)
    { return (REDLINE_SHOW_INSERT | REDLINE_SHOW_DELETE) == (eM & REDLINE_SHOW_MASK); }

    static int IsHideChanges(const USHORT eM)
    { return REDLINE_SHOW_INSERT == (eM & REDLINE_SHOW_MASK); }

    static int IsShowOriginal(const USHORT eM)
    { return REDLINE_SHOW_DELETE == (eM & REDLINE_SHOW_MASK); }

    static int IsRedlineOn(const USHORT eM)
    { return REDLINE_ON == (eM & (REDLINE_ON | REDLINE_IGNORE )); }

 public:

    /*************************************************
        Query
    *************************************************/

    /** Query the currently set redline mode

        @returns
        the currently set redline mode
    */
     virtual RedlineMode_t GetRedlineMode() const = 0;

    /** Set a new redline mode.

        @param eMode
        [in] the new redline mode.
    */
    virtual void SetRedlineMode_intern(/*[in]*/RedlineMode_t eMode) = 0;

    /** Set a new redline mode.

        @param eMode
        [in] the new redline mode.
    */
    virtual void SetRedlineMode(/*[in]*/RedlineMode_t eMode) = 0;

    /** Query if redlining is on.

        @returns
        </TRUE> if redlining is on </FALSE> otherwise
    */
    virtual bool IsRedlineOn() const = 0;

    /**
    */
    virtual bool IsIgnoreRedline() const = 0;

    /**
    */
    virtual const SwRedlineTbl& GetRedlineTbl() const = 0;

   /*
    */
   virtual bool IsInRedlines(const SwNode& rNode) const = 0;

    /***************************************************
        Manipulation
     ***************************************************/

    /** Append a new redline

        @param pPtr

        @param bCallDelete

        @returns
    */
    virtual bool AppendRedline(/*[in]*/SwRedline* pPtr, /*[in]*/bool bCallDelete) = 0;

    /**
    */
    virtual bool SplitRedline(/*[in]*/const SwPaM& rPam) = 0;

    /**
    */
    virtual bool DeleteRedline(
        /*[in]*/const SwPaM& rPam,
        /*[in]*/bool bSaveInUndo,
        /*[in]*/sal_uInt16 nDelType) = 0;

    /**
    */
    virtual bool DeleteRedline(
        /*[in]*/const SwStartNode& rSection,
        /*[in]*/bool bSaveInUndo,
        /*[in]*/sal_uInt16 nDelType) = 0;

    /**
    */
    virtual sal_uInt16 GetRedlinePos(
        /*[in]*/const SwNode& rNode,
        /*[in]*/sal_uInt16 nType) const = 0;

    virtual void CompressRedlines() = 0;

    /**
    */
    virtual const SwRedline* GetRedline(
        /*[in]*/const SwPosition& rPos,
        /*[in]*/sal_uInt16* pFndPos) const = 0;

    /**
    */
    virtual bool IsRedlineMove() const = 0;

    /**
    */
    virtual void SetRedlineMove(/*[in]*/bool bFlag) = 0;

    /**
    */
    virtual bool AcceptRedline(/*[in]*/sal_uInt16 nPos, /*[in]*/bool bCallDelete) = 0;

    /**
    */
    virtual bool AcceptRedline(/*[in]*/const SwPaM& rPam, /*[in]*/bool bCallDelete) = 0;

    /**
    */
    virtual bool RejectRedline(/*[in]*/sal_uInt16 nPos, /*[in]*/bool bCallDelete) = 0;

    /**
    */
    virtual bool RejectRedline(/*[in]*/const SwPaM& rPam, /*[in]*/bool bCallDelete) = 0;

    /**
    */
    virtual const SwRedline* SelNextRedline(/*[in]*/SwPaM& rPam) const = 0;

    /**
    */
    virtual const SwRedline* SelPrevRedline(/*[in]*/SwPaM& rPam) const = 0;

    // alle Redline invalidieren, die Darstellung hat sich geaendert
    virtual void UpdateRedlineAttr() = 0;

    // legt gegebenenfalls einen neuen Author an
    virtual sal_uInt16 GetRedlineAuthor() = 0;

    // fuer die Reader usw. - neuen Author in die Tabelle eintragen
    virtual sal_uInt16 InsertRedlineAuthor(const String& rAuthor) = 0;

    // Kommentar am Redline an der Position setzen
    virtual bool SetRedlineComment(
        /*[in]*/const SwPaM& rPam,
        /*[in]*/const String& rComment) = 0;

    /**
    */
    virtual const ::com::sun::star::uno::Sequence <sal_Int8>& GetRedlinePassword() const = 0;

    /**
    */
    virtual void SetRedlinePassword(
        /*[in]*/const ::com::sun::star::uno::Sequence <sal_Int8>& rNewPassword) = 0;

 protected:
     virtual ~IDocumentRedlineAccess() {};
 };

 #endif
<|endoftext|>


<commit_before>#include "object.hpp"
#include "class.hpp"
#include "symbol.hpp"
#include "string.hpp"
#include "../runtime.hpp"
#include "../collector.hpp"
#include "proc.hpp"

namespace Mirb
{
	void Object::generate_hash()
	{
		hash_value = hash_number((size_t)this); // Note: The first two bits are constant
		this->hashed = true;
	}

	value_t Object::allocate(value_t instance_of)
	{
		return auto_cast(Collector::allocate<Object>(auto_cast(instance_of)));
	}

	value_t Object::tap(value_t obj, value_t block)
	{
		OnStack<1> os(obj);

		if(yield(block, 1, &obj) == value_raise)
			return value_raise;

		return obj;
	}

	value_t Object::inspect(value_t obj)
	{
		return call(obj, "to_s");
	}

	value_t Object::to_s(value_t obj)
	{
		value_t c = real_class_of(obj);
		value_t name = get_var(c, Symbol::from_literal("__classname__"));

		if(Value::test(name))
		{
			auto classname = cast<String>(get_var(c, Symbol::from_literal("__classname__")));

			CharArray result = "#<" + classname->string + ":0x" + CharArray::hex((size_t)obj) + ">";

			return result.to_string();
		}
		else
		{
			CharArray result = "#<0x" + CharArray::hex((size_t)obj) + ">";

			return result.to_string();
		}
	}

	value_t Object::dummy()
	{
		return value_nil;
	}

	value_t Object::equal(value_t obj, value_t other)
	{
		return auto_cast(obj == other);
	}

	value_t Object::not_equal(value_t obj, value_t other)
	{
		return auto_cast(obj != other);
	}

	value_t Object::method_not(value_t obj)
	{
		return auto_cast(!Value::test(obj));
	}

	value_t Object::instance_eval(value_t obj, size_t argc, value_t argv[], value_t block)
	{
		if(argc > 1)
			return raise(context->argument_error, "Too many arguments.");

		if(argc == 0)
		{
			if(Value::type(block) == Value::Proc)
				return Proc::call_with_options(obj, current_frame->prev->scope, block, value_nil, 0, nullptr);
			else
				return raise(context->type_error, "Expected block to evaluate");
		}
		else
		{
			if(Value::type(argv[0]) == Value::String)
			{
				CharArray code = cast<String>(argv[0])->string.c_str();

				return eval(obj, Symbol::from_literal("in eval"), current_frame->prev->scope, code.str_ref(), code.str_length(), "(eval)");
			}
			else
				return raise(context->type_error, "Expected string");
		}
	}

	value_t Object::klass(value_t obj)
	{
		return real_class_of(obj);
	}

	value_t Object::extend(value_t obj, size_t argc, value_t argv[])
	{
		OnStack<1> os(obj);

		for(size_t i = 0; i < argc; ++i)
		{
			if(type_error(argv[i], context->module_class))
				return 0;

			if(!call(argv[i], "extend_object", 1, &obj))
				return 0;

			if(!call(argv[i], "extended", 1, &obj))
				return 0;
		}

		return obj;
	}

	void Object::initialize()
	{
		method(context->object_class, "initialize", &dummy);
		context->inspect_method = method<Arg::Self>(context->object_class, "inspect", &inspect);
		method<Arg::Self>(context->object_class, "to_s", &to_s);
		method<Arg::Self>(context->object_class, "class", &klass);
		method<Arg::Self>(context->object_class, "freeze", &dummy);
		method<Arg::Self>(context->object_class, "frozen?", &dummy);
		method<Arg::Self, Arg::Count, Arg::Values>(context->object_class, "extend", &extend);
		method<Arg::Self, Arg::Block>(context->object_class, "tap", &tap);
		method<Arg::Self, Arg::Value>(context->object_class, "equal?", &equal);
		method<Arg::Self, Arg::Value>(context->object_class, "eql?", &equal);
		method<Arg::Self, Arg::Value>(context->object_class, "==", &equal);
		method<Arg::Self, Arg::Value>(context->object_class, "===", &equal);
		method<Arg::Self, Arg::Value>(context->object_class, "!=", &not_equal);
		method<Arg::Self>(context->object_class, "!", &method_not);
		method<Arg::Self, Arg::Count, Arg::Values, Arg::Block>(context->object_class, "instance_eval", &instance_eval);

		singleton_method<Arg::Self>(context->object_class, "allocate", &allocate);
	}
};

<commit_msg>Added dummy object id functions.<commit_after>#include "object.hpp"
#include "class.hpp"
#include "symbol.hpp"
#include "string.hpp"
#include "../runtime.hpp"
#include "../collector.hpp"
#include "proc.hpp"
#include "fixnum.hpp"

namespace Mirb
{
	void Object::generate_hash()
	{
		hash_value = hash_number((size_t)this); // Note: The first two bits are constant
		this->hashed = true;
	}

	value_t Object::allocate(value_t instance_of)
	{
		return auto_cast(Collector::allocate<Object>(auto_cast(instance_of)));
	}

	value_t Object::tap(value_t obj, value_t block)
	{
		OnStack<1> os(obj);

		if(yield(block, 1, &obj) == value_raise)
			return value_raise;

		return obj;
	}

	value_t Object::inspect(value_t obj)
	{
		return call(obj, "to_s");
	}

	value_t Object::to_s(value_t obj)
	{
		value_t c = real_class_of(obj);
		value_t name = get_var(c, Symbol::from_literal("__classname__"));

		if(Value::test(name))
		{
			auto classname = cast<String>(get_var(c, Symbol::from_literal("__classname__")));

			CharArray result = "#<" + classname->string + ":0x" + CharArray::hex((size_t)obj) + ">";

			return result.to_string();
		}
		else
		{
			CharArray result = "#<0x" + CharArray::hex((size_t)obj) + ">";

			return result.to_string();
		}
	}

	value_t Object::dummy()
	{
		return value_nil;
	}

	value_t Object::equal(value_t obj, value_t other)
	{
		return auto_cast(obj == other);
	}

	value_t Object::not_equal(value_t obj, value_t other)
	{
		return auto_cast(obj != other);
	}

	value_t Object::method_not(value_t obj)
	{
		return auto_cast(!Value::test(obj));
	}

	value_t Object::instance_eval(value_t obj, size_t argc, value_t argv[], value_t block)
	{
		if(argc > 1)
			return raise(context->argument_error, "Too many arguments.");

		if(argc == 0)
		{
			if(Value::type(block) == Value::Proc)
				return Proc::call_with_options(obj, current_frame->prev->scope, block, value_nil, 0, nullptr);
			else
				return raise(context->type_error, "Expected block to evaluate");
		}
		else
		{
			if(Value::type(argv[0]) == Value::String)
			{
				CharArray code = cast<String>(argv[0])->string.c_str();

				return eval(obj, Symbol::from_literal("in eval"), current_frame->prev->scope, code.str_ref(), code.str_length(), "(eval)");
			}
			else
				return raise(context->type_error, "Expected string");
		}
	}

	value_t Object::klass(value_t obj)
	{
		return real_class_of(obj);
	}

	value_t Object::extend(value_t obj, size_t argc, value_t argv[])
	{
		OnStack<1> os(obj);

		for(size_t i = 0; i < argc; ++i)
		{
			if(type_error(argv[i], context->module_class))
				return 0;

			if(!call(argv[i], "extend_object", 1, &obj))
				return 0;

			if(!call(argv[i], "extended", 1, &obj))
				return 0;
		}

		return obj;
	}

	value_t object_id(value_t obj)
	{
		return Fixnum::from_size_t(Value::hash(obj)); // TODO: Make a proper object_id
	}

	void Object::initialize()
	{
		method<Arg::Self>(context->object_class, "object_id", &object_id);
		method<Arg::Self>(context->object_class, "__id__", &object_id);

		method(context->object_class, "initialize", &dummy);
		context->inspect_method = method<Arg::Self>(context->object_class, "inspect", &inspect);
		method<Arg::Self>(context->object_class, "to_s", &to_s);
		method<Arg::Self>(context->object_class, "class", &klass);
		method<Arg::Self>(context->object_class, "freeze", &dummy);
		method<Arg::Self>(context->object_class, "frozen?", &dummy);
		method<Arg::Self, Arg::Count, Arg::Values>(context->object_class, "extend", &extend);
		method<Arg::Self, Arg::Block>(context->object_class, "tap", &tap);
		method<Arg::Self, Arg::Value>(context->object_class, "equal?", &equal);
		method<Arg::Self, Arg::Value>(context->object_class, "eql?", &equal);
		method<Arg::Self, Arg::Value>(context->object_class, "==", &equal);
		method<Arg::Self, Arg::Value>(context->object_class, "===", &equal);
		method<Arg::Self, Arg::Value>(context->object_class, "!=", &not_equal);
		method<Arg::Self>(context->object_class, "!", &method_not);
		method<Arg::Self, Arg::Count, Arg::Values, Arg::Block>(context->object_class, "instance_eval", &instance_eval);

		singleton_method<Arg::Self>(context->object_class, "allocate", &allocate);
	}
};

<|endoftext|>


<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
 *
 * This 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.  See file COPYING.
 *
 */

#include "libceph.h"
#include <iostream>

using namespace std;

int main(int argc, const char **argv)
{
  if (ceph_initialize(argc, argv) < 0) {
    cerr << "error initializing\n" << endl;
    return(1);
  }
  cout << "Successfully initialized Ceph!" << std::endl;

  if(ceph_mount() < 0) {
    cerr << "error mounting\n" << endl;
    return(1);
  }
  cout << "Successfully mounted Ceph!" << std::endl;

  ceph_deinitialize();
  cout << "Successfully deinitialized Ceph!" << std::endl;

  return 0;
}
<commit_msg>testceph: Clarify use of endl so it's non-ambiguous when the includes change.<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
 *
 * This 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.  See file COPYING.
 *
 */

#include "libceph.h"
#include <iostream>

using namespace std;

int main(int argc, const char **argv)
{
  if (ceph_initialize(argc, argv) < 0) {
    cerr << "error initializing\n" << std::endl;
    return(1);
  }
  cout << "Successfully initialized Ceph!" << std::endl;

  if(ceph_mount() < 0) {
    cerr << "error mounting\n" << std::endl;
    return(1);
  }
  cout << "Successfully mounted Ceph!" << std::endl;

  ceph_deinitialize();
  cout << "Successfully deinitialized Ceph!" << std::endl;

  return 0;
}
<|endoftext|>


<commit_before><commit_msg>WaE: implicit conversion of literal of type 'const char *' to 'bool'<commit_after><|endoftext|>


<commit_before>#include "MazeInterface.h"

#include "Logging.h"
#include "SimUtilities.h"

namespace sim {

MazeInterface::MazeInterface(std::vector<std::vector<BasicTile>>* basicMaze) : m_basicMaze(basicMaze) {
}

void MazeInterface::debug(const std::string& str) {
    Logging::getMouseLogger()->debug(str);
}

void MazeInterface::info(const std::string& str) {
    Logging::getMouseLogger()->info(str);
}

void MazeInterface::warn(const std::string& str) {
    Logging::getMouseLogger()->warn(str);
}

void MazeInterface::error(const std::string& str) {
    Logging::getMouseLogger()->error(str);
}

void MazeInterface::quit() {
    SimUtilities::quit();
}

double MazeInterface::getRandom() {
    return SimUtilities::getRandom();
}

void MazeInterface::setWall(int x, int y, char direction, bool wallExists) {

    if (x < 0 || getWidth() <= x || y < 0 || getHeight() <= y) {
        L()->warn(
            "The generated maze width and height values are %v and %v, respectively."
            " There is no tile at position (%v, %v), and thus you cannot set its wall value.",
            getWidth(), getHeight(), x, y);
        return;
    }

    if (!SimUtilities::mapContains(CHAR_TO_DIRECTION, direction)) {
        L()->warn("The character '%v' is not mapped to a valid direction.", direction);
        return;
    }
    m_basicMaze->at(x).at(y).walls.at(CHAR_TO_DIRECTION.at(direction)) = wallExists;
}

int MazeInterface::getWidth() {
    return m_basicMaze->size();
}

int MazeInterface::getHeight() {
    return (m_basicMaze->size() > 0 ? m_basicMaze->at(0).size() : 0);
}

} // namespace sim
<commit_msg>Fix logger instance bug<commit_after>#include "MazeInterface.h"

#include "Logging.h"
#include "SimUtilities.h"

namespace sim {

MazeInterface::MazeInterface(std::vector<std::vector<BasicTile>>* basicMaze) : m_basicMaze(basicMaze) {
}

void MazeInterface::debug(const std::string& str) {
    Logging::getMazeLogger()->debug(str);
}

void MazeInterface::info(const std::string& str) {
    Logging::getMazeLogger()->info(str);
}

void MazeInterface::warn(const std::string& str) {
    Logging::getMazeLogger()->warn(str);
}

void MazeInterface::error(const std::string& str) {
    Logging::getMazeLogger()->error(str);
}

void MazeInterface::quit() {
    SimUtilities::quit();
}

double MazeInterface::getRandom() {
    return SimUtilities::getRandom();
}

void MazeInterface::setWall(int x, int y, char direction, bool wallExists) {

    if (x < 0 || getWidth() <= x || y < 0 || getHeight() <= y) {
        L()->warn(
            "The generated maze width and height values are %v and %v, respectively."
            " There is no tile at position (%v, %v), and thus you cannot set its wall value.",
            getWidth(), getHeight(), x, y);
        return;
    }

    if (!SimUtilities::mapContains(CHAR_TO_DIRECTION, direction)) {
        L()->warn("The character '%v' is not mapped to a valid direction.", direction);
        return;
    }
    m_basicMaze->at(x).at(y).walls.at(CHAR_TO_DIRECTION.at(direction)) = wallExists;
}

int MazeInterface::getWidth() {
    return m_basicMaze->size();
}

int MazeInterface::getHeight() {
    return (m_basicMaze->size() > 0 ? m_basicMaze->at(0).size() : 0);
}

} // namespace sim
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/random.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/VFS.h"
#include "fnord-rpc/ServerGroup.h"
#include "fnord-rpc/RPC.h"
#include "fnord-rpc/RPCClient.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-json/json.h"
#include "fnord-json/jsonrpc.h"
#include "fnord-http/httprouter.h"
#include "fnord-http/httpserver.h"
#include "fnord-http/VFSFileServlet.h"
#include "fnord-feeds/FeedService.h"
#include "fnord-feeds/RemoteFeedFactory.h"
#include "fnord-feeds/RemoteFeedReader.h"
#include "fnord-base/stats/statsdagent.h"
#include "fnord-sstable/SSTableServlet.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "reports/AnalyticsServlet.h"
#include "reports/CTRByPageServlet.h"
#include "reports/CTRStatsServlet.h"
#include "analytics/CTRByPositionRollup.h"
#include "analytics/AnalyticsQueryEngine.h"

using namespace fnord;

int main(int argc, const char** argv) {
  fnord::Application::init();
  fnord::Application::logToStderr();

  fnord::cli::FlagParser flags;

  flags.defineFlag(
      "http_port",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "8000",
      "Start the public http server on this port",
      "<port>");

  flags.defineFlag(
      "artifacts",
      cli::FlagParser::T_STRING,
      true,
      NULL,
      NULL,
      "artifacts path",
      "<path>");

  flags.defineFlag(
      "loglevel",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.parseArgv(argc, argv);

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  WhitelistVFS vfs;

  /* start http server */
  fnord::thread::EventLoop ev;
  fnord::http::HTTPRouter http_router;
  fnord::http::HTTPServer http_server(&http_router, &ev);
  http_server.listen(flags.getInt("http_port"));

  /* sstable servlet */
  sstable::SSTableServlet sstable_servlet("/sstable", &vfs);
  http_router.addRouteByPrefixMatch("/sstable", &sstable_servlet);

  /* file servlet */
  http::VFSFileServlet file_servlet("/file", &vfs);
  http_router.addRouteByPrefixMatch("/file", &file_servlet);

  /* add all files to whitelist vfs */
  auto dir = flags.getString("artifacts");
  FileUtil::ls(dir, [&vfs, &dir] (const String& file) -> bool {
    vfs.registerFile(file, FileUtil::joinPaths(dir, file));
    fnord::logInfo("cm.reportserver", "[VFS] Adding file: $0", file);
    return true;
  });

  /* analytics */
  cm::AnalyticsQueryEngine analytics(8, &vfs);
  cm::AnalyticsServlet analytics_servlet(&analytics);
  http_router.addRouteByPrefixMatch("/analytics", &analytics_servlet);

  analytics.registerQueryFactory("ctr_by_position", [] (
      const cm::AnalyticsQuery& query,
      const cm::AnalyticsQuery::SubQueryParams params,
      const Vector<RefPtr<cm::TrafficSegment>>& segments,
      cm::AnalyticsTableScan* scan) {
    return new cm::CTRByPositionRollup(scan, segments);
  });

  ev.run();
  return 0;
}

<commit_msg>run analytics servlet on threadpool<commit_after>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/random.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/VFS.h"
#include "fnord-rpc/ServerGroup.h"
#include "fnord-rpc/RPC.h"
#include "fnord-rpc/RPCClient.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-json/json.h"
#include "fnord-json/jsonrpc.h"
#include "fnord-http/httprouter.h"
#include "fnord-http/httpserver.h"
#include "fnord-http/VFSFileServlet.h"
#include "fnord-feeds/FeedService.h"
#include "fnord-feeds/RemoteFeedFactory.h"
#include "fnord-feeds/RemoteFeedReader.h"
#include "fnord-base/stats/statsdagent.h"
#include "fnord-sstable/SSTableServlet.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "reports/AnalyticsServlet.h"
#include "reports/CTRByPageServlet.h"
#include "reports/CTRStatsServlet.h"
#include "analytics/CTRByPositionRollup.h"
#include "analytics/AnalyticsQueryEngine.h"

using namespace fnord;

int main(int argc, const char** argv) {
  fnord::Application::init();
  fnord::Application::logToStderr();

  fnord::cli::FlagParser flags;

  flags.defineFlag(
      "http_port",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "8000",
      "Start the public http server on this port",
      "<port>");

  flags.defineFlag(
      "artifacts",
      cli::FlagParser::T_STRING,
      true,
      NULL,
      NULL,
      "artifacts path",
      "<path>");

  flags.defineFlag(
      "loglevel",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.parseArgv(argc, argv);

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  WhitelistVFS vfs;

  /* start http server */
  fnord::thread::EventLoop ev;
  fnord::thread::ThreadPool tpool;
  fnord::http::HTTPRouter http_router;
  fnord::http::HTTPServer http_server(&http_router, &ev);
  http_server.listen(flags.getInt("http_port"));

  /* sstable servlet */
  sstable::SSTableServlet sstable_servlet("/sstable", &vfs);
  http_router.addRouteByPrefixMatch("/sstable", &sstable_servlet);

  /* file servlet */
  http::VFSFileServlet file_servlet("/file", &vfs);
  http_router.addRouteByPrefixMatch("/file", &file_servlet);

  /* add all files to whitelist vfs */
  auto dir = flags.getString("artifacts");
  FileUtil::ls(dir, [&vfs, &dir] (const String& file) -> bool {
    vfs.registerFile(file, FileUtil::joinPaths(dir, file));
    fnord::logInfo("cm.reportserver", "[VFS] Adding file: $0", file);
    return true;
  });

  /* analytics */
  cm::AnalyticsQueryEngine analytics(8, &vfs);
  cm::AnalyticsServlet analytics_servlet(&analytics);
  http_router.addRouteByPrefixMatch("/analytics", &analytics_servlet, &tpool);

  analytics.registerQueryFactory("ctr_by_position", [] (
      const cm::AnalyticsQuery& query,
      const cm::AnalyticsQuery::SubQueryParams params,
      const Vector<RefPtr<cm::TrafficSegment>>& segments,
      cm::AnalyticsTableScan* scan) {
    return new cm::CTRByPositionRollup(scan, segments);
  });

  ev.run();
  return 0;
}

<|endoftext|>


<commit_before><commit_msg>Adapt to sal/log.hxx<commit_after><|endoftext|>


<commit_before>#define MS_CLASS "RTC::SeqManager"
// #define MS_LOG_DEV_LEVEL 3

#include <iterator>
#include "RTC/SeqManager.hpp"
#include "Logger.hpp"

namespace RTC
{
	template<typename T>
	bool SeqManager<T>::SeqLowerThan::operator()(const T lhs, const T rhs) const
	{
		return ((rhs > lhs) && (rhs - lhs <= MaxValue / 2)) ||
		       ((lhs > rhs) && (lhs - rhs > MaxValue / 2));
	}

	template<typename T>
	bool SeqManager<T>::SeqHigherThan::operator()(const T lhs, const T rhs) const
	{
		return ((lhs > rhs) && (lhs - rhs <= MaxValue / 2)) ||
		       ((rhs > lhs) && (rhs - lhs > MaxValue / 2));
	}

	template<typename T>
	const typename SeqManager<T>::SeqLowerThan SeqManager<T>::isSeqLowerThan{};

	template<typename T>
	const typename SeqManager<T>::SeqHigherThan SeqManager<T>::isSeqHigherThan{};

	template<typename T>
	bool SeqManager<T>::IsSeqLowerThan(const T lhs, const T rhs)
	{
		return isSeqLowerThan(lhs, rhs);
	}

	template<typename T>
	bool SeqManager<T>::IsSeqHigherThan(const T lhs, const T rhs)
	{
		return isSeqHigherThan(lhs, rhs);
	}

	template<typename T>
	void SeqManager<T>::Sync(T input)
	{
		// Update base.
		this->base = this->maxOutput - input;

		// Update maxInput.
		this->maxInput = input;

		// Clear dropped set.
		this->dropped.clear();
	}

	template<typename T>
	void SeqManager<T>::Drop(T input)
	{
		// Mark as dropped if 'input' is higher than anyone already processed.
		if (SeqManager<T>::IsSeqHigherThan(input, this->maxInput))
		{
			this->dropped.insert(input);
		}
	}

	template<typename T>
	void SeqManager<T>::Offset(T offset)
	{
		this->base += offset;
	}

	template<typename T>
	bool SeqManager<T>::Input(const T input, T& output)
	{
		auto base = this->base;

		// There are dropped inputs. Synchronize.
		if (!this->dropped.empty())
		{
			// Delete dropped inputs older than input - MaxValue/2.
			size_t droppedSize = this->dropped.size();
			auto it            = this->dropped.lower_bound(input - MaxValue / 2);

			this->dropped.erase(this->dropped.begin(), it);
			this->base -= (droppedSize - this->dropped.size());
			base = this->base;

			// Check whether this input was dropped.
			it = this->dropped.find(input);

			if (it != this->dropped.end())
			{
				MS_DEBUG_DEV("trying to send a dropped input");

				return false;
			}

			// Count dropped entries before 'input' in order to adapt the base.
			size_t dropped = this->dropped.size()
			 - std::distance(this->dropped.upper_bound(input) , this->dropped.end());

			base -= dropped;
		}

		output = input + base;

		T idelta = input - this->maxInput;
		T odelta = output - this->maxOutput;

		// New input is higher than the maximum seen. But less than acceptable units higher.
		// Keep it as the maximum seen. See Drop().
		if (idelta < MaxValue / 2)
			this->maxInput = input;

		// New output is higher than the maximum seen. But less than acceptable units higher.
		// Keep it as the maximum seen. See Sync().
		if (odelta < MaxValue / 2)
			this->maxOutput = output;

		return true;
	}

	template<typename T>
	T SeqManager<T>::GetMaxInput() const
	{
		return this->maxInput;
	}

	template<typename T>
	T SeqManager<T>::GetMaxOutput() const
	{
		return this->maxOutput;
	}

	// Explicit instantiation to have all SeqManager definitions in this file.
	template class SeqManager<uint8_t>;
	template class SeqManager<uint16_t>;
	template class SeqManager<uint32_t>;

} // namespace RTC
<commit_msg>make format<commit_after>#define MS_CLASS "RTC::SeqManager"
// #define MS_LOG_DEV_LEVEL 3

#include "RTC/SeqManager.hpp"
#include "Logger.hpp"
#include <iterator>

namespace RTC
{
	template<typename T>
	bool SeqManager<T>::SeqLowerThan::operator()(const T lhs, const T rhs) const
	{
		return ((rhs > lhs) && (rhs - lhs <= MaxValue / 2)) ||
		       ((lhs > rhs) && (lhs - rhs > MaxValue / 2));
	}

	template<typename T>
	bool SeqManager<T>::SeqHigherThan::operator()(const T lhs, const T rhs) const
	{
		return ((lhs > rhs) && (lhs - rhs <= MaxValue / 2)) ||
		       ((rhs > lhs) && (rhs - lhs > MaxValue / 2));
	}

	template<typename T>
	const typename SeqManager<T>::SeqLowerThan SeqManager<T>::isSeqLowerThan{};

	template<typename T>
	const typename SeqManager<T>::SeqHigherThan SeqManager<T>::isSeqHigherThan{};

	template<typename T>
	bool SeqManager<T>::IsSeqLowerThan(const T lhs, const T rhs)
	{
		return isSeqLowerThan(lhs, rhs);
	}

	template<typename T>
	bool SeqManager<T>::IsSeqHigherThan(const T lhs, const T rhs)
	{
		return isSeqHigherThan(lhs, rhs);
	}

	template<typename T>
	void SeqManager<T>::Sync(T input)
	{
		// Update base.
		this->base = this->maxOutput - input;

		// Update maxInput.
		this->maxInput = input;

		// Clear dropped set.
		this->dropped.clear();
	}

	template<typename T>
	void SeqManager<T>::Drop(T input)
	{
		// Mark as dropped if 'input' is higher than anyone already processed.
		if (SeqManager<T>::IsSeqHigherThan(input, this->maxInput))
		{
			this->dropped.insert(input);
		}
	}

	template<typename T>
	void SeqManager<T>::Offset(T offset)
	{
		this->base += offset;
	}

	template<typename T>
	bool SeqManager<T>::Input(const T input, T& output)
	{
		auto base = this->base;

		// There are dropped inputs. Synchronize.
		if (!this->dropped.empty())
		{
			// Delete dropped inputs older than input - MaxValue/2.
			size_t droppedSize = this->dropped.size();
			auto it            = this->dropped.lower_bound(input - MaxValue / 2);

			this->dropped.erase(this->dropped.begin(), it);
			this->base -= (droppedSize - this->dropped.size());
			base = this->base;

			// Check whether this input was dropped.
			it = this->dropped.find(input);

			if (it != this->dropped.end())
			{
				MS_DEBUG_DEV("trying to send a dropped input");

				return false;
			}

			// Count dropped entries before 'input' in order to adapt the base.
			size_t dropped =
			  this->dropped.size() - std::distance(this->dropped.upper_bound(input), this->dropped.end());

			base -= dropped;
		}

		output = input + base;

		T idelta = input - this->maxInput;
		T odelta = output - this->maxOutput;

		// New input is higher than the maximum seen. But less than acceptable units higher.
		// Keep it as the maximum seen. See Drop().
		if (idelta < MaxValue / 2)
			this->maxInput = input;

		// New output is higher than the maximum seen. But less than acceptable units higher.
		// Keep it as the maximum seen. See Sync().
		if (odelta < MaxValue / 2)
			this->maxOutput = output;

		return true;
	}

	template<typename T>
	T SeqManager<T>::GetMaxInput() const
	{
		return this->maxInput;
	}

	template<typename T>
	T SeqManager<T>::GetMaxOutput() const
	{
		return this->maxOutput;
	}

	// Explicit instantiation to have all SeqManager definitions in this file.
	template class SeqManager<uint8_t>;
	template class SeqManager<uint16_t>;
	template class SeqManager<uint32_t>;

} // namespace RTC
<|endoftext|>


<commit_before>// Copyright 2018-present Open Networking Foundation
//
// 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 "stratum/hal/lib/dummy/dummy_switch.h"

#include <string>
#include <vector>

#include "absl/strings/str_format.h"
#include "absl/memory/memory.h"
#include "stratum/hal/lib/common/gnmi_events.h"
#include "stratum/hal/lib/common/common.pb.h"
#include "stratum/glue/logging.h"
#include "stratum/hal/lib/dummy/dummy_global_vars.h"

namespace stratum {
namespace hal {
namespace dummy_switch {

::util::Status DummySwitch::PushChassisConfig(const ChassisConfig& config) {
  absl::WriterMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  auto phal_status = phal_interface_->PushChassisConfig(config);
  auto chassis_mgr_status = chassis_mgr_->PushChassisConfig(config);
  if (!phal_status.ok()) {
    return phal_status;
  }
  if (!chassis_mgr_status.ok()) {
    return chassis_mgr_status;
  }
  for (auto& node : config.nodes()) {
    LOG(INFO) <<
      absl::StrFormat("Creating node \"%s\" (id: %d). Slot %d, Index: %d.",
                      node.name(), node.id(), node.slot(), node.index());
    auto new_node = DummyNode::CreateInstance(node.id(), node.name(),
                                              node.slot(), node.index());

    // Since "PushChassisConfig" called after "RegisterEventNotifyWriter"
    // We also need to register writer from nodes
    new_node->RegisterEventNotifyWriter(gnmi_event_writer_);
    new_node->PushChassisConfig(config);
    dummy_nodes_.emplace(node.id(), new_node);
  }

  for (const auto& singleton_port : config.singleton_ports()) {
    uint64 node_id = singleton_port.node();
    uint32 port_id = singleton_port.id();
    int32 slot = singleton_port.slot();
    int32 port = singleton_port.port();
    std::pair<uint64, uint32> node_port_pair = std::make_pair(node_id, port_id);
    node_port_id_to_slot.emplace(node_port_pair, slot);
    node_port_id_to_port.emplace(node_port_pair, port);
  }

  return ::util::OkStatus();
}

::util::Status DummySwitch::VerifyChassisConfig(const ChassisConfig& config) {
  absl::ReaderMutexLock l(&chassis_lock);
  // TODO(Yi Tseng): Implement this method.
  LOG(INFO) << __FUNCTION__;
  return ::util::OkStatus();
}

::util::Status DummySwitch::PushForwardingPipelineConfig(
    uint64 node_id,
    const ::p4::v1::ForwardingPipelineConfig& config) {
  absl::ReaderMutexLock l(&chassis_lock);
  DummyNode* node = nullptr;
  ASSIGN_OR_RETURN(node, GetDummyNode(node_id));
  return node->PushForwardingPipelineConfig(config);
}

::util::Status DummySwitch::SaveForwardingPipelineConfig(
    uint64 node_id,
    const ::p4::v1::ForwardingPipelineConfig& config) {
  absl::ReaderMutexLock l(&chassis_lock);
  DummyNode* node = nullptr;
  ASSIGN_OR_RETURN(node, GetDummyNode(node_id));
  return MAKE_ERROR(ERR_UNIMPLEMENTED)
      << "SaveForwardingPipelineConfig not implemented for this target";
}

::util::Status DummySwitch::CommitForwardingPipelineConfig(uint64 node_id) {
  absl::ReaderMutexLock l(&chassis_lock);
  DummyNode* node = nullptr;
  ASSIGN_OR_RETURN(node, GetDummyNode(node_id));
  return MAKE_ERROR(ERR_UNIMPLEMENTED)
      << "CommitForwardingPipelineConfig not implemented for this target";
}

::util::Status DummySwitch::VerifyForwardingPipelineConfig(
    uint64 node_id,
    const ::p4::v1::ForwardingPipelineConfig& config) {
  absl::ReaderMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  DummyNode* node = nullptr;
  ASSIGN_OR_RETURN(node, GetDummyNode(node_id));
  return node->VerifyForwardingPipelineConfig(config);
}

::util::Status DummySwitch::Shutdown() {
  absl::WriterMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  RETURN_IF_ERROR(phal_interface_->Shutdown());
  bool successful = true;
  for (auto kv : dummy_nodes_) {
    auto node = kv.second;
    auto node_status = node -> Shutdown();
    if (!node_status.ok()) {
      LOG(ERROR) << "Got error while shutting down node " << node->Name()
                 << node_status.ToString();
      successful = false;
      // Continue shutting down other nodes.
    }
  }
  shutdown = chassis_mgr_->Shutdown().ok() && successful;
  return shutdown ? ::util::OkStatus() :
      ::util::Status(::util::error::INTERNAL,
                     "Got error while shutting down the switch");
}
::util::Status DummySwitch::Freeze() {
  absl::WriterMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  bool successful = true;
  for (auto kv : dummy_nodes_) {
    auto node = kv.second;
    auto node_status = node -> Freeze();
    if (!node_status.ok()) {
      LOG(ERROR) << "Got error while freezing node " << node->Name()
                 << node_status.ToString();
      successful = false;
      // Continue freezing other nodes.
    }
  }
  return successful ? chassis_mgr_->Freeze() :
      ::util::Status(::util::error::INTERNAL,
                     "Got error while freezing the switch");
}
::util::Status DummySwitch::Unfreeze() {
  absl::WriterMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  bool successful = true;
  for (auto kv : dummy_nodes_) {
    auto node = kv.second;
    auto node_status = node -> Unfreeze();
    if (!node_status.ok()) {
      LOG(ERROR) << "Got error while unfreezing node " << node->Name()
                 << node_status.ToString();
      successful = false;
      // Continue unfreezing other nodes.
    }
  }
  return successful ? chassis_mgr_->Unfreeze() :
      ::util::Status(::util::error::INTERNAL,
                     "Got error while unfreezing the switch");
}
::util::Status DummySwitch::WriteForwardingEntries(
    const ::p4::v1::WriteRequest& req,
    std::vector<::util::Status>* results) {
  absl::ReaderMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  uint64 node_id = req.device_id();
  DummyNode* node = nullptr;
  ASSIGN_OR_RETURN(node, GetDummyNode(node_id));
  return node->WriteForwardingEntries(req, results);
}

::util::Status DummySwitch::ReadForwardingEntries(
    const ::p4::v1::ReadRequest& req,
    WriterInterface<::p4::v1::ReadResponse>* writer,
    std::vector<::util::Status>* details) {
  absl::ReaderMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  uint64 node_id = req.device_id();
  DummyNode* node = nullptr;
  ASSIGN_OR_RETURN(node, GetDummyNode(node_id));
  return node->ReadForwardingEntries(req, writer, details);
}

::util::Status DummySwitch::RegisterPacketReceiveWriter(
    uint64 node_id,
    std::shared_ptr<WriterInterface<::p4::v1::PacketIn>> writer) {
  absl::ReaderMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  DummyNode* node = nullptr;
  ASSIGN_OR_RETURN(node, GetDummyNode(node_id));
  return node->RegisterPacketReceiveWriter(writer);
}

::util::Status DummySwitch::UnregisterPacketReceiveWriter(uint64 node_id) {
  absl::ReaderMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  DummyNode* node = nullptr;
  ASSIGN_OR_RETURN(node, GetDummyNode(node_id));
  return node->UnregisterPacketReceiveWriter();
}

::util::Status DummySwitch::TransmitPacket(uint64 node_id,
                              const ::p4::v1::PacketOut& packet) {
  absl::ReaderMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  DummyNode* node = nullptr;
  ASSIGN_OR_RETURN(node, GetDummyNode(node_id));
  return node->TransmitPacket(packet);
}

::util::Status DummySwitch::RegisterEventNotifyWriter(
    std::shared_ptr<WriterInterface<GnmiEventPtr>> writer) {
  absl::WriterMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  gnmi_event_writer_ = writer;
  return chassis_mgr_->RegisterEventNotifyWriter(writer);
}

::util::Status DummySwitch::UnregisterEventNotifyWriter() {
  absl::WriterMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  for (auto node : GetDummyNodes()) {
    node->UnregisterEventNotifyWriter();
  }
  gnmi_event_writer_.reset();
  return chassis_mgr_->UnregisterEventNotifyWriter();
}

::util::Status DummySwitch::RetrieveValue(uint64 node_id,
                             const DataRequest& requests,
                             WriterInterface<DataResponse>* writer,
                             std::vector<::util::Status>* details) {
  absl::ReaderMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;

  DummyNode* dummy_node;
  if (node_id != 0) {
    ASSIGN_OR_RETURN(dummy_node, GetDummyNode(node_id));
  }
  DataResponse resp_val;
  ::util::StatusOr<DataResponse> resp;
  for (const auto& request : requests.requests()) {
    switch (request.request_case()) {
      case Request::kOperStatus:
      case Request::kAdminStatus:
      case Request::kMacAddress:
      case Request::kPortSpeed:
      case Request::kNegotiatedPortSpeed:
      case Request::kLacpRouterMac:
      case Request::kLacpSystemPriority:
      case Request::kPortCounters:
      case Request::kForwardingViability:
      case Request::kHealthIndicator:
      case Request::kHardwarePort:
        resp = dummy_node->RetrievePortData(request);
        break;
      case Request::kMemoryErrorAlarm:
      case Request::kFlowProgrammingExceptionAlarm:
        resp = chassis_mgr_->RetrieveChassisData(request);
        break;
      case Request::kPortQosCounters:
        resp = dummy_node->RetrievePortQosData(request);
        break;
      case Request::kFrontPanelPortInfo: {
        FrontPanelPortInfo front_panel_port_info;
        std::pair<uint64, uint32> node_port_pair =
            std::make_pair(request.front_panel_port_info().node_id(),
                           request.front_panel_port_info().port_id());
        int slot = node_port_id_to_slot[node_port_pair];
        int port = node_port_id_to_port[node_port_pair];
        ::util::Status status =
            phal_interface_->GetFrontPanelPortInfo(slot, port, resp_val.mutable_front_panel_port_info());
        if (status.ok()) {
          resp = resp_val;
        }
        break;
      }
      default:
        resp = MAKE_ERROR(ERR_INTERNAL) << "Not supported yet";
        break;
    }
    if (resp.ok()) {
      writer->Write(resp.ValueOrDie());
    } else if (details) {
      details->push_back(resp.status());
    }
  }
  return ::util::OkStatus();
}

::util::Status DummySwitch::SetValue(uint64 node_id, const SetRequest& request,
                                     std::vector<::util::Status>* details) {
  absl::ReaderMutexLock l(&chassis_lock);
  // TODO(Yi Tseng): Implement this method.
  LOG(INFO) << __FUNCTION__;
  return ::util::OkStatus();
}

::util::StatusOr<std::vector<std::string>> DummySwitch::VerifyState() {
  // TODO(Yi Tseng): Implement this method.
  return std::vector<std::string>();
}

std::vector<DummyNode*> DummySwitch::GetDummyNodes() {
  // TODO(Yi Tseng) find more efficient ways to implement this.
  std::vector<DummyNode*> nodes;
  nodes.reserve(dummy_nodes_.size());
  for (auto kv : dummy_nodes_) {
    nodes.emplace_back(kv.second);
  }
  return nodes;
}

::util::StatusOr<DummyNode*> DummySwitch::GetDummyNode(uint64 node_id) {
  auto node_element = dummy_nodes_.find(node_id);
  if (node_element == dummy_nodes_.end()) {
    return MAKE_ERROR(::util::error::NOT_FOUND)
      << "DummyNode with id " << node_id << " not found.";
  }
  return ::util::StatusOr<DummyNode*>(node_element->second);
}

std::unique_ptr<DummySwitch>
  DummySwitch::CreateInstance(PhalInterface* phal_interface,
                              DummyChassisManager* chassis_mgr) {
  return absl::WrapUnique(new DummySwitch(phal_interface, chassis_mgr));
}

DummySwitch::~DummySwitch() {}

DummySwitch::DummySwitch(PhalInterface* phal_interface,
                         DummyChassisManager* chassis_mgr)
  : phal_interface_(phal_interface),
    chassis_mgr_(chassis_mgr),
    dummy_nodes_(::stratum::gtl::flat_hash_map<uint64, DummyNode*>()),
    gnmi_event_writer_(nullptr) {
}

}  // namespace dummy_switch
}  // namespace hal
}  // namespace stratum
<commit_msg>Clear hashmaps in order to remove unused nodes with new chassis configs (#296)<commit_after>// Copyright 2018-present Open Networking Foundation
//
// 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 "stratum/hal/lib/dummy/dummy_switch.h"

#include <string>
#include <vector>

#include "absl/strings/str_format.h"
#include "absl/memory/memory.h"
#include "stratum/hal/lib/common/gnmi_events.h"
#include "stratum/hal/lib/common/common.pb.h"
#include "stratum/glue/logging.h"
#include "stratum/hal/lib/dummy/dummy_global_vars.h"

namespace stratum {
namespace hal {
namespace dummy_switch {

::util::Status DummySwitch::PushChassisConfig(const ChassisConfig& config) {
  absl::WriterMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  auto phal_status = phal_interface_->PushChassisConfig(config);
  auto chassis_mgr_status = chassis_mgr_->PushChassisConfig(config);
  if (!phal_status.ok()) {
    return phal_status;
  }
  if (!chassis_mgr_status.ok()) {
    return chassis_mgr_status;
  }
  dummy_nodes_.clear();
  node_port_id_to_slot.clear();
  node_port_id_to_port.clear();
  for (auto& node : config.nodes()) {
    LOG(INFO) <<
      absl::StrFormat("Creating node \"%s\" (id: %d). Slot %d, Index: %d.",
                      node.name(), node.id(), node.slot(), node.index());
    auto new_node = DummyNode::CreateInstance(node.id(), node.name(),
                                              node.slot(), node.index());

    // Since "PushChassisConfig" called after "RegisterEventNotifyWriter"
    // We also need to register writer from nodes
    new_node->RegisterEventNotifyWriter(gnmi_event_writer_);
    new_node->PushChassisConfig(config);
    dummy_nodes_.emplace(node.id(), new_node);
  }

  for (const auto& singleton_port : config.singleton_ports()) {
    uint64 node_id = singleton_port.node();
    uint32 port_id = singleton_port.id();
    int32 slot = singleton_port.slot();
    int32 port = singleton_port.port();
    std::pair<uint64, uint32> node_port_pair = std::make_pair(node_id, port_id);
    node_port_id_to_slot.emplace(node_port_pair, slot);
    node_port_id_to_port.emplace(node_port_pair, port);
  }

  return ::util::OkStatus();
}

::util::Status DummySwitch::VerifyChassisConfig(const ChassisConfig& config) {
  absl::ReaderMutexLock l(&chassis_lock);
  // TODO(Yi Tseng): Implement this method.
  LOG(INFO) << __FUNCTION__;
  return ::util::OkStatus();
}

::util::Status DummySwitch::PushForwardingPipelineConfig(
    uint64 node_id,
    const ::p4::v1::ForwardingPipelineConfig& config) {
  absl::ReaderMutexLock l(&chassis_lock);
  DummyNode* node = nullptr;
  ASSIGN_OR_RETURN(node, GetDummyNode(node_id));
  return node->PushForwardingPipelineConfig(config);
}

::util::Status DummySwitch::SaveForwardingPipelineConfig(
    uint64 node_id,
    const ::p4::v1::ForwardingPipelineConfig& config) {
  absl::ReaderMutexLock l(&chassis_lock);
  DummyNode* node = nullptr;
  ASSIGN_OR_RETURN(node, GetDummyNode(node_id));
  return MAKE_ERROR(ERR_UNIMPLEMENTED)
      << "SaveForwardingPipelineConfig not implemented for this target";
}

::util::Status DummySwitch::CommitForwardingPipelineConfig(uint64 node_id) {
  absl::ReaderMutexLock l(&chassis_lock);
  DummyNode* node = nullptr;
  ASSIGN_OR_RETURN(node, GetDummyNode(node_id));
  return MAKE_ERROR(ERR_UNIMPLEMENTED)
      << "CommitForwardingPipelineConfig not implemented for this target";
}

::util::Status DummySwitch::VerifyForwardingPipelineConfig(
    uint64 node_id,
    const ::p4::v1::ForwardingPipelineConfig& config) {
  absl::ReaderMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  DummyNode* node = nullptr;
  ASSIGN_OR_RETURN(node, GetDummyNode(node_id));
  return node->VerifyForwardingPipelineConfig(config);
}

::util::Status DummySwitch::Shutdown() {
  absl::WriterMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  RETURN_IF_ERROR(phal_interface_->Shutdown());
  bool successful = true;
  for (auto kv : dummy_nodes_) {
    auto node = kv.second;
    auto node_status = node -> Shutdown();
    if (!node_status.ok()) {
      LOG(ERROR) << "Got error while shutting down node " << node->Name()
                 << node_status.ToString();
      successful = false;
      // Continue shutting down other nodes.
    }
  }
  shutdown = chassis_mgr_->Shutdown().ok() && successful;
  return shutdown ? ::util::OkStatus() :
      ::util::Status(::util::error::INTERNAL,
                     "Got error while shutting down the switch");
}
::util::Status DummySwitch::Freeze() {
  absl::WriterMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  bool successful = true;
  for (auto kv : dummy_nodes_) {
    auto node = kv.second;
    auto node_status = node -> Freeze();
    if (!node_status.ok()) {
      LOG(ERROR) << "Got error while freezing node " << node->Name()
                 << node_status.ToString();
      successful = false;
      // Continue freezing other nodes.
    }
  }
  return successful ? chassis_mgr_->Freeze() :
      ::util::Status(::util::error::INTERNAL,
                     "Got error while freezing the switch");
}
::util::Status DummySwitch::Unfreeze() {
  absl::WriterMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  bool successful = true;
  for (auto kv : dummy_nodes_) {
    auto node = kv.second;
    auto node_status = node -> Unfreeze();
    if (!node_status.ok()) {
      LOG(ERROR) << "Got error while unfreezing node " << node->Name()
                 << node_status.ToString();
      successful = false;
      // Continue unfreezing other nodes.
    }
  }
  return successful ? chassis_mgr_->Unfreeze() :
      ::util::Status(::util::error::INTERNAL,
                     "Got error while unfreezing the switch");
}
::util::Status DummySwitch::WriteForwardingEntries(
    const ::p4::v1::WriteRequest& req,
    std::vector<::util::Status>* results) {
  absl::ReaderMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  uint64 node_id = req.device_id();
  DummyNode* node = nullptr;
  ASSIGN_OR_RETURN(node, GetDummyNode(node_id));
  return node->WriteForwardingEntries(req, results);
}

::util::Status DummySwitch::ReadForwardingEntries(
    const ::p4::v1::ReadRequest& req,
    WriterInterface<::p4::v1::ReadResponse>* writer,
    std::vector<::util::Status>* details) {
  absl::ReaderMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  uint64 node_id = req.device_id();
  DummyNode* node = nullptr;
  ASSIGN_OR_RETURN(node, GetDummyNode(node_id));
  return node->ReadForwardingEntries(req, writer, details);
}

::util::Status DummySwitch::RegisterPacketReceiveWriter(
    uint64 node_id,
    std::shared_ptr<WriterInterface<::p4::v1::PacketIn>> writer) {
  absl::ReaderMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  DummyNode* node = nullptr;
  ASSIGN_OR_RETURN(node, GetDummyNode(node_id));
  return node->RegisterPacketReceiveWriter(writer);
}

::util::Status DummySwitch::UnregisterPacketReceiveWriter(uint64 node_id) {
  absl::ReaderMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  DummyNode* node = nullptr;
  ASSIGN_OR_RETURN(node, GetDummyNode(node_id));
  return node->UnregisterPacketReceiveWriter();
}

::util::Status DummySwitch::TransmitPacket(uint64 node_id,
                              const ::p4::v1::PacketOut& packet) {
  absl::ReaderMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  DummyNode* node = nullptr;
  ASSIGN_OR_RETURN(node, GetDummyNode(node_id));
  return node->TransmitPacket(packet);
}

::util::Status DummySwitch::RegisterEventNotifyWriter(
    std::shared_ptr<WriterInterface<GnmiEventPtr>> writer) {
  absl::WriterMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  gnmi_event_writer_ = writer;
  return chassis_mgr_->RegisterEventNotifyWriter(writer);
}

::util::Status DummySwitch::UnregisterEventNotifyWriter() {
  absl::WriterMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;
  for (auto node : GetDummyNodes()) {
    node->UnregisterEventNotifyWriter();
  }
  gnmi_event_writer_.reset();
  return chassis_mgr_->UnregisterEventNotifyWriter();
}

::util::Status DummySwitch::RetrieveValue(uint64 node_id,
                             const DataRequest& requests,
                             WriterInterface<DataResponse>* writer,
                             std::vector<::util::Status>* details) {
  absl::ReaderMutexLock l(&chassis_lock);
  LOG(INFO) << __FUNCTION__;

  DummyNode* dummy_node;
  if (node_id != 0) {
    ASSIGN_OR_RETURN(dummy_node, GetDummyNode(node_id));
  }
  DataResponse resp_val;
  ::util::StatusOr<DataResponse> resp;
  for (const auto& request : requests.requests()) {
    switch (request.request_case()) {
      case Request::kOperStatus:
      case Request::kAdminStatus:
      case Request::kMacAddress:
      case Request::kPortSpeed:
      case Request::kNegotiatedPortSpeed:
      case Request::kLacpRouterMac:
      case Request::kLacpSystemPriority:
      case Request::kPortCounters:
      case Request::kForwardingViability:
      case Request::kHealthIndicator:
      case Request::kHardwarePort:
        resp = dummy_node->RetrievePortData(request);
        break;
      case Request::kMemoryErrorAlarm:
      case Request::kFlowProgrammingExceptionAlarm:
        resp = chassis_mgr_->RetrieveChassisData(request);
        break;
      case Request::kPortQosCounters:
        resp = dummy_node->RetrievePortQosData(request);
        break;
      case Request::kFrontPanelPortInfo: {
        FrontPanelPortInfo front_panel_port_info;
        std::pair<uint64, uint32> node_port_pair =
            std::make_pair(request.front_panel_port_info().node_id(),
                           request.front_panel_port_info().port_id());
        int slot = node_port_id_to_slot[node_port_pair];
        int port = node_port_id_to_port[node_port_pair];
        ::util::Status status =
            phal_interface_->GetFrontPanelPortInfo(slot, port, resp_val.mutable_front_panel_port_info());
        if (status.ok()) {
          resp = resp_val;
        }
        break;
      }
      default:
        resp = MAKE_ERROR(ERR_INTERNAL) << "Not supported yet";
        break;
    }
    if (resp.ok()) {
      writer->Write(resp.ValueOrDie());
    } else if (details) {
      details->push_back(resp.status());
    }
  }
  return ::util::OkStatus();
}

::util::Status DummySwitch::SetValue(uint64 node_id, const SetRequest& request,
                                     std::vector<::util::Status>* details) {
  absl::ReaderMutexLock l(&chassis_lock);
  // TODO(Yi Tseng): Implement this method.
  LOG(INFO) << __FUNCTION__;
  return ::util::OkStatus();
}

::util::StatusOr<std::vector<std::string>> DummySwitch::VerifyState() {
  // TODO(Yi Tseng): Implement this method.
  return std::vector<std::string>();
}

std::vector<DummyNode*> DummySwitch::GetDummyNodes() {
  // TODO(Yi Tseng) find more efficient ways to implement this.
  std::vector<DummyNode*> nodes;
  nodes.reserve(dummy_nodes_.size());
  for (auto kv : dummy_nodes_) {
    nodes.emplace_back(kv.second);
  }
  return nodes;
}

::util::StatusOr<DummyNode*> DummySwitch::GetDummyNode(uint64 node_id) {
  auto node_element = dummy_nodes_.find(node_id);
  if (node_element == dummy_nodes_.end()) {
    return MAKE_ERROR(::util::error::NOT_FOUND)
      << "DummyNode with id " << node_id << " not found.";
  }
  return ::util::StatusOr<DummyNode*>(node_element->second);
}

std::unique_ptr<DummySwitch>
  DummySwitch::CreateInstance(PhalInterface* phal_interface,
                              DummyChassisManager* chassis_mgr) {
  return absl::WrapUnique(new DummySwitch(phal_interface, chassis_mgr));
}

DummySwitch::~DummySwitch() {}

DummySwitch::DummySwitch(PhalInterface* phal_interface,
                         DummyChassisManager* chassis_mgr)
  : phal_interface_(phal_interface),
    chassis_mgr_(chassis_mgr),
    dummy_nodes_(::stratum::gtl::flat_hash_map<uint64, DummyNode*>()),
    gnmi_event_writer_(nullptr) {
}

}  // namespace dummy_switch
}  // namespace hal
}  // namespace stratum
<|endoftext|>


<commit_before>#include "environ_utils.hpp"

#include <configure/bind.hpp>
#include <configure/Node.hpp>
#include <configure/PropertyMap.hpp>
#include <configure/lua/State.hpp>
#include <configure/lua/Type.hpp>

#include <boost/filesystem/path.hpp>

namespace fs = boost::filesystem;

namespace configure {

	static int Node_property(lua_State* state)
	{
		NodePtr& self = lua::Converter<NodePtr>::extract(state, 1);
		Environ& env = self->properties();
		return utils::env_get(state, env, 2);
	}

	static int Node_set_property(lua_State* state)
	{
		NodePtr& self = lua::Converter<NodePtr>::extract(state, 1);
		Environ& env = self->properties();
		return utils::env_set(state, env, 2);
	}

	static int Node_set_property_default(lua_State* state)
	{
		NodePtr& self = lua::Converter<NodePtr>::extract(state, 1);
		Environ& env = self->properties();
		return utils::env_set_default(state, env, 2);
	}

	void bind_node(lua::State& state)
	{
		/// Node represent a vertex in the build graph.
		//
		// @classmod Node
		lua::Type<Node, NodePtr>(state, "Node")
			/// True if the node is a virtual node.
			// @function Node:is_virtual
			// @treturn bool
			.def("is_virtual", &Node::is_virtual)

			/// Path of the node
			// @function Node:path
			// @treturn Path absolute path
			.def("path", &Node::path)

			/// Name of a virtual node.
			// @function Node:name
			// @treturn string
			.def("name", &Node::name)

			.def("__tostring", &Node::string)

			/// Relative path to the node
			// @tparam Path start Starting point of the relative path
			// @treturn Path the relative path
			// @function Node:relative_path
			.def("relative_path", &Node::relative_path)

			/// Retrieve a Node property
			// @string name The property name
			// @treturn string|Path|boolean|nil
			.def("property", &Node_property)

			/// Set a Node property
			// @string name The property name
			// @tparam string|Path|boolean|nil the value to set
			// @treturn string|Path|boolean|nil
			.def("set_property", &Node_set_property)

			/// Set a Node property default value
			// @string name The property name
			// @tparam string|Path|boolean|nil the default value to set
			// @treturn string|Path|boolean|nil
			.def("set_property_default", &Node_set_property_default)
		;
	}

}

<commit_msg>Fix lua binding doc.<commit_after>#include "environ_utils.hpp"

#include <configure/bind.hpp>
#include <configure/Node.hpp>
#include <configure/PropertyMap.hpp>
#include <configure/lua/State.hpp>
#include <configure/lua/Type.hpp>

#include <boost/filesystem/path.hpp>

namespace fs = boost::filesystem;

namespace configure {

	static int Node_property(lua_State* state)
	{
		NodePtr& self = lua::Converter<NodePtr>::extract(state, 1);
		Environ& env = self->properties();
		return utils::env_get(state, env, 2);
	}

	static int Node_set_property(lua_State* state)
	{
		NodePtr& self = lua::Converter<NodePtr>::extract(state, 1);
		Environ& env = self->properties();
		return utils::env_set(state, env, 2);
	}

	static int Node_set_property_default(lua_State* state)
	{
		NodePtr& self = lua::Converter<NodePtr>::extract(state, 1);
		Environ& env = self->properties();
		return utils::env_set_default(state, env, 2);
	}

	void bind_node(lua::State& state)
	{
		/// Node represent a vertex in the build graph.
		//
		// @classmod Node
		lua::Type<Node, NodePtr>(state, "Node")
			/// True if the node is a virtual node.
			// @function Node:is_virtual
			// @treturn bool
			.def("is_virtual", &Node::is_virtual)

			/// Path of the node
			// @function Node:path
			// @treturn Path absolute path
			.def("path", &Node::path)

			/// Name of a virtual node.
			// @function Node:name
			// @treturn string
			.def("name", &Node::name)

			.def("__tostring", &Node::string)

			/// Relative path to the node
			// @tparam Path start Starting point of the relative path
			// @treturn Path the relative path
			// @function Node:relative_path
			.def("relative_path", &Node::relative_path)

			/// Retrieve a Node property
			// @string name The property name
			// @treturn string|Path|boolean|nil
			// @function Node:property
			.def("property", &Node_property)

			/// Set a Node property
			// @string name The property name
			// @tparam string|Path|boolean|nil the value to set
			// @treturn string|Path|boolean|nil
			// @function Node:set_property
			.def("set_property", &Node_set_property)

			/// Set a Node property default value
			// @string name The property name
			// @tparam string|Path|boolean|nil the default value to set
			// @treturn string|Path|boolean|nil
			// @function Node:set_property_default
			.def("set_property_default", &Node_set_property_default)
		;
	}

}

<|endoftext|>