<commit_before>/*************************************************************************
 *
 *  $RCSfile: bmkmenu.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: mba $ $Date: 2001-05-03 17:04:14 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#include <limits.h>

#include "classes/bmkmenu.hxx"

#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif

#ifndef __FRAMEWORK_MACROS_DEBUG_ASSERTION_HXX_
#include <macros/debug/assertion.hxx>
#endif

#ifndef __FRAMEWORK_HELPER_IMAGEPRODUCER_HXX_
#include <helper/imageproducer.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _UNOTOOLS_PROCESSFACTORY_HXX
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_DATETIME_HPP_
#include <com/sun/star/util/DateTime.hpp>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#include <vcl/config.hxx>
#include <svtools/dynamicmenuoptions.hxx>

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

using namespace ::rtl;
using namespace ::comphelper;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::beans;

#define S2U(STRING)                     ::rtl::OStringToOUString(STRING, RTL_TEXTENCODING_UTF8)
#define U2S(STRING)                     ::rtl::OUStringToOString(STRING, RTL_TEXTENCODING_UTF8)

namespace framework
{

void GetMenuEntry(
    Sequence< PropertyValue >&  aDynamicMenuEntry,
    ::rtl::OUString&            rTitle,
    ::rtl::OUString&            rURL,
    ::rtl::OUString&            rFrame,
    ::rtl::OUString&            rImageId );

class BmkMenu_Impl
{
    private:
        static USHORT        m_nMID;

    public:
        BmkMenu*             m_pRoot;
        BOOL                 m_bInitialized;

        BmkMenu_Impl( BmkMenu* pRoot );
        BmkMenu_Impl();
        ~BmkMenu_Impl();

        static USHORT       GetMID();
};

USHORT BmkMenu_Impl::m_nMID = BMKMENU_ITEMID_START;

BmkMenu_Impl::BmkMenu_Impl( BmkMenu* pRoot ) :
    m_pRoot(pRoot),
    m_bInitialized(FALSE)
{
}

BmkMenu_Impl::BmkMenu_Impl() :
    m_pRoot(0),
    m_bInitialized(FALSE)
{
}

BmkMenu_Impl::~BmkMenu_Impl()
{
}

USHORT BmkMenu_Impl::GetMID()
{
    m_nMID++;
    if( !m_nMID )
        m_nMID = BMKMENU_ITEMID_START;
    return m_nMID;
}

/*
String BmkMenu_Impl::GetTitle( const String& rStr )
{
    // "_..._" vorne rausschneiden
    String aTitle( rStr );
    if ( aTitle.Len() && aTitle.GetChar(0) == 0x005f)
    {
        aTitle.Erase( 0, 1 );
        while ( aTitle.Len() && aTitle.GetChar(0) != 0x005f )
            aTitle.Erase( 0, 1 );
        if ( aTitle.Len() )
            aTitle.Erase( 0, 1 );
        else
            aTitle = rStr;
    }

    return aTitle;
}
*/

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

//ImageList* BmkMenu::_pSmallImages = NULL;
//ImageList* BmkMenu::_pBigImages = NULL;

BmkMenu::BmkMenu( Reference< XFrame >& xFrame, BmkMenu::BmkMenuType nType, BmkMenu* pRoot ) :
    m_xFrame( xFrame ), m_nType( nType )
{
    _pImp = new BmkMenu_Impl( pRoot );
    Initialize();
}

/*
Image BmkMenu::GetImage( USHORT nId, BOOL bBig )
{
    ImageList* pList = NULL;
    if ( bBig )
    {
        if ( !_pBigImages )
            _pBigImages = new ImageList( SfxResId( RID_IMGLST_BIG ) );
        pList = _pBigImages;
    }
    else
    {
        if ( !_pSmallImages )
            _pSmallImages = new ImageList( SfxResId( RID_IMGLST_SMALL ) );
        pList = _pSmallImages;
    }
    return pList->GetImage( nId );
}
*/

BmkMenu::BmkMenu( Reference< XFrame >& xFrame, BmkMenu::BmkMenuType nType ) :
    m_nType( nType ), m_xFrame( xFrame )
{
    _pImp = new BmkMenu_Impl();
    Initialize();
}

BmkMenu::~BmkMenu()
{
    delete _pImp;
}

void BmkMenu::Initialize()
{
    if( _pImp->m_bInitialized )
        return;

    _pImp->m_bInitialized = TRUE;

    Sequence< Sequence< PropertyValue > > aDynamicMenuEntries;

    if ( m_nType == BmkMenu::BMK_NEWMENU )
        aDynamicMenuEntries = SvtDynamicMenuOptions().GetMenu( E_NEWMENU );
    else if ( m_nType == BmkMenu::BMK_WIZARDMENU )
        aDynamicMenuEntries = SvtDynamicMenuOptions().GetMenu( E_WIZARDMENU );

    ::rtl::OUString aTitle;
    ::rtl::OUString aURL;
    ::rtl::OUString aTargetFrame;
    ::rtl::OUString aImageId;

    UINT32 i, nCount = aDynamicMenuEntries.getLength();
    for ( i = 0; i < nCount; ++i )
    {
        GetMenuEntry( aDynamicMenuEntries[i], aTitle, aURL, aTargetFrame, aImageId );

        if ( !aTitle.getLength() && !aURL.getLength() )
            continue;

        if ( aURL == ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:separator" )))
            InsertSeparator();
        else
        {
            USHORT nId = CreateMenuId();

            Image aImage = GetImageFromURL( m_xFrame, aURL, FALSE );
            if ( !aImage )
                InsertItem( nId, aTitle );
            else
                InsertItem( nId, aTitle, aImage );

            BmkMenu::Attributes* pUserAttributes = new BmkMenu::Attributes;
            pUserAttributes->aTargetFrame = aTargetFrame;
            SetUserValue( nId, (ULONG)pUserAttributes );

            SetItemCommand( nId, aURL );
        }
    }
}

USHORT BmkMenu::CreateMenuId()
{
    return BmkMenu_Impl::GetMID();
}

void GetMenuEntry
(
    Sequence< PropertyValue >& aDynamicMenuEntry,
    ::rtl::OUString& rTitle,
    ::rtl::OUString& rURL,
    ::rtl::OUString& rFrame,
    ::rtl::OUString& rImageId
)
{
    for ( int i = 0; i < aDynamicMenuEntry.getLength(); i++ )
    {
        if ( aDynamicMenuEntry[i].Name == DYNAMICMENU_PROPERTYNAME_URL )
            aDynamicMenuEntry[i].Value >>= rURL;
        else if ( aDynamicMenuEntry[i].Name == DYNAMICMENU_PROPERTYNAME_TITLE )
            aDynamicMenuEntry[i].Value >>= rTitle;
        else if ( aDynamicMenuEntry[i].Name == DYNAMICMENU_PROPERTYNAME_IMAGEIDENTIFIER )
            aDynamicMenuEntry[i].Value >>= rImageId;
        else if ( aDynamicMenuEntry[i].Name == DYNAMICMENU_PROPERTYNAME_TARGETNAME )
            aDynamicMenuEntry[i].Value >>= rFrame;
    }
}

}
<commit_msg>use image id url<commit_after>/*************************************************************************
 *
 *  $RCSfile: bmkmenu.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: pb $ $Date: 2001-05-11 10:12:07 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#include <limits.h>

#include "classes/bmkmenu.hxx"

#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif

#ifndef __FRAMEWORK_MACROS_DEBUG_ASSERTION_HXX_
#include <macros/debug/assertion.hxx>
#endif

#ifndef __FRAMEWORK_HELPER_IMAGEPRODUCER_HXX_
#include <helper/imageproducer.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _UNOTOOLS_PROCESSFACTORY_HXX
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_DATETIME_HPP_
#include <com/sun/star/util/DateTime.hpp>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#include <vcl/config.hxx>
#include <svtools/dynamicmenuoptions.hxx>

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

using namespace ::rtl;
using namespace ::comphelper;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::beans;

namespace framework
{

void GetMenuEntry(
    Sequence< PropertyValue >&  aDynamicMenuEntry,
    ::rtl::OUString&            rTitle,
    ::rtl::OUString&            rURL,
    ::rtl::OUString&            rFrame,
    ::rtl::OUString&            rImageId );

class BmkMenu_Impl
{
    private:
        static USHORT        m_nMID;

    public:
        BmkMenu*             m_pRoot;
        BOOL                 m_bInitialized;

        BmkMenu_Impl( BmkMenu* pRoot );
        BmkMenu_Impl();
        ~BmkMenu_Impl();

        static USHORT       GetMID();
};

USHORT BmkMenu_Impl::m_nMID = BMKMENU_ITEMID_START;

BmkMenu_Impl::BmkMenu_Impl( BmkMenu* pRoot ) :
    m_pRoot(pRoot),
    m_bInitialized(FALSE)
{
}

BmkMenu_Impl::BmkMenu_Impl() :
    m_pRoot(0),
    m_bInitialized(FALSE)
{
}

BmkMenu_Impl::~BmkMenu_Impl()
{
}

USHORT BmkMenu_Impl::GetMID()
{
    m_nMID++;
    if( !m_nMID )
        m_nMID = BMKMENU_ITEMID_START;
    return m_nMID;
}

/*
String BmkMenu_Impl::GetTitle( const String& rStr )
{
    // "_..._" vorne rausschneiden
    String aTitle( rStr );
    if ( aTitle.Len() && aTitle.GetChar(0) == 0x005f)
    {
        aTitle.Erase( 0, 1 );
        while ( aTitle.Len() && aTitle.GetChar(0) != 0x005f )
            aTitle.Erase( 0, 1 );
        if ( aTitle.Len() )
            aTitle.Erase( 0, 1 );
        else
            aTitle = rStr;
    }

    return aTitle;
}
*/

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

//ImageList* BmkMenu::_pSmallImages = NULL;
//ImageList* BmkMenu::_pBigImages = NULL;

BmkMenu::BmkMenu( Reference< XFrame >& xFrame, BmkMenu::BmkMenuType nType, BmkMenu* pRoot ) :
    m_xFrame( xFrame ), m_nType( nType )
{
    _pImp = new BmkMenu_Impl( pRoot );
    Initialize();
}

/*
Image BmkMenu::GetImage( USHORT nId, BOOL bBig )
{
    ImageList* pList = NULL;
    if ( bBig )
    {
        if ( !_pBigImages )
            _pBigImages = new ImageList( SfxResId( RID_IMGLST_BIG ) );
        pList = _pBigImages;
    }
    else
    {
        if ( !_pSmallImages )
            _pSmallImages = new ImageList( SfxResId( RID_IMGLST_SMALL ) );
        pList = _pSmallImages;
    }
    return pList->GetImage( nId );
}
*/

BmkMenu::BmkMenu( Reference< XFrame >& xFrame, BmkMenu::BmkMenuType nType ) :
    m_nType( nType ), m_xFrame( xFrame )
{
    _pImp = new BmkMenu_Impl();
    Initialize();
}

BmkMenu::~BmkMenu()
{
    delete _pImp;
}

void BmkMenu::Initialize()
{
    if( _pImp->m_bInitialized )
        return;

    _pImp->m_bInitialized = TRUE;

    Sequence< Sequence< PropertyValue > > aDynamicMenuEntries;

    if ( m_nType == BmkMenu::BMK_NEWMENU )
        aDynamicMenuEntries = SvtDynamicMenuOptions().GetMenu( E_NEWMENU );
    else if ( m_nType == BmkMenu::BMK_WIZARDMENU )
        aDynamicMenuEntries = SvtDynamicMenuOptions().GetMenu( E_WIZARDMENU );

    ::rtl::OUString aTitle;
    ::rtl::OUString aURL;
    ::rtl::OUString aTargetFrame;
    ::rtl::OUString aImageId;

    UINT32 i, nCount = aDynamicMenuEntries.getLength();
    for ( i = 0; i < nCount; ++i )
    {
        GetMenuEntry( aDynamicMenuEntries[i], aTitle, aURL, aTargetFrame, aImageId );

        if ( !aTitle.getLength() && !aURL.getLength() )
            continue;

        if ( aURL == ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:separator" )))
            InsertSeparator();
        else
        {
            sal_Bool    bImageSet = sal_False;
            USHORT      nId = CreateMenuId();

            if ( aImageId.getLength() > 0 )
            {
                Image aImage = GetImageFromURL( m_xFrame, aImageId, FALSE );
                if ( !!aImage )
                {
                    bImageSet = sal_True;
                    InsertItem( nId, aTitle, aImage );
                }
            }

            if ( !bImageSet )
            {
                Image aImage = GetImageFromURL( m_xFrame, aURL, FALSE );
                if ( !aImage )
                    InsertItem( nId, aTitle );
                else
                    InsertItem( nId, aTitle, aImage );
            }

            BmkMenu::Attributes* pUserAttributes = new BmkMenu::Attributes;
            pUserAttributes->aTargetFrame = aTargetFrame;
            SetUserValue( nId, (ULONG)pUserAttributes );

            SetItemCommand( nId, aURL );
        }
    }
}

USHORT BmkMenu::CreateMenuId()
{
    return BmkMenu_Impl::GetMID();
}

void GetMenuEntry
(
    Sequence< PropertyValue >& aDynamicMenuEntry,
    ::rtl::OUString& rTitle,
    ::rtl::OUString& rURL,
    ::rtl::OUString& rFrame,
    ::rtl::OUString& rImageId
)
{
    for ( int i = 0; i < aDynamicMenuEntry.getLength(); i++ )
    {
        if ( aDynamicMenuEntry[i].Name == DYNAMICMENU_PROPERTYNAME_URL )
            aDynamicMenuEntry[i].Value >>= rURL;
        else if ( aDynamicMenuEntry[i].Name == DYNAMICMENU_PROPERTYNAME_TITLE )
            aDynamicMenuEntry[i].Value >>= rTitle;
        else if ( aDynamicMenuEntry[i].Name == DYNAMICMENU_PROPERTYNAME_IMAGEIDENTIFIER )
            aDynamicMenuEntry[i].Value >>= rImageId;
        else if ( aDynamicMenuEntry[i].Name == DYNAMICMENU_PROPERTYNAME_TARGETNAME )
            aDynamicMenuEntry[i].Value >>= rFrame;
    }
}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fudraw.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2005-09-28 12:12:10 $
 *
 *  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 SC_FUDRAW_HXX
#define SC_FUDRAW_HXX

#ifndef _SC_FUPOOR_HXX
#include "fupoor.hxx"
#endif

#ifndef _SV_POINTR_HXX //autogen
#include <vcl/pointr.hxx>
#endif

/*************************************************************************
|*
|* Basisklasse fuer alle Drawmodul-spezifischen Funktionen
|*
\************************************************************************/

class FuDraw : public FuPoor
{
 protected:
    Pointer aNewPointer;
    Pointer aOldPointer;

 public:
    FuDraw(ScTabViewShell* pViewSh, Window* pWin, SdrView* pView,
           SdrModel* pDoc, SfxRequest& rReq);
    virtual ~FuDraw();

    virtual BOOL KeyInput(const KeyEvent& rKEvt);

    virtual void ScrollStart();
    virtual void ScrollEnd();

    virtual void Activate();
    virtual void Deactivate();

    virtual void ForcePointer(const MouseEvent* pMEvt);

    virtual BOOL MouseMove(const MouseEvent& rMEvt);
    virtual BOOL MouseButtonUp(const MouseEvent& rMEvt);
    virtual BOOL MouseButtonDown(const MouseEvent& rMEvt);

    // #97016# II
    virtual void SelectionHasChanged();

    BOOL IsSizingOrMovingNote( const MouseEvent& rMEvt ) const;
    void CheckVisibleNote() const;

 private:
    void    DoModifiers(const MouseEvent& rMEvt);
    void    ResetModifiers();
};

#endif      // _SD_FUDRAW_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.5.690); FILE MERGED 2008/04/01 12:36:46 thb 1.5.690.2: #i85898# Stripping all external header guards 2008/03/31 17:15:41 rt 1.5.690.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: fudraw.hxx,v $
 * $Revision: 1.6 $
 *
 * 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 SC_FUDRAW_HXX
#define SC_FUDRAW_HXX

#include "fupoor.hxx"

#ifndef _SV_POINTR_HXX //autogen
#include <vcl/pointr.hxx>
#endif

/*************************************************************************
|*
|* Basisklasse fuer alle Drawmodul-spezifischen Funktionen
|*
\************************************************************************/

class FuDraw : public FuPoor
{
 protected:
    Pointer aNewPointer;
    Pointer aOldPointer;

 public:
    FuDraw(ScTabViewShell* pViewSh, Window* pWin, SdrView* pView,
           SdrModel* pDoc, SfxRequest& rReq);
    virtual ~FuDraw();

    virtual BOOL KeyInput(const KeyEvent& rKEvt);

    virtual void ScrollStart();
    virtual void ScrollEnd();

    virtual void Activate();
    virtual void Deactivate();

    virtual void ForcePointer(const MouseEvent* pMEvt);

    virtual BOOL MouseMove(const MouseEvent& rMEvt);
    virtual BOOL MouseButtonUp(const MouseEvent& rMEvt);
    virtual BOOL MouseButtonDown(const MouseEvent& rMEvt);

    // #97016# II
    virtual void SelectionHasChanged();

    BOOL IsSizingOrMovingNote( const MouseEvent& rMEvt ) const;
    void CheckVisibleNote() const;

 private:
    void    DoModifiers(const MouseEvent& rMEvt);
    void    ResetModifiers();
};

#endif      // _SD_FUDRAW_HXX
<|endoftext|>


<commit_before>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright (C) 2011 - 2015                                                  *
 * Dominik Charousset <dominik.charousset (at) haw-hamburg.de>                *
 * Raphael Hiesgen <raphael.hiesgen (at) haw-hamburg.de>                      *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#include "caf/exception.hpp"

#include "caf/io/broker.hpp"
#include "caf/io/middleman.hpp"

#include "caf/io/network/asio_multiplexer.hpp"

namespace caf {
namespace io {
namespace network {

namespace {

/// A wrapper for the supervisor backend provided by boost::asio.
struct asio_supervisor : public multiplexer::supervisor {
  explicit asio_supervisor(io_backend& iob) : work(iob) {
    // nop
  }

private:
  boost::asio::io_service::work work;
};

} // namespace anonymous

default_socket new_tcp_connection(io_backend& backend, const std::string& host,
                                  uint16_t port) {
  default_socket fd{backend};
  using boost::asio::ip::tcp;
  tcp::resolver r(fd.get_io_service());
  tcp::resolver::query q(host, std::to_string(port));
  boost::system::error_code ec;
  auto i = r.resolve(q, ec);
  if (ec) {
    throw network_error("could not resolve host: " + host);
  }
  boost::asio::connect(fd, i, ec);
  if (ec) {
    throw network_error("could not connect to host: " + host +
                        ":" + std::to_string(port));
  }
  return fd;
}

void ip_bind(default_socket_acceptor& fd, uint16_t port,
             const char* addr = nullptr, bool reuse_addr = true) {
  CAF_LOGF_TRACE(CAF_ARG(port));
  using boost::asio::ip::tcp;
  try {
    auto bind_and_listen = [&](tcp::endpoint& ep) {
      fd.open(ep.protocol());
      fd.set_option(tcp::acceptor::reuse_address(reuse_addr));
      fd.bind(ep);
      fd.listen();
    };
    if (addr) {
      tcp::endpoint ep(boost::asio::ip::address::from_string(addr), port);
      bind_and_listen(ep);
      CAF_LOGF_DEBUG("created IPv6 endpoint: " << ep.address() << ":"
                                               << fd.local_endpoint().port());
    } else {
      tcp::endpoint ep(tcp::v6(), port);
      bind_and_listen(ep);
      CAF_LOGF_DEBUG("created IPv6 endpoint: " << ep.address() << ":"
                                               << fd.local_endpoint().port());
    }
  } catch (boost::system::system_error& se) {
    if (se.code() == boost::system::errc::address_in_use) {
      throw bind_failure(se.code().message());
    }
    throw network_error(se.code().message());
  }
}

connection_handle asio_multiplexer::new_tcp_scribe(const std::string& host,
                                                   uint16_t port) {
  default_socket fd{new_tcp_connection(backend(), host, port)};
  auto id = int64_from_native_socket(fd.native_handle());
  std::lock_guard<std::mutex> lock(mtx_sockets_);
  unassigned_sockets_.insert(std::make_pair(id, std::move(fd)));
  return connection_handle::from_int(id);
}

<<<<<<< HEAD
void asio_multiplexer::assign_tcp_scribe(broker* self, connection_handle hdl) {
  std::lock_guard<std::mutex> lock(mtx_sockets_);
  auto itr = unassigned_sockets_.find(hdl.id());
  if (itr != unassigned_sockets_.end()) {
=======
void asio_multiplexer::assign_tcp_scribe(abstract_broker* self, connection_handle hdl) {
  std::lock_guard<std::mutex> lock(mtx_sockets_);
  auto itr = unassigned_sockets_.find(hdl.id());
  if (itr != unassigned_sockets_.end()) {
>>>>>>> 84f43f6f825114da12757fe0e7018b9464b97614
    add_tcp_scribe(self, std::move(itr->second));
    unassigned_sockets_.erase(itr);
  }
}

template <class Socket>
connection_handle asio_multiplexer::add_tcp_scribe(abstract_broker* self,
                                                   Socket&& sock) {
  CAF_LOG_TRACE("");
<<<<<<< HEAD
  class impl : public broker::scribe {
 public:
    impl(broker* ptr, Socket&& s)
=======
  class impl : public abstract_broker::scribe {
  public:
    impl(abstract_broker* ptr, Socket&& s)
>>>>>>> 84f43f6f825114da12757fe0e7018b9464b97614
        : scribe(ptr, network::conn_hdl_from_socket(s)),
          launched_(false),
          stream_(s.get_io_service()) {
      stream_.init(std::move(s));
    }
    void configure_read(receive_policy::config config) override {
      CAF_LOG_TRACE("");
      stream_.configure_read(config);
      if (! launched_) {
        launch();
      }
    }
<<<<<<< HEAD
    broker::buffer_type& wr_buf() override { return stream_.wr_buf(); }
    broker::buffer_type& rd_buf() override { return stream_.rd_buf(); }
=======
    abstract_broker::buffer_type& wr_buf() override { return stream_.wr_buf(); }
    abstract_broker::buffer_type& rd_buf() override { return stream_.rd_buf(); }
>>>>>>> 84f43f6f825114da12757fe0e7018b9464b97614
    void stop_reading() override {
      CAF_LOG_TRACE("");
      stream_.stop_reading();
      disconnect(false);
    }
    void flush() override {
      CAF_LOG_TRACE("");
      stream_.flush(this);
    }
    void launch() {
      CAF_LOG_TRACE("");
      CAF_ASSERT(! launched_);
      launched_ = true;
      stream_.start(this);
    }

 private:
    bool launched_;
    stream<Socket> stream_;
  };
  abstract_broker::scribe_pointer ptr = make_counted<impl>(self, std::move(sock));
  self->add_scribe(ptr);
  return ptr->hdl();
}

connection_handle asio_multiplexer::add_tcp_scribe(abstract_broker* self,
                                                   native_socket fd) {
  CAF_LOG_TRACE(CAF_ARG(self) << ", " << CAF_ARG(fd));
  boost::system::error_code ec;
  default_socket sock{backend()};
  sock.assign(boost::asio::ip::tcp::v6(), fd, ec);
  if (ec) {
    sock.assign(boost::asio::ip::tcp::v4(), fd, ec);
  }
  if (ec) {
    throw network_error(ec.message());
  }
  return add_tcp_scribe(self, std::move(sock));
}

connection_handle asio_multiplexer::add_tcp_scribe(abstract_broker* self,
                                                   const std::string& host,
                                                   uint16_t port) {
  CAF_LOG_TRACE(CAF_ARG(self) << ", " << CAF_ARG(host) << ":" << CAF_ARG(port));
  return add_tcp_scribe(self, new_tcp_connection(backend(), host, port));
}

std::pair<accept_handle, uint16_t>
asio_multiplexer::new_tcp_doorman(uint16_t port, const char* in, bool rflag) {
  CAF_LOG_TRACE(CAF_ARG(port) << ", addr = " << (in ? in : "nullptr"));
  default_socket_acceptor fd{backend()};
  ip_bind(fd, port, in, rflag);
  auto id = int64_from_native_socket(fd.native_handle());
  auto assigned_port = fd.local_endpoint().port();
  std::lock_guard<std::mutex> lock(mtx_acceptors_);
  unassigned_acceptors_.insert(std::make_pair(id, std::move(fd)));
  return {accept_handle::from_int(id), assigned_port};
}

void asio_multiplexer::assign_tcp_doorman(abstract_broker* self, accept_handle hdl) {
  CAF_LOG_TRACE("");
  std::lock_guard<std::mutex> lock(mtx_acceptors_);
  auto itr = unassigned_acceptors_.find(hdl.id());
  if (itr != unassigned_acceptors_.end()) {
    add_tcp_doorman(self, std::move(itr->second));
    unassigned_acceptors_.erase(itr);
  }
}

accept_handle
asio_multiplexer::add_tcp_doorman(abstract_broker* self,
                                  default_socket_acceptor&& sock) {
  CAF_LOG_TRACE("sock.fd = " << sock.native_handle());
  CAF_ASSERT(sock.native_handle() != network::invalid_native_socket);
<<<<<<< HEAD
  class impl : public broker::doorman {
 public:
    impl(broker* ptr, default_socket_acceptor&& s,
=======
  class impl : public abstract_broker::doorman {
  public:
    impl(abstract_broker* ptr, default_socket_acceptor&& s,
>>>>>>> 84f43f6f825114da12757fe0e7018b9464b97614
         network::asio_multiplexer& am)
        : doorman(ptr, network::accept_hdl_from_socket(s)),
          acceptor_(am, s.get_io_service()) {
      acceptor_.init(std::move(s));
    }
    void new_connection() override {
      CAF_LOG_TRACE("");
      auto& am = acceptor_.backend();
      accept_msg().handle
        = am.add_tcp_scribe(parent(), std::move(acceptor_.accepted_socket()));
      parent()->invoke_message(invalid_actor_addr, invalid_message_id,
                               accept_msg_);
    }
    void stop_reading() override {
      CAF_LOG_TRACE("");
      acceptor_.stop();
      disconnect(false);
    }
    void launch() override {
      CAF_LOG_TRACE("");
      acceptor_.start(this);
    }

 private:
    network::acceptor<default_socket_acceptor> acceptor_;
  };
  abstract_broker::doorman_pointer ptr
    = make_counted<impl>(self, std::move(sock), *this);
  self->add_doorman(ptr);
  return ptr->hdl();
}

accept_handle asio_multiplexer::add_tcp_doorman(abstract_broker* self,
                                                native_socket fd) {
  default_socket_acceptor sock{backend()};
  boost::system::error_code ec;
  sock.assign(boost::asio::ip::tcp::v6(), fd, ec);
  if (ec) {
    sock.assign(boost::asio::ip::tcp::v4(), fd, ec);
  }
  if (ec) {
    throw network_error(ec.message());
  }
  return add_tcp_doorman(self, std::move(sock));
}

std::pair<accept_handle, uint16_t>
asio_multiplexer::add_tcp_doorman(abstract_broker* self, uint16_t port, const char* in,
                                  bool rflag) {
  default_socket_acceptor fd{backend()};
  ip_bind(fd, port, in, rflag);
  auto p = fd.local_endpoint().port();
  return {add_tcp_doorman(self, std::move(fd)), p};
}

void asio_multiplexer::dispatch_runnable(runnable_ptr ptr) {
  backend().post([=]() {
    ptr->run();
  });
}

asio_multiplexer::asio_multiplexer() {
  // nop
}

asio_multiplexer::~asio_multiplexer() {
  //nop
}

multiplexer::supervisor_ptr asio_multiplexer::make_supervisor() {
  return std::unique_ptr<asio_supervisor>(new asio_supervisor(backend()));
}

void asio_multiplexer::run() {
  CAF_LOG_TRACE("asio-based multiplexer");
  boost::system::error_code ec;
  backend().run(ec);
  if (ec) {
    throw std::runtime_error(ec.message());
  }
}

boost::asio::io_service* asio_multiplexer::pimpl() {
  return &backend_;
}

asio_multiplexer& get_multiplexer_singleton() {
  return static_cast<asio_multiplexer&>(middleman::instance()->backend());
}

} // namesapce network
} // namespace io
} // namespace caf
<commit_msg>Fix ASIO build<commit_after>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright (C) 2011 - 2015                                                  *
 * Dominik Charousset <dominik.charousset (at) haw-hamburg.de>                *
 * Raphael Hiesgen <raphael.hiesgen (at) haw-hamburg.de>                      *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#include "caf/exception.hpp"

#include "caf/io/broker.hpp"
#include "caf/io/middleman.hpp"

#include "caf/io/network/asio_multiplexer.hpp"

namespace caf {
namespace io {
namespace network {

namespace {

/// A wrapper for the supervisor backend provided by boost::asio.
struct asio_supervisor : public multiplexer::supervisor {
  explicit asio_supervisor(io_backend& iob) : work(iob) {
    // nop
  }

private:
  boost::asio::io_service::work work;
};

} // namespace anonymous

default_socket new_tcp_connection(io_backend& backend, const std::string& host,
                                  uint16_t port) {
  default_socket fd{backend};
  using boost::asio::ip::tcp;
  tcp::resolver r(fd.get_io_service());
  tcp::resolver::query q(host, std::to_string(port));
  boost::system::error_code ec;
  auto i = r.resolve(q, ec);
  if (ec) {
    throw network_error("could not resolve host: " + host);
  }
  boost::asio::connect(fd, i, ec);
  if (ec) {
    throw network_error("could not connect to host: " + host +
                        ":" + std::to_string(port));
  }
  return fd;
}

void ip_bind(default_socket_acceptor& fd, uint16_t port,
             const char* addr = nullptr, bool reuse_addr = true) {
  CAF_LOGF_TRACE(CAF_ARG(port));
  using boost::asio::ip::tcp;
  try {
    auto bind_and_listen = [&](tcp::endpoint& ep) {
      fd.open(ep.protocol());
      fd.set_option(tcp::acceptor::reuse_address(reuse_addr));
      fd.bind(ep);
      fd.listen();
    };
    if (addr) {
      tcp::endpoint ep(boost::asio::ip::address::from_string(addr), port);
      bind_and_listen(ep);
      CAF_LOGF_DEBUG("created IPv6 endpoint: " << ep.address() << ":"
                                               << fd.local_endpoint().port());
    } else {
      tcp::endpoint ep(tcp::v6(), port);
      bind_and_listen(ep);
      CAF_LOGF_DEBUG("created IPv6 endpoint: " << ep.address() << ":"
                                               << fd.local_endpoint().port());
    }
  } catch (boost::system::system_error& se) {
    if (se.code() == boost::system::errc::address_in_use) {
      throw bind_failure(se.code().message());
    }
    throw network_error(se.code().message());
  }
}

connection_handle asio_multiplexer::new_tcp_scribe(const std::string& host,
                                                   uint16_t port) {
  default_socket fd{new_tcp_connection(backend(), host, port)};
  auto id = int64_from_native_socket(fd.native_handle());
  std::lock_guard<std::mutex> lock(mtx_sockets_);
  unassigned_sockets_.insert(std::make_pair(id, std::move(fd)));
  return connection_handle::from_int(id);
}

void asio_multiplexer::assign_tcp_scribe(abstract_broker* self,
                                         connection_handle hdl) {
  std::lock_guard<std::mutex> lock(mtx_sockets_);
  auto itr = unassigned_sockets_.find(hdl.id());
  if (itr != unassigned_sockets_.end()) {
    add_tcp_scribe(self, std::move(itr->second));
    unassigned_sockets_.erase(itr);
  }
}

template <class Socket>
connection_handle asio_multiplexer::add_tcp_scribe(abstract_broker* self,
                                                   Socket&& sock) {
  CAF_LOG_TRACE("");
  class impl : public abstract_broker::scribe {
  public:
    impl(abstract_broker* ptr, Socket&& s)
        : scribe(ptr, network::conn_hdl_from_socket(s)),
          launched_(false),
          stream_(s.get_io_service()) {
      stream_.init(std::move(s));
    }
    void configure_read(receive_policy::config config) override {
      CAF_LOG_TRACE("");
      stream_.configure_read(config);
      if (! launched_) {
        launch();
      }
    }
    abstract_broker::buffer_type& wr_buf() override {
      return stream_.wr_buf();
    }
    abstract_broker::buffer_type& rd_buf() override {
      return stream_.rd_buf();
    }
    void stop_reading() override {
      CAF_LOG_TRACE("");
      stream_.stop_reading();
      disconnect(false);
    }
    void flush() override {
      CAF_LOG_TRACE("");
      stream_.flush(this);
    }
    void launch() {
      CAF_LOG_TRACE("");
      CAF_ASSERT(! launched_);
      launched_ = true;
      stream_.start(this);
    }

 private:
    bool launched_;
    stream<Socket> stream_;
  };
  abstract_broker::scribe_pointer ptr = make_counted<impl>(self, std::move(sock));
  self->add_scribe(ptr);
  return ptr->hdl();
}

connection_handle asio_multiplexer::add_tcp_scribe(abstract_broker* self,
                                                   native_socket fd) {
  CAF_LOG_TRACE(CAF_ARG(self) << ", " << CAF_ARG(fd));
  boost::system::error_code ec;
  default_socket sock{backend()};
  sock.assign(boost::asio::ip::tcp::v6(), fd, ec);
  if (ec) {
    sock.assign(boost::asio::ip::tcp::v4(), fd, ec);
  }
  if (ec) {
    throw network_error(ec.message());
  }
  return add_tcp_scribe(self, std::move(sock));
}

connection_handle asio_multiplexer::add_tcp_scribe(abstract_broker* self,
                                                   const std::string& host,
                                                   uint16_t port) {
  CAF_LOG_TRACE(CAF_ARG(self) << ", " << CAF_ARG(host) << ":" << CAF_ARG(port));
  return add_tcp_scribe(self, new_tcp_connection(backend(), host, port));
}

std::pair<accept_handle, uint16_t>
asio_multiplexer::new_tcp_doorman(uint16_t port, const char* in, bool rflag) {
  CAF_LOG_TRACE(CAF_ARG(port) << ", addr = " << (in ? in : "nullptr"));
  default_socket_acceptor fd{backend()};
  ip_bind(fd, port, in, rflag);
  auto id = int64_from_native_socket(fd.native_handle());
  auto assigned_port = fd.local_endpoint().port();
  std::lock_guard<std::mutex> lock(mtx_acceptors_);
  unassigned_acceptors_.insert(std::make_pair(id, std::move(fd)));
  return {accept_handle::from_int(id), assigned_port};
}

void asio_multiplexer::assign_tcp_doorman(abstract_broker* self, accept_handle hdl) {
  CAF_LOG_TRACE("");
  std::lock_guard<std::mutex> lock(mtx_acceptors_);
  auto itr = unassigned_acceptors_.find(hdl.id());
  if (itr != unassigned_acceptors_.end()) {
    add_tcp_doorman(self, std::move(itr->second));
    unassigned_acceptors_.erase(itr);
  }
}

accept_handle
asio_multiplexer::add_tcp_doorman(abstract_broker* self,
                                  default_socket_acceptor&& sock) {
  CAF_LOG_TRACE("sock.fd = " << sock.native_handle());
  CAF_ASSERT(sock.native_handle() != network::invalid_native_socket);
  class impl : public abstract_broker::doorman {
  public:
    impl(abstract_broker* ptr, default_socket_acceptor&& s,
         network::asio_multiplexer& am)
        : doorman(ptr, network::accept_hdl_from_socket(s)),
          acceptor_(am, s.get_io_service()) {
      acceptor_.init(std::move(s));
    }
    void new_connection() override {
      CAF_LOG_TRACE("");
      auto& am = acceptor_.backend();
      accept_msg().handle
        = am.add_tcp_scribe(parent(), std::move(acceptor_.accepted_socket()));
      parent()->invoke_message(invalid_actor_addr, invalid_message_id,
                               accept_msg_);
    }
    void stop_reading() override {
      CAF_LOG_TRACE("");
      acceptor_.stop();
      disconnect(false);
    }
    void launch() override {
      CAF_LOG_TRACE("");
      acceptor_.start(this);
    }

 private:
    network::acceptor<default_socket_acceptor> acceptor_;
  };
  abstract_broker::doorman_pointer ptr
    = make_counted<impl>(self, std::move(sock), *this);
  self->add_doorman(ptr);
  return ptr->hdl();
}

accept_handle asio_multiplexer::add_tcp_doorman(abstract_broker* self,
                                                native_socket fd) {
  default_socket_acceptor sock{backend()};
  boost::system::error_code ec;
  sock.assign(boost::asio::ip::tcp::v6(), fd, ec);
  if (ec) {
    sock.assign(boost::asio::ip::tcp::v4(), fd, ec);
  }
  if (ec) {
    throw network_error(ec.message());
  }
  return add_tcp_doorman(self, std::move(sock));
}

std::pair<accept_handle, uint16_t>
asio_multiplexer::add_tcp_doorman(abstract_broker* self, uint16_t port, const char* in,
                                  bool rflag) {
  default_socket_acceptor fd{backend()};
  ip_bind(fd, port, in, rflag);
  auto p = fd.local_endpoint().port();
  return {add_tcp_doorman(self, std::move(fd)), p};
}

void asio_multiplexer::dispatch_runnable(runnable_ptr ptr) {
  backend().post([=]() {
    ptr->run();
  });
}

asio_multiplexer::asio_multiplexer() {
  // nop
}

asio_multiplexer::~asio_multiplexer() {
  //nop
}

multiplexer::supervisor_ptr asio_multiplexer::make_supervisor() {
  return std::unique_ptr<asio_supervisor>(new asio_supervisor(backend()));
}

void asio_multiplexer::run() {
  CAF_LOG_TRACE("asio-based multiplexer");
  boost::system::error_code ec;
  backend().run(ec);
  if (ec) {
    throw std::runtime_error(ec.message());
  }
}

boost::asio::io_service* asio_multiplexer::pimpl() {
  return &backend_;
}

asio_multiplexer& get_multiplexer_singleton() {
  return static_cast<asio_multiplexer&>(middleman::instance()->backend());
}

} // namesapce network
} // namespace io
} // namespace caf
<|endoftext|>


<commit_before>#include <icvar.h>
#include <string>
#include <sstream>
#include "main.h"
#include "cvar.h"
#include "sound.h"

/*
 * Define ConVars
 *
 * Note:
 *
 *  Notable constructors of ConVar
 *
        ConVar( const char *pName, const char *pDefaultValue, int flags = 0);

        ConVar( const char *pName, const char *pDefaultValue, int flags, const char *pHelpString );

        ConVar( const char *pName, const char *pDefaultValue, int flags, const char *pHelpString,
            bool bMin, float fMin, bool bMax, float fMax );

        ConVar( const char *pName, const char *pDefaultValue, int flags, const char *pHelpString,
            FnChangeCallback_t callback );

        ConVar( const char *pName, const char *pDefaultValue, int flags,
            const char *pHelpString, bool bMin, float fMin, bool bMax, float fMax,
            FnChangeCallback_t callback );

 *
 *  FCVAR_* flags can be found in tier1/iconvar.h
 *  FCVAR_ARCHIVE will allow cvars to be archived
 *
 *  Definition of FnChangeCallback_t:
 *
        typedef void ( *FnChangeCallback_t )( IConVar *var, const char *pOldValue, float flOldValue );
 *
 */

static ConVar prec_version("prec_version", OPENPREC_VERSION, FCVAR_NONE,
        "The current version of open-prec");

ConVar prec_next_demoname("prec_next_demoname", "", FCVAR_NONE,
        "Name of the next demo");

ConVar prec_notify("prec_notify", "1", FCVAR_ARCHIVE,
        "Where to log notifications (started/stopped recording, bookmarks, etc.)\n"
        "\t0 - Log to console\n"
        "\t1 - Log to team chat\n"
        "\t2 - Display on HUD (unimplemented)");

enum struct PrecNotify {
    Console,
    Chat,
    Hud
};

ConVar prec_mode("prec_mode", "2", FCVAR_ARCHIVE,
        "\t0 - Turn off addon\n"
        "\t1 - Record only custom named demos\n"
        "\t2 - Record on servers with mp_tournament 1\n"
        "\t3 - Always record");

ConVar prec_min_streak("prec_min_streak", "4", FCVAR_ARCHIVE,
        "Minimum killstreak to log",
        true, 2.0, false, 0);

ConVar prec_kill_delay("prec_kill_delay", "15", FCVAR_ARCHIVE,
        "Max delay between kills in a killstreak",
        true, 5.0, false, 0);

ConVar prec_dir("prec_dir", "", FCVAR_ARCHIVE,
        "Directory to store demos in");

ConVar prec_sound("prec_sound", "1", FCVAR_ARCHIVE,
        "Play sounds when starting/stopping recording\n"
        "\t0 - Off\n"
        "\t1 - On");

ConVar prec_screens("prec_screens", "0", FCVAR_ARCHIVE,
        "Take screenshots of score and status\n"
        "\t0 - Off\n"
        "\t1 - On");

ConVar prec_log("prec_log", "1", FCVAR_ARCHIVE,
        "\t0 - Don't log killstreaks or bookmarks\n"
        "\t1 - Log killstreaks and bookmarks to killstreaks.txt\n"
        "\t2 - Log separately for each demo\n"
        "\t3 - Log separately for each map");

enum struct LogMode {
    Dont,
    Global,
    PerDemo,
    PerMap
};

ConVar prec_delete_useless_demo("prec_delete_useless_demo", "0", FCVAR_ARCHIVE,
        "Delete demo files without killstreaks or bookmarks (unimplemented)\n"
        "\t0 - Off \n"
        "\t1 - On");

ConVar prec_stv_status("prec_stv_status", "0", FCVAR_ARCHIVE,
        "Show SourceTV statistics after match (unimplemented)\n"
        "\t0 - Off\n"
        "\t1 - On");

ConVar prec_tag("prec_tag", "", FCVAR_ARCHIVE,
        "Tag for demo file name");

static const int g_numCvars = 13;
static ConVar *g_cvarList[] = {
    &prec_version,
    &prec_next_demoname,
    &prec_notify,
    &prec_mode,
    &prec_min_streak,
    &prec_kill_delay,
    &prec_dir,
    &prec_sound,
    &prec_screens,
    &prec_log,
    &prec_delete_useless_demo,
    &prec_stv_status,
    &prec_tag
};

/*
 * Define ConCommands
 *
 * Note:
 *
 *  CON_COMMAND(name, ...) expands to the following
 *
 *      static ConCommand name##_command(...) // Variable
 *      static void name(...) { ... } // Function
 *
 *  First argument passed can safely be assumed to be garbage
 *  Probably a legacy thing, because no built in convars read
 *  the first arg anyways
 */

static const int g_numCommands = 5;
extern ConCommand *g_commandList[g_numCommands];

CON_COMMAND(prec_about, "Display useful information about the plugin") {
    Msg("%s\n%s\n%s\n",
        OPENPREC_NAME " is an open-source demo recording tool for TF2",
        "Version: " OPENPREC_VERSION, "Author: " OPENPREC_AUTH
    );
    play_sound(Sound::About);
}

CON_COMMAND(prec_info, "List commands and cvars") {
    ConCommand *help = g_pCVar->FindCommand("help");
    const char *argv[2];
    argv[0] = "help";
    for (int i = 0; i < g_numCommands; ++i) {
        argv[1] = g_commandList[i]->GetName();
        CCommand args(2, argv);
        help->Dispatch(args);
    }
    for (int i = 0; i < g_numCvars; ++i) {
        argv[1] = g_cvarList[i]->GetName();
        CCommand args(2, argv);
        help->Dispatch(args);
    }
}

std::string parse_demoname( const char *fmt, const char *tag, const char *date,
                            const char *map, const char *blu, const char *red) {
    char ch;
    bool escape = false;
    std::ostringstream fmtbuf, demoname;
    std::string fmtword;
    while ((ch = *fmt++) != 0) {
        if (ch == '%') {
            if (escape) {
                fmtword = fmtbuf.str();
                fmtbuf.str(std::string());
                if (fmtword == "tag") {
                    demoname << tag;
                } else if (fmtword == "date") {
                    demoname << date;
                } else if (fmtword == "map") {
                    demoname << map;
                } else if (fmtword == "blu") {
                    demoname << blu;
                } else if (fmtword == "red") {
                    demoname << red;
                }
            }
            escape = !escape;
        } else if (escape) {
            fmtbuf << ch;
        } else {
            demoname << ch;
        }
    }
    return demoname.str();
}

#ifdef _WIN32
#define PATH_SEPARATOR '\\'
#else
#define PATH_SEPARATOR '/'
#endif
std::string create_file_path(const char *dir, const char *name) {
    std::ostringstream path;
    // Don't worry about multiple separators, most systems will happily ignore them
    path << dir << PATH_SEPARATOR << name;
    return path.str();
}

void prec_auto_record() {
    if (g_pEngineClient->IsRecordingDemo()) return;
    int mode = prec_mode.GetInt();
    const char *nextdemoname = prec_next_demoname.GetString();
    int mp_tournament = g_pCVar->FindVar("mp_tournament")->GetInt();
    switch (static_cast<PrecMode>(mode)) {
        case PrecMode::Off: return;
        case PrecMode::Named: {
            if (strcmp(nextdemoname, "") == 0) return;
        } break;
        case PrecMode::Tournament: {
            if (mp_tournament != 1) return;
        } break;
        case PrecMode::Always: break;
        default: {
            ConNotify("Invalid recording mode, doing nothing");
            return;
        }
    }
    prec_record(CCommand(0, nullptr));
}

#define RECORD_NOTIFICATION "**RECORDING STARTED**"
CON_COMMAND_EXTERN(prec_record, prec_record, "Record a demo") {
    if (g_pEngineClient->IsRecordingDemo()) return;
    time_t posixtime;
    tm *timeinfo;
    ConCommand *record = g_pCVar->FindCommand("record");
    int mp_tournament = g_pCVar->FindVar("mp_tournament")->GetInt();
    const char *argv[2];
    const char *nextdemoname = prec_next_demoname.GetString();
    const char *basedir;
    const char *tag;
    const char *bluteam;
    const char *redteam;
    char mapname[256];
    char datetime[256];
    std::string fallbackname;
    std::string filepath;
    argv[0] = "record";
    basedir = prec_dir.GetString();
    tag = prec_tag.GetString();
    bluteam = g_pCVar->FindVar("mp_tournament_blueteamname")->GetString();
    redteam = g_pCVar->FindVar("mp_tournament_redteamname")->GetString();
    time(&posixtime);
    timeinfo = localtime(&posixtime);
    strftime(datetime, sizeof(datetime), "%F", timeinfo);
    datetime[sizeof(datetime) - 1] = 0;
    g_pEngineClient->GetChapterName(mapname, sizeof(mapname));
    for (int i = 0; i < sizeof(mapname); ++i) {
        if (mapname[i] == ' ') {
            mapname[i] = 0;
            break;
        }
    }
    if (strcmp(nextdemoname, "") == 0) {
        // TODO: Read custom format string
        const char *demonamefmt = "%date%_%map%_%red%_%blu%_%tag%";
        fallbackname = parse_demoname(demonamefmt, tag, datetime, mapname, bluteam, redteam);
        nextdemoname = fallbackname.c_str();
    }
    filepath = create_file_path(basedir, nextdemoname);
    argv[1] = filepath.c_str();
    record->Dispatch(CCommand(2, argv));
    if (g_pEngineClient->IsRecordingDemo()) {
        g_demoIsInternal = true;

        // Write demo info
        g_pPrevDemoInfo.swap(g_pDemoInfo);
        g_pDemoInfo = std::unique_ptr<DemoInfo>(
            new DemoInfo(filepath.c_str(), nextdemoname, tag, datetime, mapname, bluteam, redteam));

        // Write notifications
        int notify = prec_notify.GetInt();
        ConNotify(RECORD_NOTIFICATION);
        play_sound(Sound::Recording);
        if (mp_tournament == 1) {
            switch (static_cast<PrecNotify>(notify)) {
                default:
                case PrecNotify::Console:
                    break;
                case PrecNotify::Chat: {
                    g_pEngineClient->ClientCmd("say_team [" OPENPREC_NAME "]: " RECORD_NOTIFICATION);
                } break;
                case PrecNotify::Hud: {
                    ConNotifyf(OPENPREC_NOFEATURE_MSGF, "Hud notifications");
                } break;
            }
        }
    }
}

#define LOGNAME "killstreaks.txt"
void prec_log_mark(const Mark type, const int tick, const int kills) {
    time_t posixtime;
    tm *timeinfo;
    FileHandle_t logfile = NULL;
    int logmode = prec_log.GetInt();
    int datetimelen;
    const char *basedir = prec_dir.GetString();
    char datetime[256];
    std::ostringstream pathbuf;
    std::ostringstream tickstrbuf;
    std::ostringstream killstrbuf;
    std::string tickstr;
    std::string killstr;
    std::string path, fullpath;
    switch (static_cast<LogMode>(logmode)) {
        default:
        case LogMode::Dont: return;
        case LogMode::Global: {
            path = LOGNAME;
        } break;
        case LogMode::PerDemo: {
            pathbuf << g_pDemoInfo->filename << "_" << LOGNAME;
            path = pathbuf.str();
        } break;
        case LogMode::PerMap: {
            pathbuf << g_pDemoInfo->mapname << "_" << LOGNAME;
            path = pathbuf.str();
        } break;
    }
    fullpath = create_file_path(basedir, path.c_str());
    logfile = g_pFileSystem->Open(fullpath.c_str(), "a");
    if (logfile != NULL) {
        time(&posixtime);
        timeinfo = localtime(&posixtime);
        datetimelen = strftime(datetime, sizeof(datetime), "[%F %T]: ", timeinfo);
        tickstrbuf << tick;
        tickstr = tickstrbuf.str();
        killstrbuf << kills;
        killstr = killstrbuf.str();
        g_pFileSystem->Write(datetime, datetimelen, logfile);
        switch (type) {
            case Mark::Killstreak: {
                ConMarkf("Killstreak (%i kills) @%i in %s", kills, tick, g_pDemoInfo->filename.c_str());
                g_pFileSystem->Write("Killstreak (", 12, logfile);
                g_pFileSystem->Write(killstr.c_str(), killstr.length(), logfile);
                g_pFileSystem->Write(" kills) @", 9, logfile);
            } break;
            case Mark::Bookmark: {
                ConMarkf("%s%i in %s", "Bookmark @", tick, g_pDemoInfo->filename.c_str());
                g_pFileSystem->Write("Bookmark @", 10, logfile);
            } break;
        }
        g_pFileSystem->Write(tickstr.c_str(), tickstr.length(), logfile);
        g_pFileSystem->Write(" in ", 4, logfile);
        g_pFileSystem->Write(g_pDemoInfo->filename.c_str(), g_pDemoInfo->filename.length(), logfile);
        g_pFileSystem->Write("\n", 1, logfile);
        g_pFileSystem->Close(logfile);
        logfile = NULL;
    } else {
        ConNotifyf("%s", "Could not open log file for writing!");
    }
}

CON_COMMAND(prec_mark, "Make a bookmark at the current tick") {
    if (g_pEngineClient->IsRecordingDemo() && g_demoIsInternal) {
        prec_log_mark(Mark::Bookmark, g_pEngineClient->GetDemoRecordingTick(), -1);
    }
}

CON_COMMAND(prec_delete_demo, "Delete previous demo") {
    std::ostringstream pathbuf;
    std::string path;
    if (g_pEngineClient->IsRecordingDemo() && g_demoIsInternal) {
        if (g_pPrevDemoInfo == nullptr) return;
        pathbuf << g_pPrevDemoInfo->fullpath;
    } else {
        if (g_pDemoInfo == nullptr) return;
        pathbuf << g_pDemoInfo->fullpath;
    }
    pathbuf << ".dem";
    path = pathbuf.str();
    ConNotifyf("Deleting demo \"%s\"", path.c_str());
    g_pFileSystem->RemoveFile(path.c_str());
}

ConCommand *g_commandList[g_numCommands] = {
    &prec_about_command,
    &prec_info_command,
    &prec_record_command,
    &prec_mark_command,
    &prec_delete_demo_command
};

bool register_cvars() {
    for (int i = 0; i < g_numCvars; ++i) {
        g_pCVar->RegisterConCommand(g_cvarList[i]);
    }
    return true;
}

void unregister_cvars() {
    for (int i = 0; i < g_numCvars; ++i) {
        g_pCVar->UnregisterConCommand(g_cvarList[i]);
    }
}

bool register_concommands() {
    for (int i = 0; i < g_numCommands; ++i) {
        g_pCVar->RegisterConCommand(g_commandList[i]);
    }
    return true;
}

void unregister_concommands() {
    for (int i = 0; i < g_numCommands; ++i) {
        g_pCVar->UnregisterConCommand(g_commandList[i]);
    }
}
<commit_msg>Reset prec_next_demoname upon recording<commit_after>#include <icvar.h>
#include <string>
#include <sstream>
#include "main.h"
#include "cvar.h"
#include "sound.h"

/*
 * Define ConVars
 *
 * Note:
 *
 *  Notable constructors of ConVar
 *
        ConVar( const char *pName, const char *pDefaultValue, int flags = 0);

        ConVar( const char *pName, const char *pDefaultValue, int flags, const char *pHelpString );

        ConVar( const char *pName, const char *pDefaultValue, int flags, const char *pHelpString,
            bool bMin, float fMin, bool bMax, float fMax );

        ConVar( const char *pName, const char *pDefaultValue, int flags, const char *pHelpString,
            FnChangeCallback_t callback );

        ConVar( const char *pName, const char *pDefaultValue, int flags,
            const char *pHelpString, bool bMin, float fMin, bool bMax, float fMax,
            FnChangeCallback_t callback );

 *
 *  FCVAR_* flags can be found in tier1/iconvar.h
 *  FCVAR_ARCHIVE will allow cvars to be archived
 *
 *  Definition of FnChangeCallback_t:
 *
        typedef void ( *FnChangeCallback_t )( IConVar *var, const char *pOldValue, float flOldValue );
 *
 */

static ConVar prec_version("prec_version", OPENPREC_VERSION, FCVAR_NONE,
        "The current version of open-prec");

ConVar prec_next_demoname("prec_next_demoname", "", FCVAR_NONE,
        "Name of the next demo");

ConVar prec_notify("prec_notify", "1", FCVAR_ARCHIVE,
        "Where to log notifications (started/stopped recording, bookmarks, etc.)\n"
        "\t0 - Log to console\n"
        "\t1 - Log to team chat\n"
        "\t2 - Display on HUD (unimplemented)");

enum struct PrecNotify {
    Console,
    Chat,
    Hud
};

ConVar prec_mode("prec_mode", "2", FCVAR_ARCHIVE,
        "\t0 - Turn off addon\n"
        "\t1 - Record only custom named demos\n"
        "\t2 - Record on servers with mp_tournament 1\n"
        "\t3 - Always record");

ConVar prec_min_streak("prec_min_streak", "4", FCVAR_ARCHIVE,
        "Minimum killstreak to log",
        true, 2.0, false, 0);

ConVar prec_kill_delay("prec_kill_delay", "15", FCVAR_ARCHIVE,
        "Max delay between kills in a killstreak",
        true, 5.0, false, 0);

ConVar prec_dir("prec_dir", "", FCVAR_ARCHIVE,
        "Directory to store demos in");

ConVar prec_sound("prec_sound", "1", FCVAR_ARCHIVE,
        "Play sounds when starting/stopping recording\n"
        "\t0 - Off\n"
        "\t1 - On");

ConVar prec_screens("prec_screens", "0", FCVAR_ARCHIVE,
        "Take screenshots of score and status\n"
        "\t0 - Off\n"
        "\t1 - On");

ConVar prec_log("prec_log", "1", FCVAR_ARCHIVE,
        "\t0 - Don't log killstreaks or bookmarks\n"
        "\t1 - Log killstreaks and bookmarks to killstreaks.txt\n"
        "\t2 - Log separately for each demo\n"
        "\t3 - Log separately for each map");

enum struct LogMode {
    Dont,
    Global,
    PerDemo,
    PerMap
};

ConVar prec_delete_useless_demo("prec_delete_useless_demo", "0", FCVAR_ARCHIVE,
        "Delete demo files without killstreaks or bookmarks (unimplemented)\n"
        "\t0 - Off \n"
        "\t1 - On");

ConVar prec_stv_status("prec_stv_status", "0", FCVAR_ARCHIVE,
        "Show SourceTV statistics after match (unimplemented)\n"
        "\t0 - Off\n"
        "\t1 - On");

ConVar prec_tag("prec_tag", "", FCVAR_ARCHIVE,
        "Tag for demo file name");

static const int g_numCvars = 13;
static ConVar *g_cvarList[] = {
    &prec_version,
    &prec_next_demoname,
    &prec_notify,
    &prec_mode,
    &prec_min_streak,
    &prec_kill_delay,
    &prec_dir,
    &prec_sound,
    &prec_screens,
    &prec_log,
    &prec_delete_useless_demo,
    &prec_stv_status,
    &prec_tag
};

/*
 * Define ConCommands
 *
 * Note:
 *
 *  CON_COMMAND(name, ...) expands to the following
 *
 *      static ConCommand name##_command(...) // Variable
 *      static void name(...) { ... } // Function
 *
 *  First argument passed can safely be assumed to be garbage
 *  Probably a legacy thing, because no built in convars read
 *  the first arg anyways
 */

static const int g_numCommands = 5;
extern ConCommand *g_commandList[g_numCommands];

CON_COMMAND(prec_about, "Display useful information about the plugin") {
    Msg("%s\n%s\n%s\n",
        OPENPREC_NAME " is an open-source demo recording tool for TF2",
        "Version: " OPENPREC_VERSION, "Author: " OPENPREC_AUTH
    );
    play_sound(Sound::About);
}

CON_COMMAND(prec_info, "List commands and cvars") {
    ConCommand *help = g_pCVar->FindCommand("help");
    const char *argv[2];
    argv[0] = "help";
    for (int i = 0; i < g_numCommands; ++i) {
        argv[1] = g_commandList[i]->GetName();
        CCommand args(2, argv);
        help->Dispatch(args);
    }
    for (int i = 0; i < g_numCvars; ++i) {
        argv[1] = g_cvarList[i]->GetName();
        CCommand args(2, argv);
        help->Dispatch(args);
    }
}

std::string parse_demoname( const char *fmt, const char *tag, const char *date,
                            const char *map, const char *blu, const char *red) {
    char ch;
    bool escape = false;
    std::ostringstream fmtbuf, demoname;
    std::string fmtword;
    while ((ch = *fmt++) != 0) {
        if (ch == '%') {
            if (escape) {
                fmtword = fmtbuf.str();
                fmtbuf.str(std::string());
                if (fmtword == "tag") {
                    demoname << tag;
                } else if (fmtword == "date") {
                    demoname << date;
                } else if (fmtword == "map") {
                    demoname << map;
                } else if (fmtword == "blu") {
                    demoname << blu;
                } else if (fmtword == "red") {
                    demoname << red;
                }
            }
            escape = !escape;
        } else if (escape) {
            fmtbuf << ch;
        } else {
            demoname << ch;
        }
    }
    return demoname.str();
}

#ifdef _WIN32
#define PATH_SEPARATOR '\\'
#else
#define PATH_SEPARATOR '/'
#endif
std::string create_file_path(const char *dir, const char *name) {
    std::ostringstream path;
    // Don't worry about multiple separators, most systems will happily ignore them
    path << dir << PATH_SEPARATOR << name;
    return path.str();
}

void prec_auto_record() {
    if (g_pEngineClient->IsRecordingDemo()) return;
    int mode = prec_mode.GetInt();
    const char *nextdemoname = prec_next_demoname.GetString();
    int mp_tournament = g_pCVar->FindVar("mp_tournament")->GetInt();
    switch (static_cast<PrecMode>(mode)) {
        case PrecMode::Off: return;
        case PrecMode::Named: {
            if (strcmp(nextdemoname, "") == 0) return;
        } break;
        case PrecMode::Tournament: {
            if (mp_tournament != 1) return;
        } break;
        case PrecMode::Always: break;
        default: {
            ConNotify("Invalid recording mode, doing nothing");
            return;
        }
    }
    prec_record(CCommand(0, nullptr));
}

#define RECORD_NOTIFICATION "**RECORDING STARTED**"
CON_COMMAND_EXTERN(prec_record, prec_record, "Record a demo") {
    if (g_pEngineClient->IsRecordingDemo()) return;
    time_t posixtime;
    tm *timeinfo;
    ConCommand *record = g_pCVar->FindCommand("record");
    int mp_tournament = g_pCVar->FindVar("mp_tournament")->GetInt();
    const char *argv[2];
    const char *nextdemoname = prec_next_demoname.GetString();
    const char *basedir;
    const char *tag;
    const char *bluteam;
    const char *redteam;
    char mapname[256];
    char datetime[256];
    bool customName = true;
    std::string fallbackname;
    std::string filepath;
    argv[0] = "record";
    basedir = prec_dir.GetString();
    tag = prec_tag.GetString();
    bluteam = g_pCVar->FindVar("mp_tournament_blueteamname")->GetString();
    redteam = g_pCVar->FindVar("mp_tournament_redteamname")->GetString();
    time(&posixtime);
    timeinfo = localtime(&posixtime);
    strftime(datetime, sizeof(datetime), "%F", timeinfo);
    datetime[sizeof(datetime) - 1] = 0;
    g_pEngineClient->GetChapterName(mapname, sizeof(mapname));
    for (int i = 0; i < sizeof(mapname); ++i) {
        if (mapname[i] == ' ') {
            mapname[i] = 0;
            break;
        }
    }
    if (strcmp(nextdemoname, "") == 0) {
        // TODO: Read custom format string
        const char *demonamefmt = "%date%_%map%_%red%_%blu%_%tag%";
        customName = false;
        fallbackname = parse_demoname(demonamefmt, tag, datetime, mapname, bluteam, redteam);
        nextdemoname = fallbackname.c_str();
    }
    filepath = create_file_path(basedir, nextdemoname);
    argv[1] = filepath.c_str();
    record->Dispatch(CCommand(2, argv));
    if (g_pEngineClient->IsRecordingDemo()) {
        g_demoIsInternal = true;
        if (customName) {
            prec_next_demoname.SetValue("");
        }

        // Write demo info
        g_pPrevDemoInfo.swap(g_pDemoInfo);
        g_pDemoInfo = std::unique_ptr<DemoInfo>(
            new DemoInfo(filepath.c_str(), nextdemoname, tag, datetime, mapname, bluteam, redteam));

        // Write notifications
        int notify = prec_notify.GetInt();
        ConNotify(RECORD_NOTIFICATION);
        play_sound(Sound::Recording);
        if (mp_tournament == 1) {
            switch (static_cast<PrecNotify>(notify)) {
                default:
                case PrecNotify::Console:
                    break;
                case PrecNotify::Chat: {
                    g_pEngineClient->ClientCmd("say_team [" OPENPREC_NAME "]: " RECORD_NOTIFICATION);
                } break;
                case PrecNotify::Hud: {
                    ConNotifyf(OPENPREC_NOFEATURE_MSGF, "Hud notifications");
                } break;
            }
        }
    }
}

#define LOGNAME "killstreaks.txt"
void prec_log_mark(const Mark type, const int tick, const int kills) {
    time_t posixtime;
    tm *timeinfo;
    FileHandle_t logfile = NULL;
    int logmode = prec_log.GetInt();
    int datetimelen;
    const char *basedir = prec_dir.GetString();
    char datetime[256];
    std::ostringstream pathbuf;
    std::ostringstream tickstrbuf;
    std::ostringstream killstrbuf;
    std::string tickstr;
    std::string killstr;
    std::string path, fullpath;
    switch (static_cast<LogMode>(logmode)) {
        default:
        case LogMode::Dont: return;
        case LogMode::Global: {
            path = LOGNAME;
        } break;
        case LogMode::PerDemo: {
            pathbuf << g_pDemoInfo->filename << "_" << LOGNAME;
            path = pathbuf.str();
        } break;
        case LogMode::PerMap: {
            pathbuf << g_pDemoInfo->mapname << "_" << LOGNAME;
            path = pathbuf.str();
        } break;
    }
    fullpath = create_file_path(basedir, path.c_str());
    logfile = g_pFileSystem->Open(fullpath.c_str(), "a");
    if (logfile != NULL) {
        time(&posixtime);
        timeinfo = localtime(&posixtime);
        datetimelen = strftime(datetime, sizeof(datetime), "[%F %T]: ", timeinfo);
        tickstrbuf << tick;
        tickstr = tickstrbuf.str();
        killstrbuf << kills;
        killstr = killstrbuf.str();
        g_pFileSystem->Write(datetime, datetimelen, logfile);
        switch (type) {
            case Mark::Killstreak: {
                ConMarkf("Killstreak (%i kills) @%i in %s", kills, tick, g_pDemoInfo->filename.c_str());
                g_pFileSystem->Write("Killstreak (", 12, logfile);
                g_pFileSystem->Write(killstr.c_str(), killstr.length(), logfile);
                g_pFileSystem->Write(" kills) @", 9, logfile);
            } break;
            case Mark::Bookmark: {
                ConMarkf("%s%i in %s", "Bookmark @", tick, g_pDemoInfo->filename.c_str());
                g_pFileSystem->Write("Bookmark @", 10, logfile);
            } break;
        }
        g_pFileSystem->Write(tickstr.c_str(), tickstr.length(), logfile);
        g_pFileSystem->Write(" in ", 4, logfile);
        g_pFileSystem->Write(g_pDemoInfo->filename.c_str(), g_pDemoInfo->filename.length(), logfile);
        g_pFileSystem->Write("\n", 1, logfile);
        g_pFileSystem->Close(logfile);
        logfile = NULL;
    } else {
        ConNotifyf("%s", "Could not open log file for writing!");
    }
}

CON_COMMAND(prec_mark, "Make a bookmark at the current tick") {
    if (g_pEngineClient->IsRecordingDemo() && g_demoIsInternal) {
        prec_log_mark(Mark::Bookmark, g_pEngineClient->GetDemoRecordingTick(), -1);
    }
}

CON_COMMAND(prec_delete_demo, "Delete previous demo") {
    std::ostringstream pathbuf;
    std::string path;
    if (g_pEngineClient->IsRecordingDemo() && g_demoIsInternal) {
        if (g_pPrevDemoInfo == nullptr) return;
        pathbuf << g_pPrevDemoInfo->fullpath;
    } else {
        if (g_pDemoInfo == nullptr) return;
        pathbuf << g_pDemoInfo->fullpath;
    }
    pathbuf << ".dem";
    path = pathbuf.str();
    ConNotifyf("Deleting demo \"%s\"", path.c_str());
    g_pFileSystem->RemoveFile(path.c_str());
}

ConCommand *g_commandList[g_numCommands] = {
    &prec_about_command,
    &prec_info_command,
    &prec_record_command,
    &prec_mark_command,
    &prec_delete_demo_command
};

bool register_cvars() {
    for (int i = 0; i < g_numCvars; ++i) {
        g_pCVar->RegisterConCommand(g_cvarList[i]);
    }
    return true;
}

void unregister_cvars() {
    for (int i = 0; i < g_numCvars; ++i) {
        g_pCVar->UnregisterConCommand(g_cvarList[i]);
    }
}

bool register_concommands() {
    for (int i = 0; i < g_numCommands; ++i) {
        g_pCVar->RegisterConCommand(g_commandList[i]);
    }
    return true;
}

void unregister_concommands() {
    for (int i = 0; i < g_numCommands; ++i) {
        g_pCVar->UnregisterConCommand(g_commandList[i]);
    }
}
<|endoftext|>


<commit_before>#include <ppasskeeper/data.h>

#include <assert.h>

extern "C" ppk_data* ppk_string_data_new(const char* string)
{
	ppk_data* data = new ppk_data;
	size_t len;
	data->type=ppk_string;
	len = strlen(string);
	data->string = new char[len + 1];
	strcpy((char*)data->string, string);
	return data;
}

extern "C" ppk_data* ppk_blob_data_new(const void* data, size_t size)
{
	ppk_data* edata = new ppk_data;
	size_t len;
	edata->type=ppk_blob;
	((ppk_data_blob)edata->blob).data = new char[size];
	memcpy((char*)edata->blob.data, data, size);
	((ppk_data_blob)edata->blob).size=size;
	return edata;
}

extern "C" ppk_data_type ppk_get_data_type(const ppk_data* data)
{
	return data->type;
}

const char* ppk_get_data_string(const ppk_data* data)
{
	if(ppk_get_data_type(data)==ppk_string)
		return data->string;
	else
		return NULL;
}

const ppk_data_blob* ppk_get_data_blob(const ppk_data* data)
{
	if(ppk_get_data_type(data)==ppk_blob)
		return &(data->blob);
	else
		return NULL;
}

extern "C" void ppk_data_free(ppk_data* data)
{
	if (data == NULL)
		return;
	switch (data->type)
	{
	case ppk_string:
		delete[] data->string;
		break;
	case ppk_blob:
		delete[] (char*)data->blob.data;
		break;
	default:
		assert(false);
	};
	delete data;
}

<commit_msg>Use a more c++ way to cast constness. As a bonus, it fixes clang's compilation (but clang crashes later on<commit_after>#include <ppasskeeper/data.h>

#include <assert.h>

extern "C" ppk_data* ppk_string_data_new(const char* string)
{
	ppk_data* data = new ppk_data;
	size_t len;
	data->type=ppk_string;
	len = strlen(string);
	data->string = new char[len + 1];
	strcpy((char*)data->string, string);
	return data;
}

extern "C" ppk_data* ppk_blob_data_new(const void* data, size_t size)
{
	ppk_data* edata = new ppk_data;
	size_t len;
	edata->type=ppk_blob;
	const_cast<ppk_data_blob*>(&(edata->blob))->data = new char[size];
	memcpy((char*)edata->blob.data, data, size);
	const_cast<ppk_data_blob*>(&(edata->blob))->size=size;
	return edata;
}

extern "C" ppk_data_type ppk_get_data_type(const ppk_data* data)
{
	return data->type;
}

const char* ppk_get_data_string(const ppk_data* data)
{
	if(ppk_get_data_type(data)==ppk_string)
		return data->string;
	else
		return NULL;
}

const ppk_data_blob* ppk_get_data_blob(const ppk_data* data)
{
	if(ppk_get_data_type(data)==ppk_blob)
		return &(data->blob);
	else
		return NULL;
}

extern "C" void ppk_data_free(ppk_data* data)
{
	if (data == NULL)
		return;
	switch (data->type)
	{
	case ppk_string:
		delete[] data->string;
		break;
	case ppk_blob:
		delete[] (char*)data->blob.data;
		break;
	default:
		assert(false);
	};
	delete data;
}

<|endoftext|>


<commit_before>/*

  This program will add histograms from a list of root files and write them
  to a target root file. The target file is newly created and must not be
  identical to one of the source files.

  Syntax:

  hadd targetfile source1 source2 ...

  Author: Sven A. Schmidt, sven.schmidt@cern.ch
  Date:   13.2.2001

  This code is based on the hadd.C example by Rene Brun and Dirk Geppert,
  which had a problem with directories more than one level deep.
  (see macro hadd_old.C for this previous implementation).

  I have tested this macro on rootfiles with one and two dimensional
  histograms, and two levels of subdirectories. Feel free to send comments
  or bug reports to me.

 */

#include <string>
#include "TChain.h"
#include "TFile.h"
#include "TH1.h"
#include "TKey.h"
#include "Riostream.h"

using std::string;

TList *FileList;
TFile *Target;

void MergeRootfile( TDirectory *target, TList *sourcelist );

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

  if ( argc < 4 || "-h" == string(argv[1]) || "--help" == string(argv[1]) ) {
    cout << "Usage: " << argv[0] << " targetfile source1 source2 [source3 ...]" << endl;
    cout << "This program will add histograms from a list of root files and write them" << endl;
    cout << "to a target root file. The target file is newly created and must not be" << endl;
    cout << "identical to one of the source files." << endl;
    cout << "Supply at least two source files for this to make sense... ;-)" << endl;
    return 1;
  }
   FileList = new TList();

  cout << "Target file: " << argv[1] << endl;
  Target = TFile::Open( argv[1], "RECREATE" );

  for ( int i = 2; i < argc; i++ ) {
    cout << "Source file " << i-1 << ": " << argv[i] << endl;
    FileList->Add( TFile::Open( argv[i] ) );
  }

  MergeRootfile( Target, FileList );

  return 0;
}

void MergeRootfile( TDirectory *target, TList *sourcelist ) {

  //  cout << "Target path: " << target->GetPath() << endl;
  TString path( (char*)strstr( target->GetPath(), ":" ) );
  path.Remove( 0, 2 );

  TFile *first_source = (TFile*)sourcelist->First();
  first_source->cd( path );
  TDirectory *current_sourcedir = gDirectory;

  // loop over all keys in this directory
  TChain *globChain = 0;
  TIter nextkey( current_sourcedir->GetListOfKeys() );
  TKey *key;
  while ( (key = (TKey*)nextkey())) {

    // read object from first source file
    first_source->cd( path );
    TObject *obj = key->ReadObj();

    if ( obj->IsA()->InheritsFrom( "TH1" ) ) {
      // descendant of TH1 -> merge it

      //      cout << "Merging histogram " << obj->GetName() << endl;
      TH1 *h1 = (TH1*)obj;

      // loop over all source files and add the content of the
      // correspondant histogram to the one pointed to by "h1"
      TFile *nextsource = (TFile*)sourcelist->After( first_source );
      while ( nextsource ) {

        // make sure we are at the correct directory level by cd'ing to path
        nextsource->cd( path );
        TH1 *h2 = (TH1*)gDirectory->Get( h1->GetName() );
        if ( h2 ) {
          h1->Add( h2 );
          delete h2; // don't know if this is necessary, i.e. if
                     // h2 is created by the call to gDirectory above.
        }

        nextsource = (TFile*)sourcelist->After( nextsource );
      }
    }
    else if ( obj->IsA()->InheritsFrom( "TTree" ) ) {

      // loop over all source files create a chain of Trees "globChain"
      TString obj_name;
      if (path.Length()) {
         obj_name = path + "/" + obj->GetName();
      } else {
         obj_name = obj->GetName();
      }

      globChain = new TChain(obj_name);
      globChain->Add(first_source->GetName());
      TFile *nextsource = (TFile*)sourcelist->After( first_source );
      //      const char* file_name = nextsource->GetName();
      // cout << "file name  " << file_name << endl;
      while ( nextsource ) {

         globChain->Add(nextsource->GetName());
         nextsource = (TFile*)sourcelist->After( nextsource );
      }

    } else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) {
      // it's a subdirectory

      cout << "Found subdirectory " << obj->GetName() << endl;

      // create a new subdir of same name and title in the target file
      target->cd();
      TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() );

      // newdir is now the starting point of another round of merging
      // newdir still knows its depth within the target file via
      // GetPath(), so we can still figure out where we are in the recursion
      MergeRootfile( newdir, sourcelist );

    } else {

      // object is of no type that we know or can handle
      cout << "Unknown object type, name: "
           << obj->GetName() << " title: " << obj->GetTitle() << endl;
    }

    // now write the merged histogram (which is "in" obj) to the target file
    // note that this will just store obj in the current directory level,
    // which is not persistent until the complete directory itself is stored
    // by "target->Write()" below
    if ( obj ) {
       target->cd();

       //!!if the object is a tree, it is stored in globChain...
       if(obj->IsA()->InheritsFrom( "TTree" ))
          globChain->Merge(target->GetFile(),0,"keep");
       else
          obj->Write( key->GetName() );
    }

  } // while ( ( TKey *key = (TKey*)nextkey() ) )

  // save modifications to target file
  target->Write();

}
<commit_msg>Remove statement using std::string<commit_after>/*

  This program will add histograms from a list of root files and write them
  to a target root file. The target file is newly created and must not be
  identical to one of the source files.

  Syntax:

  hadd targetfile source1 source2 ...

  Author: Sven A. Schmidt, sven.schmidt@cern.ch
  Date:   13.2.2001

  This code is based on the hadd.C example by Rene Brun and Dirk Geppert,
  which had a problem with directories more than one level deep.
  (see macro hadd_old.C for this previous implementation).

  I have tested this macro on rootfiles with one and two dimensional
  histograms, and two levels of subdirectories. Feel free to send comments
  or bug reports to me.

 */

#include <string>
#include "TChain.h"
#include "TFile.h"
#include "TH1.h"
#include "TKey.h"
#include "Riostream.h"

TList *FileList;
TFile *Target;

void MergeRootfile( TDirectory *target, TList *sourcelist );

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

  if ( argc < 4 || "-h" == string(argv[1]) || "--help" == string(argv[1]) ) {
    cout << "Usage: " << argv[0] << " targetfile source1 source2 [source3 ...]" << endl;
    cout << "This program will add histograms from a list of root files and write them" << endl;
    cout << "to a target root file. The target file is newly created and must not be" << endl;
    cout << "identical to one of the source files." << endl;
    cout << "Supply at least two source files for this to make sense... ;-)" << endl;
    return 1;
  }
   FileList = new TList();

  cout << "Target file: " << argv[1] << endl;
  Target = TFile::Open( argv[1], "RECREATE" );

  for ( int i = 2; i < argc; i++ ) {
    cout << "Source file " << i-1 << ": " << argv[i] << endl;
    FileList->Add( TFile::Open( argv[i] ) );
  }

  MergeRootfile( Target, FileList );

  return 0;
}

void MergeRootfile( TDirectory *target, TList *sourcelist ) {

  //  cout << "Target path: " << target->GetPath() << endl;
  TString path( (char*)strstr( target->GetPath(), ":" ) );
  path.Remove( 0, 2 );

  TFile *first_source = (TFile*)sourcelist->First();
  first_source->cd( path );
  TDirectory *current_sourcedir = gDirectory;

  // loop over all keys in this directory
  TChain *globChain = 0;
  TIter nextkey( current_sourcedir->GetListOfKeys() );
  TKey *key;
  while ( (key = (TKey*)nextkey())) {

    // read object from first source file
    first_source->cd( path );
    TObject *obj = key->ReadObj();

    if ( obj->IsA()->InheritsFrom( "TH1" ) ) {
      // descendant of TH1 -> merge it

      //      cout << "Merging histogram " << obj->GetName() << endl;
      TH1 *h1 = (TH1*)obj;

      // loop over all source files and add the content of the
      // correspondant histogram to the one pointed to by "h1"
      TFile *nextsource = (TFile*)sourcelist->After( first_source );
      while ( nextsource ) {

        // make sure we are at the correct directory level by cd'ing to path
        nextsource->cd( path );
        TH1 *h2 = (TH1*)gDirectory->Get( h1->GetName() );
        if ( h2 ) {
          h1->Add( h2 );
          delete h2; // don't know if this is necessary, i.e. if
                     // h2 is created by the call to gDirectory above.
        }

        nextsource = (TFile*)sourcelist->After( nextsource );
      }
    }
    else if ( obj->IsA()->InheritsFrom( "TTree" ) ) {

      // loop over all source files create a chain of Trees "globChain"
      TString obj_name;
      if (path.Length()) {
         obj_name = path + "/" + obj->GetName();
      } else {
         obj_name = obj->GetName();
      }

      globChain = new TChain(obj_name);
      globChain->Add(first_source->GetName());
      TFile *nextsource = (TFile*)sourcelist->After( first_source );
      //      const char* file_name = nextsource->GetName();
      // cout << "file name  " << file_name << endl;
      while ( nextsource ) {

         globChain->Add(nextsource->GetName());
         nextsource = (TFile*)sourcelist->After( nextsource );
      }

    } else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) {
      // it's a subdirectory

      cout << "Found subdirectory " << obj->GetName() << endl;

      // create a new subdir of same name and title in the target file
      target->cd();
      TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() );

      // newdir is now the starting point of another round of merging
      // newdir still knows its depth within the target file via
      // GetPath(), so we can still figure out where we are in the recursion
      MergeRootfile( newdir, sourcelist );

    } else {

      // object is of no type that we know or can handle
      cout << "Unknown object type, name: "
           << obj->GetName() << " title: " << obj->GetTitle() << endl;
    }

    // now write the merged histogram (which is "in" obj) to the target file
    // note that this will just store obj in the current directory level,
    // which is not persistent until the complete directory itself is stored
    // by "target->Write()" below
    if ( obj ) {
       target->cd();

       //!!if the object is a tree, it is stored in globChain...
       if(obj->IsA()->InheritsFrom( "TTree" ))
          globChain->Merge(target->GetFile(),0,"keep");
       else
          obj->Write( key->GetName() );
    }

  } // while ( ( TKey *key = (TKey*)nextkey() ) )

  // save modifications to target file
  target->Write();

}
<|endoftext|>