<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: listeneriter.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 09:53:44 $
 *
 *  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 _SVT_LISTENERITER_HXX
#define _SVT_LISTENERITER_HXX

#ifndef INCLUDED_SVLDLLAPI_H
#include "svtools/svldllapi.h"
#endif

#ifndef _RTTI_HXX //autogen
#include <tools/rtti.hxx>
#endif

class SvtListener;
class SvtListenerBase;
class SvtBroadcaster;

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

class SVL_DLLPUBLIC SvtListenerIter
{
    friend class SvtListenerBase;

    SvtBroadcaster& rRoot;
    SvtListenerBase *pAkt, *pDelNext;

    // for the update of all iterator's, if a listener is added or removed
    // at the same time.
    static SvtListenerIter *pListenerIters;
    SvtListenerIter *pNxtIter;
    TypeId aSrchId;             // fuer First/Next - suche diesen Type

    SVL_DLLPRIVATE static void RemoveListener( SvtListenerBase& rDel,
                                               SvtListenerBase* pNext );

public:
    SvtListenerIter( SvtBroadcaster& );
    ~SvtListenerIter();

    const SvtBroadcaster& GetBroadcaster() const    { return rRoot; }
          SvtBroadcaster& GetBroadcaster()          { return rRoot; }

    SvtListener* GoNext();          // to the next
    SvtListener* GoPrev();          // to the previous

    SvtListener* GoStart();         // to the start of the list
    SvtListener* GoEnd();           // to the end of the list

    SvtListener* GoRoot();          // to the root
    SvtListener* GetCurr() const;   // returns the current

    int IsChanged() const       { return pDelNext != pAkt; }

    SvtListener* First( TypeId nType );
    SvtListener* Next();
};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.3.772); FILE MERGED 2008/04/01 15:44:22 thb 1.3.772.3: #i85898# Stripping all external header guards 2008/04/01 12:43:07 thb 1.3.772.2: #i85898# Stripping all external header guards 2008/03/31 13:00:53 rt 1.3.772.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: listeneriter.hxx,v $
 * $Revision: 1.4 $
 *
 * 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 _SVT_LISTENERITER_HXX
#define _SVT_LISTENERITER_HXX

#include "svtools/svldllapi.h"
#include <tools/rtti.hxx>

class SvtListener;
class SvtListenerBase;
class SvtBroadcaster;

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

class SVL_DLLPUBLIC SvtListenerIter
{
    friend class SvtListenerBase;

    SvtBroadcaster& rRoot;
    SvtListenerBase *pAkt, *pDelNext;

    // for the update of all iterator's, if a listener is added or removed
    // at the same time.
    static SvtListenerIter *pListenerIters;
    SvtListenerIter *pNxtIter;
    TypeId aSrchId;             // fuer First/Next - suche diesen Type

    SVL_DLLPRIVATE static void RemoveListener( SvtListenerBase& rDel,
                                               SvtListenerBase* pNext );

public:
    SvtListenerIter( SvtBroadcaster& );
    ~SvtListenerIter();

    const SvtBroadcaster& GetBroadcaster() const    { return rRoot; }
          SvtBroadcaster& GetBroadcaster()          { return rRoot; }

    SvtListener* GoNext();          // to the next
    SvtListener* GoPrev();          // to the previous

    SvtListener* GoStart();         // to the start of the list
    SvtListener* GoEnd();           // to the end of the list

    SvtListener* GoRoot();          // to the root
    SvtListener* GetCurr() const;   // returns the current

    int IsChanged() const       { return pDelNext != pAkt; }

    SvtListener* First( TypeId nType );
    SvtListener* Next();
};

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fmobjfac.cxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 18:13:34 $
 *
 *  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
 *
 ************************************************************************/

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

#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif

#ifndef _SVDOBJ_HXX
#include <svx/svdobj.hxx>
#endif

#ifndef _SVX_FMTOOLS_HXX
#include "fmtools.hxx"
#endif

#ifndef _SVX_FMSERVS_HXX
#include "fmservs.hxx"
#endif

#ifndef _FM_FMOBJFAC_HXX
#include "fmobjfac.hxx"
#endif

#ifndef _FM_FMGLOB_HXX
#include <svx/fmglob.hxx>
#endif

#ifndef _FM_FMOBJ_HXX
#include "fmobj.hxx"
#endif

#ifndef _SVX_FMSHIMP_HXX
#include "fmshimp.hxx"
#endif

#ifndef _FM_FMSHELL_HXX
#include <svx/fmshell.hxx>
#endif

#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif

#ifndef _SVX_TBXFORM_HXX
#include "tbxform.hxx"
#endif

#ifndef _TOOLS_RESID_HXX //autogen
#include <tools/resid.hxx>
#endif

#ifndef _SVX_FMRESIDS_HRC
#include "fmresids.hrc"
#endif

#ifndef _SHL_HXX
#include <tools/shl.hxx>
#endif

#ifndef _SVX_DIALMGR_HXX
#include <svx/dialmgr.hxx>
#endif

#ifndef _SVX_FMSERVS_HXX
#include "fmservs.hxx"
#endif

#ifndef _SVX_TABWIN_HXX
#include "tabwin.hxx"
#endif

#ifndef _SVX_FMEXPL_HXX
#include "fmexpl.hxx"
#endif

#ifndef _SVX_FILTNAV_HXX
#include "filtnav.hxx"
#endif

#ifndef _SVX_FMPROP_HRC
#include "fmprop.hrc"
#endif
#ifndef SVX_FMPROPBRW_HXX
#include "fmPropBrw.hxx"
#endif

#ifndef _SVX_DATANAVI_HXX
#include "datanavi.hxx"
#endif

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::svxform;

static BOOL bInit = FALSE;

/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/
FmFormObjFactory::FmFormObjFactory()
{
    if ( !bInit )
    {
        SdrObjFactory::InsertMakeObjectHdl(LINK(this, FmFormObjFactory, MakeObject));

        //////////////////////////////////////////////////////////////////////
        // Konfigurations-::com::sun::star::frame::Controller und NavigationBar registrieren
        SvxFmTbxCtlConfig::RegisterControl( SID_FM_CONFIG );
        SvxFmTbxCtlAbsRec::RegisterControl( SID_FM_RECORD_ABSOLUTE );
        SvxFmTbxCtlRecText::RegisterControl( SID_FM_RECORD_TEXT );
        SvxFmTbxCtlRecFromText::RegisterControl( SID_FM_RECORD_FROM_TEXT );
        SvxFmTbxCtlRecTotal::RegisterControl( SID_FM_RECORD_TOTAL );
        SvxFmTbxPrevRec::RegisterControl( SID_FM_RECORD_PREV );
        SvxFmTbxNextRec::RegisterControl( SID_FM_RECORD_NEXT );
        ControlConversionMenuController::RegisterControl(SID_FM_CHANGECONTROLTYPE);

        // Registrieung von globalen fenstern
        FmFieldWinMgr::RegisterChildWindow();
        FmPropBrwMgr::RegisterChildWindow();
        NavigatorFrameManager::RegisterChildWindow();
        DataNavigatorManager::RegisterChildWindow();
        FmFilterNavigatorWinMgr::RegisterChildWindow();

        //////////////////////////////////////////////////////////////////////
        // Interface fuer die Formshell registrieren
        FmFormShell::RegisterInterface(0);

        ImplSmartRegisterUnoServices();
        bInit = TRUE;
    }
}

/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/
FmFormObjFactory::~FmFormObjFactory()
{
}

/*************************************************************************
|*
|* ::com::sun::star::form::Form-Objekte erzeugen
|*
\************************************************************************/
namespace
{
    void    lcl_initProperty( FmFormObj* _pObject, const ::rtl::OUString& _rPropName, const Any& _rValue )
    {
        try
        {
            Reference< XPropertySet >  xModelSet( _pObject->GetUnoControlModel(), UNO_QUERY );
            if ( xModelSet.is() )
                xModelSet->setPropertyValue( _rPropName, _rValue );
        }
        catch( const Exception& )
        {
            DBG_ERROR( "lcl_initProperty: caught an exception!" );
        }
    }
}

IMPL_LINK(FmFormObjFactory, MakeObject, SdrObjFactory*, pObjFactory)
{
    if (pObjFactory->nInventor == FmFormInventor)
    {
        ::rtl::OUString sServiceSpecifier;

        typedef ::std::vector< ::std::pair< ::rtl::OUString, Any > > PropertyValueArray;
        PropertyValueArray aInitialProperties;

        switch ( pObjFactory->nIdentifier )
        {
            case OBJ_FM_EDIT:
                sServiceSpecifier = FM_COMPONENT_EDIT;
                break;

            case OBJ_FM_BUTTON:
                sServiceSpecifier = FM_COMPONENT_COMMANDBUTTON;
                break;

            case OBJ_FM_FIXEDTEXT:
                sServiceSpecifier = FM_COMPONENT_FIXEDTEXT;
                break;

            case OBJ_FM_LISTBOX:
                sServiceSpecifier = FM_COMPONENT_LISTBOX;
                break;

            case OBJ_FM_CHECKBOX:
                sServiceSpecifier = FM_COMPONENT_CHECKBOX;
                break;

            case OBJ_FM_RADIOBUTTON:
                sServiceSpecifier = FM_COMPONENT_RADIOBUTTON;
                break;

            case OBJ_FM_GROUPBOX:
                sServiceSpecifier = FM_COMPONENT_GROUPBOX;
                break;

            case OBJ_FM_COMBOBOX:
                sServiceSpecifier = FM_COMPONENT_COMBOBOX;
                break;

            case OBJ_FM_GRID:
                sServiceSpecifier = FM_COMPONENT_GRID;
                break;

            case OBJ_FM_IMAGEBUTTON:
                sServiceSpecifier = FM_COMPONENT_IMAGEBUTTON;
                break;

            case OBJ_FM_FILECONTROL:
                sServiceSpecifier = FM_COMPONENT_FILECONTROL;
                break;

            case OBJ_FM_DATEFIELD:
                sServiceSpecifier = FM_COMPONENT_DATEFIELD;
                break;

            case OBJ_FM_TIMEFIELD:
                sServiceSpecifier = FM_COMPONENT_TIMEFIELD;
                aInitialProperties.push_back( PropertyValueArray::value_type( FM_PROP_TIMEMAX, makeAny( (sal_Int32)( Time( 23, 59, 59, 99 ).GetTime() ) ) ) );
                break;

            case OBJ_FM_NUMERICFIELD:
                sServiceSpecifier = FM_COMPONENT_NUMERICFIELD;
                break;

            case OBJ_FM_CURRENCYFIELD:
                sServiceSpecifier = FM_COMPONENT_CURRENCYFIELD;
                break;

            case OBJ_FM_PATTERNFIELD:
                sServiceSpecifier = FM_COMPONENT_PATTERNFIELD;
                break;

            case OBJ_FM_HIDDEN:
                sServiceSpecifier = FM_COMPONENT_HIDDEN;
                break;

            case OBJ_FM_IMAGECONTROL:
                sServiceSpecifier = FM_COMPONENT_IMAGECONTROL;
                break;

            case OBJ_FM_FORMATTEDFIELD:
                sServiceSpecifier = FM_COMPONENT_FORMATTEDFIELD;
                break;

            case OBJ_FM_NAVIGATIONBAR:
                sServiceSpecifier = FM_SUN_COMPONENT_NAVIGATIONBAR;
                break;

            case OBJ_FM_SCROLLBAR:
                sServiceSpecifier = FM_SUN_COMPONENT_SCROLLBAR;
                aInitialProperties.push_back( PropertyValueArray::value_type( FM_PROP_BORDER, makeAny( (sal_Int16)0 ) ) );
                break;

            case OBJ_FM_SPINBUTTON:
                sServiceSpecifier = FM_SUN_COMPONENT_SPINBUTTON;
                aInitialProperties.push_back( PropertyValueArray::value_type( FM_PROP_BORDER, makeAny( (sal_Int16)0 ) ) );
                break;
        }

        // create the actual object
        if ( sServiceSpecifier.getLength() )
            pObjFactory->pNewObj = new FmFormObj( sServiceSpecifier, pObjFactory->nIdentifier );
        else
            pObjFactory->pNewObj = new FmFormObj( pObjFactory->nIdentifier );

        // initialize some properties which we want to differ from the defaults
        for (   PropertyValueArray::const_iterator aInitProp = aInitialProperties.begin();
                aInitProp != aInitialProperties.end();
                ++aInitProp
            )
        {
            lcl_initProperty(
                static_cast< FmFormObj* >( pObjFactory->pNewObj ),
                aInitProp->first,
                aInitProp->second
            );
        }
    }

    return 0;
}

<commit_msg>INTEGRATION: CWS changefileheader (1.17.368); FILE MERGED 2008/04/01 15:51:01 thb 1.17.368.3: #i85898# Stripping all external header guards 2008/04/01 12:48:51 thb 1.17.368.2: #i85898# Stripping all external header guards 2008/03/31 14:21:54 rt 1.17.368.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: fmobjfac.cxx,v $
 * $Revision: 1.18 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include <comphelper/stl_types.hxx>
#include <svx/svdobj.hxx>
#include "fmtools.hxx"
#include "fmservs.hxx"

#ifndef _FM_FMOBJFAC_HXX
#include "fmobjfac.hxx"
#endif

#ifndef _FM_FMGLOB_HXX
#include <svx/fmglob.hxx>
#endif

#ifndef _FM_FMOBJ_HXX
#include "fmobj.hxx"
#endif
#include "fmshimp.hxx"

#ifndef _FM_FMSHELL_HXX
#include <svx/fmshell.hxx>
#endif

#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#include "tbxform.hxx"
#include <tools/resid.hxx>

#ifndef _SVX_FMRESIDS_HRC
#include "fmresids.hrc"
#endif
#include <tools/shl.hxx>
#include <svx/dialmgr.hxx>
#include "fmservs.hxx"
#include "tabwin.hxx"
#include "fmexpl.hxx"
#include "filtnav.hxx"

#ifndef _SVX_FMPROP_HRC
#include "fmprop.hrc"
#endif
#include "fmPropBrw.hxx"
#include "datanavi.hxx"

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::svxform;

static BOOL bInit = FALSE;

/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/
FmFormObjFactory::FmFormObjFactory()
{
    if ( !bInit )
    {
        SdrObjFactory::InsertMakeObjectHdl(LINK(this, FmFormObjFactory, MakeObject));

        //////////////////////////////////////////////////////////////////////
        // Konfigurations-::com::sun::star::frame::Controller und NavigationBar registrieren
        SvxFmTbxCtlConfig::RegisterControl( SID_FM_CONFIG );
        SvxFmTbxCtlAbsRec::RegisterControl( SID_FM_RECORD_ABSOLUTE );
        SvxFmTbxCtlRecText::RegisterControl( SID_FM_RECORD_TEXT );
        SvxFmTbxCtlRecFromText::RegisterControl( SID_FM_RECORD_FROM_TEXT );
        SvxFmTbxCtlRecTotal::RegisterControl( SID_FM_RECORD_TOTAL );
        SvxFmTbxPrevRec::RegisterControl( SID_FM_RECORD_PREV );
        SvxFmTbxNextRec::RegisterControl( SID_FM_RECORD_NEXT );
        ControlConversionMenuController::RegisterControl(SID_FM_CHANGECONTROLTYPE);

        // Registrieung von globalen fenstern
        FmFieldWinMgr::RegisterChildWindow();
        FmPropBrwMgr::RegisterChildWindow();
        NavigatorFrameManager::RegisterChildWindow();
        DataNavigatorManager::RegisterChildWindow();
        FmFilterNavigatorWinMgr::RegisterChildWindow();

        //////////////////////////////////////////////////////////////////////
        // Interface fuer die Formshell registrieren
        FmFormShell::RegisterInterface(0);

        ImplSmartRegisterUnoServices();
        bInit = TRUE;
    }
}

/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/
FmFormObjFactory::~FmFormObjFactory()
{
}

/*************************************************************************
|*
|* ::com::sun::star::form::Form-Objekte erzeugen
|*
\************************************************************************/
namespace
{
    void    lcl_initProperty( FmFormObj* _pObject, const ::rtl::OUString& _rPropName, const Any& _rValue )
    {
        try
        {
            Reference< XPropertySet >  xModelSet( _pObject->GetUnoControlModel(), UNO_QUERY );
            if ( xModelSet.is() )
                xModelSet->setPropertyValue( _rPropName, _rValue );
        }
        catch( const Exception& )
        {
            DBG_ERROR( "lcl_initProperty: caught an exception!" );
        }
    }
}

IMPL_LINK(FmFormObjFactory, MakeObject, SdrObjFactory*, pObjFactory)
{
    if (pObjFactory->nInventor == FmFormInventor)
    {
        ::rtl::OUString sServiceSpecifier;

        typedef ::std::vector< ::std::pair< ::rtl::OUString, Any > > PropertyValueArray;
        PropertyValueArray aInitialProperties;

        switch ( pObjFactory->nIdentifier )
        {
            case OBJ_FM_EDIT:
                sServiceSpecifier = FM_COMPONENT_EDIT;
                break;

            case OBJ_FM_BUTTON:
                sServiceSpecifier = FM_COMPONENT_COMMANDBUTTON;
                break;

            case OBJ_FM_FIXEDTEXT:
                sServiceSpecifier = FM_COMPONENT_FIXEDTEXT;
                break;

            case OBJ_FM_LISTBOX:
                sServiceSpecifier = FM_COMPONENT_LISTBOX;
                break;

            case OBJ_FM_CHECKBOX:
                sServiceSpecifier = FM_COMPONENT_CHECKBOX;
                break;

            case OBJ_FM_RADIOBUTTON:
                sServiceSpecifier = FM_COMPONENT_RADIOBUTTON;
                break;

            case OBJ_FM_GROUPBOX:
                sServiceSpecifier = FM_COMPONENT_GROUPBOX;
                break;

            case OBJ_FM_COMBOBOX:
                sServiceSpecifier = FM_COMPONENT_COMBOBOX;
                break;

            case OBJ_FM_GRID:
                sServiceSpecifier = FM_COMPONENT_GRID;
                break;

            case OBJ_FM_IMAGEBUTTON:
                sServiceSpecifier = FM_COMPONENT_IMAGEBUTTON;
                break;

            case OBJ_FM_FILECONTROL:
                sServiceSpecifier = FM_COMPONENT_FILECONTROL;
                break;

            case OBJ_FM_DATEFIELD:
                sServiceSpecifier = FM_COMPONENT_DATEFIELD;
                break;

            case OBJ_FM_TIMEFIELD:
                sServiceSpecifier = FM_COMPONENT_TIMEFIELD;
                aInitialProperties.push_back( PropertyValueArray::value_type( FM_PROP_TIMEMAX, makeAny( (sal_Int32)( Time( 23, 59, 59, 99 ).GetTime() ) ) ) );
                break;

            case OBJ_FM_NUMERICFIELD:
                sServiceSpecifier = FM_COMPONENT_NUMERICFIELD;
                break;

            case OBJ_FM_CURRENCYFIELD:
                sServiceSpecifier = FM_COMPONENT_CURRENCYFIELD;
                break;

            case OBJ_FM_PATTERNFIELD:
                sServiceSpecifier = FM_COMPONENT_PATTERNFIELD;
                break;

            case OBJ_FM_HIDDEN:
                sServiceSpecifier = FM_COMPONENT_HIDDEN;
                break;

            case OBJ_FM_IMAGECONTROL:
                sServiceSpecifier = FM_COMPONENT_IMAGECONTROL;
                break;

            case OBJ_FM_FORMATTEDFIELD:
                sServiceSpecifier = FM_COMPONENT_FORMATTEDFIELD;
                break;

            case OBJ_FM_NAVIGATIONBAR:
                sServiceSpecifier = FM_SUN_COMPONENT_NAVIGATIONBAR;
                break;

            case OBJ_FM_SCROLLBAR:
                sServiceSpecifier = FM_SUN_COMPONENT_SCROLLBAR;
                aInitialProperties.push_back( PropertyValueArray::value_type( FM_PROP_BORDER, makeAny( (sal_Int16)0 ) ) );
                break;

            case OBJ_FM_SPINBUTTON:
                sServiceSpecifier = FM_SUN_COMPONENT_SPINBUTTON;
                aInitialProperties.push_back( PropertyValueArray::value_type( FM_PROP_BORDER, makeAny( (sal_Int16)0 ) ) );
                break;
        }

        // create the actual object
        if ( sServiceSpecifier.getLength() )
            pObjFactory->pNewObj = new FmFormObj( sServiceSpecifier, pObjFactory->nIdentifier );
        else
            pObjFactory->pNewObj = new FmFormObj( pObjFactory->nIdentifier );

        // initialize some properties which we want to differ from the defaults
        for (   PropertyValueArray::const_iterator aInitProp = aInitialProperties.begin();
                aInitProp != aInitialProperties.end();
                ++aInitProp
            )
        {
            lcl_initProperty(
                static_cast< FmFormObj* >( pObjFactory->pNewObj ),
                aInitProp->first,
                aInitProp->second
            );
        }
    }

    return 0;
}

<|endoftext|>


<commit_before>/*
 * XMSS Tools
 * (C) 2017 Matthias Gierlings
 *
 * Botan is released under the Simplified BSD License (see license.txt)
 **/

#include <botan/xmss_tools.h>

namespace Botan {

#if defined(BOTAN_TARGET_OS_HAS_THREADS)

size_t XMSS_Tools::max_threads()
   {
   static const size_t threads { bench_threads() };
   return threads;
   }

size_t XMSS_Tools::bench_threads()
   {
   if(std::thread::hardware_concurrency() <= 1)
      {
      return 1;
      }
   const size_t BENCH_ITERATIONS = 1000;
   std::vector<std::thread> threads;
   threads.reserve(std::thread::hardware_concurrency());
   std::vector<std::chrono::nanoseconds> durations;

   std::vector<size_t> concurrency { std::thread::hardware_concurrency(),
                                     std::thread::hardware_concurrency() / 2 };

   for(const auto& cc : concurrency)
      {
      AutoSeeded_RNG rng;
      std::vector<XMSS_Hash> hash(std::thread::hardware_concurrency(),
                                  XMSS_Hash("SHA-256"));
      std::vector<secure_vector<uint8_t>> data(
          std::thread::hardware_concurrency(),
          rng.random_vec(hash[0].output_length()));
      auto start = std::chrono::high_resolution_clock::now();
      for(size_t i = 0; i < cc; ++i)
         {
         auto& hs = hash[i];
         auto& d = data[i];
         threads.emplace_back(
            std::thread([&BENCH_ITERATIONS, &i, &cc, &hs, &d]()
               {
               for(size_t n = 0;
                   n < BENCH_ITERATIONS * (std::thread::hardware_concurrency() /
                                           cc);
                   n++)
                  {
                  hs.h(d, d, d);
                  }
               }
            ));
         }
      durations.emplace_back(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now() - start));
      for(auto& t : threads)
         {
         t.join();
         }
      threads.clear();
      }

      if(durations[0].count() < durations[1].count())
         {
         return concurrency[0];
         }
      else
         {
         return concurrency[1];
         }
  }

#endif

}

<commit_msg>Clean up XMSS self-benchmark<commit_after>/*
 * XMSS Tools
 * (C) 2017 Matthias Gierlings
 *
 * Botan is released under the Simplified BSD License (see license.txt)
 **/

#include <botan/xmss_tools.h>

namespace Botan {

#if defined(BOTAN_TARGET_OS_HAS_THREADS)

size_t XMSS_Tools::max_threads()
   {
   static const size_t threads { bench_threads() };
   return threads;
   }

size_t XMSS_Tools::bench_threads()
   {
   if(std::thread::hardware_concurrency() <= 1)
      {
      return 1;
      }
   const size_t BENCH_ITERATIONS = 1000;
   std::vector<std::thread> threads;
   threads.reserve(std::thread::hardware_concurrency());
   std::vector<std::chrono::nanoseconds> durations;

   std::vector<size_t> concurrency { std::thread::hardware_concurrency(),
                                     std::thread::hardware_concurrency() / 2 };

   for(const auto& cc : concurrency)
      {
      AutoSeeded_RNG rng;
      std::vector<XMSS_Hash> hash(std::thread::hardware_concurrency(),
                                  XMSS_Hash("SHA-256"));
      std::vector<secure_vector<uint8_t>> data(
          std::thread::hardware_concurrency(),
          rng.random_vec(hash[0].output_length()));
      auto start = std::chrono::high_resolution_clock::now();
      for(size_t i = 0; i < cc; ++i)
         {
         auto& hs = hash[i];
         auto& d = data[i];

         const size_t n_iters = BENCH_ITERATIONS * (std::thread::hardware_concurrency() / cc);
         threads.emplace_back(std::thread([n_iters, &hs, &d]()
               {
               for(size_t n = 0; n < n_iters; n++)
                  {
                  hs.h(d, d, d);
                  }
               }
            ));
         }
      durations.emplace_back(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now() - start));
      for(auto& t : threads)
         {
         t.join();
         }
      threads.clear();
      }

      if(durations[0].count() < durations[1].count())
         {
         return concurrency[0];
         }
      else
         {
         return concurrency[1];
         }
  }

#endif

}

<|endoftext|>


<commit_before>/*
* OS and machine specific utility functions
* (C) 2015,2016,2017 Jack Lloyd
* (C) 2016 Daniel Neus
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/socket.h>
#include <botan/exceptn.h>
#include <chrono>

#if defined(BOTAN_HAS_BOOST_ASIO)
  /*
  * We don't need serial port support anyway, and asking for it
  * causes macro conflicts with Darwin's termios.h when this
  * file is included in the amalgamation. GH #350
  */
  #define BOOST_ASIO_DISABLE_SERIAL_PORT
  #include <boost/asio.hpp>
#endif

#if defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)

#if !defined(BOTAN_HAS_BOOST_ASIO)
  #include <sys/socket.h>
  #include <netinet/in.h>
  #include <netdb.h>
  #include <string.h>
  #include <unistd.h>
#endif

#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)
  #include <botan/mem_ops.h>

  #define NOMINMAX 1
#if !defined(BOTAN_HAS_BOOST_ASIO)
  #include <winsock2.h>
  #include <ws2tcpip.h>
#endif
  #include <windows.h>
#endif

namespace Botan {

namespace {

#if defined(BOTAN_HAS_BOOST_ASIO)

class Asio_Socket final : public OS::Socket
   {
   public:
      Asio_Socket(const std::string& hostname, const std::string& service) :
         m_tcp(m_io)
         {
         boost::asio::ip::tcp::resolver resolver(m_io);
         boost::asio::ip::tcp::resolver::query query(hostname, service);
         boost::asio::connect(m_tcp, resolver.resolve(query));
         }

      void write(const uint8_t buf[], size_t len) override
         {
         boost::asio::write(m_tcp, boost::asio::buffer(buf, len));
         }

      size_t read(uint8_t buf[], size_t len) override
         {
         boost::system::error_code error;
         size_t got = m_tcp.read_some(boost::asio::buffer(buf, len), error);

         if(error)
            {
            if(error == boost::asio::error::eof)
               return 0;
            throw boost::system::system_error(error); // Some other error.
            }

         return got;
         }

   private:
      boost::asio::io_service m_io;
      boost::asio::ip::tcp::socket m_tcp;
   };

#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)

class Winsock_Socket final : public OS::Socket
   {
   public:
      Winsock_Socket(const std::string& hostname, const std::string& service)
         {
         WSAData wsa_data;
         WORD wsa_version = MAKEWORD(2, 2);

         if (::WSAStartup(wsa_version, &wsa_data) != 0)
            {
            throw Exception("WSAStartup() failed: " + std::to_string(WSAGetLastError()));
            }

         if (LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2)
            {
            ::WSACleanup();
            throw Exception("Could not find a usable version of Winsock.dll");
            }

         addrinfo hints;
         ::memset(&hints, 0, sizeof(addrinfo));
         hints.ai_family = AF_UNSPEC;
         hints.ai_socktype = SOCK_STREAM;
         addrinfo* res;

         if(::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res) != 0)
            {
            throw Exception("Name resolution failed for " + hostname);
            }

         for(addrinfo* rp = res; (m_socket == INVALID_SOCKET) && (rp != nullptr); rp = rp->ai_next)
            {
            m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);

            // unsupported socket type?
            if(m_socket == INVALID_SOCKET)
               continue;

            if(::connect(m_socket, rp->ai_addr, rp->ai_addrlen) != 0)
               {
               ::closesocket(m_socket);
               m_socket = INVALID_SOCKET;
               continue;
               }
            }

         ::freeaddrinfo(res);

         if(m_socket == INVALID_SOCKET)
            {
            throw Exception("Connecting to " + hostname +
                            " for service " + service + " failed");
            }
         }

      ~Winsock_Socket()
         {
         ::closesocket(m_socket);
         m_socket = INVALID_SOCKET;
         ::WSACleanup();
         }

      void write(const uint8_t buf[], size_t len) override
         {
         size_t sent_so_far = 0;
         while(sent_so_far != len)
            {
            const size_t left = len - sent_so_far;
            int sent = ::send(m_socket,
                              cast_uint8_ptr_to_char(buf + sent_so_far),
                              static_cast<int>(left),
                              0);

            if(sent == SOCKET_ERROR)
               throw Exception("Socket write failed with error " +
                               std::to_string(::WSAGetLastError()));
            else
               sent_so_far += static_cast<size_t>(sent);
            }
         }

      size_t read(uint8_t buf[], size_t len) override
         {
         int got = ::recv(m_socket,
                          cast_uint8_ptr_to_char(buf),
                          static_cast<int>(len), 0);

         if(got == SOCKET_ERROR)
            throw Exception("Socket read failed with error " +
                            std::to_string(::WSAGetLastError()));
         return static_cast<size_t>(got);
         }

   private:
      SOCKET m_socket = INVALID_SOCKET;
   };

#elif defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)
class BSD_Socket final : public OS::Socket
   {
   public:
      BSD_Socket(const std::string& hostname, const std::string& service)
         {
         addrinfo hints;
         ::memset(&hints, 0, sizeof(addrinfo));
         hints.ai_family = AF_UNSPEC;
         hints.ai_socktype = SOCK_STREAM;
         addrinfo* res;

         if(::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res) != 0)
            {
            throw Exception("Name resolution failed for " + hostname);
            }

         m_fd = -1;

         for(addrinfo* rp = res; (m_fd < 0) && (rp != nullptr); rp = rp->ai_next)
            {
            m_fd = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);

            if(m_fd < 0)
               {
               // unsupported socket type?
               continue;
               }

            if(::connect(m_fd, rp->ai_addr, rp->ai_addrlen) != 0)
               {
               ::close(m_fd);
               m_fd = -1;
               continue;
               }
            }

         ::freeaddrinfo(res);

         if(m_fd < 0)
            {
            throw Exception("Connecting to " + hostname +
                            " for service " + service + " failed");
            }
         }

      ~BSD_Socket()
         {
         ::close(m_fd);
         m_fd = -1;
         }

      void write(const uint8_t buf[], size_t len) override
         {
         size_t sent_so_far = 0;
         while(sent_so_far != len)
            {
            const size_t left = len - sent_so_far;
            ssize_t sent = ::write(m_fd, &buf[sent_so_far], left);
            if(sent < 0)
               throw Exception("Socket write failed with error '" +
                               std::string(::strerror(errno)) + "'");
            else
               sent_so_far += static_cast<size_t>(sent);
            }
         }

      size_t read(uint8_t buf[], size_t len) override
         {
         ssize_t got = ::read(m_fd, buf, len);

         if(got < 0)
            throw Exception("Socket read failed with error '" +
                            std::string(::strerror(errno)) + "'");
         return static_cast<size_t>(got);
         }

   private:
      int m_fd;
   };

#endif

}

std::unique_ptr<OS::Socket>
OS::open_socket(const std::string& hostname,
                const std::string& service)
   {
#if defined(BOTAN_HAS_BOOST_ASIO)
   return std::unique_ptr<OS::Socket>(new Asio_Socket(hostname, service));

#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)
   return std::unique_ptr<OS::Socket>(new Winsock_Socket(hostname, service));

#elif defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)
   return std::unique_ptr<OS::Socket>(new BSD_Socket(hostname, service));

#else
   // No sockets for you
   return std::unique_ptr<Socket>();
#endif
   }

}
<commit_msg>Simplify header includes in socket.cpp<commit_after>/*
* OS and machine specific utility functions
* (C) 2015,2016,2017 Jack Lloyd
* (C) 2016 Daniel Neus
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/socket.h>
#include <botan/exceptn.h>
#include <botan/mem_ops.h>
#include <chrono>

#if defined(BOTAN_HAS_BOOST_ASIO)
  /*
  * We don't need serial port support anyway, and asking for it
  * causes macro conflicts with Darwin's termios.h when this
  * file is included in the amalgamation. GH #350
  */
  #define BOOST_ASIO_DISABLE_SERIAL_PORT
  #include <boost/asio.hpp>

#elif defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)
  #include <sys/socket.h>
  #include <netinet/in.h>
  #include <netdb.h>
  #include <string.h>
  #include <unistd.h>
  #include <errno.h>

#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)
  #define NOMINMAX 1
  #include <winsock2.h>
  #include <ws2tcpip.h>
  #include <windows.h>
#endif

namespace Botan {

namespace {

#if defined(BOTAN_HAS_BOOST_ASIO)

class Asio_Socket final : public OS::Socket
   {
   public:
      Asio_Socket(const std::string& hostname, const std::string& service) :
         m_tcp(m_io)
         {
         boost::asio::ip::tcp::resolver resolver(m_io);
         boost::asio::ip::tcp::resolver::query query(hostname, service);
         boost::asio::connect(m_tcp, resolver.resolve(query));
         }

      void write(const uint8_t buf[], size_t len) override
         {
         boost::asio::write(m_tcp, boost::asio::buffer(buf, len));
         }

      size_t read(uint8_t buf[], size_t len) override
         {
         boost::system::error_code error;
         size_t got = m_tcp.read_some(boost::asio::buffer(buf, len), error);

         if(error)
            {
            if(error == boost::asio::error::eof)
               return 0;
            throw boost::system::system_error(error); // Some other error.
            }

         return got;
         }

   private:
      boost::asio::io_service m_io;
      boost::asio::ip::tcp::socket m_tcp;
   };

#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)

class Winsock_Socket final : public OS::Socket
   {
   public:
      Winsock_Socket(const std::string& hostname, const std::string& service)
         {
         WSAData wsa_data;
         WORD wsa_version = MAKEWORD(2, 2);

         if (::WSAStartup(wsa_version, &wsa_data) != 0)
            {
            throw Exception("WSAStartup() failed: " + std::to_string(WSAGetLastError()));
            }

         if (LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2)
            {
            ::WSACleanup();
            throw Exception("Could not find a usable version of Winsock.dll");
            }

         addrinfo hints;
         ::memset(&hints, 0, sizeof(addrinfo));
         hints.ai_family = AF_UNSPEC;
         hints.ai_socktype = SOCK_STREAM;
         addrinfo* res;

         if(::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res) != 0)
            {
            throw Exception("Name resolution failed for " + hostname);
            }

         for(addrinfo* rp = res; (m_socket == INVALID_SOCKET) && (rp != nullptr); rp = rp->ai_next)
            {
            m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);

            // unsupported socket type?
            if(m_socket == INVALID_SOCKET)
               continue;

            if(::connect(m_socket, rp->ai_addr, rp->ai_addrlen) != 0)
               {
               ::closesocket(m_socket);
               m_socket = INVALID_SOCKET;
               continue;
               }
            }

         ::freeaddrinfo(res);

         if(m_socket == INVALID_SOCKET)
            {
            throw Exception("Connecting to " + hostname +
                            " for service " + service + " failed");
            }
         }

      ~Winsock_Socket()
         {
         ::closesocket(m_socket);
         m_socket = INVALID_SOCKET;
         ::WSACleanup();
         }

      void write(const uint8_t buf[], size_t len) override
         {
         size_t sent_so_far = 0;
         while(sent_so_far != len)
            {
            const size_t left = len - sent_so_far;
            int sent = ::send(m_socket,
                              cast_uint8_ptr_to_char(buf + sent_so_far),
                              static_cast<int>(left),
                              0);

            if(sent == SOCKET_ERROR)
               throw Exception("Socket write failed with error " +
                               std::to_string(::WSAGetLastError()));
            else
               sent_so_far += static_cast<size_t>(sent);
            }
         }

      size_t read(uint8_t buf[], size_t len) override
         {
         int got = ::recv(m_socket,
                          cast_uint8_ptr_to_char(buf),
                          static_cast<int>(len), 0);

         if(got == SOCKET_ERROR)
            throw Exception("Socket read failed with error " +
                            std::to_string(::WSAGetLastError()));
         return static_cast<size_t>(got);
         }

   private:
      SOCKET m_socket = INVALID_SOCKET;
   };

#elif defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)
class BSD_Socket final : public OS::Socket
   {
   public:
      BSD_Socket(const std::string& hostname, const std::string& service)
         {
         addrinfo hints;
         ::memset(&hints, 0, sizeof(addrinfo));
         hints.ai_family = AF_UNSPEC;
         hints.ai_socktype = SOCK_STREAM;
         addrinfo* res;

         if(::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res) != 0)
            {
            throw Exception("Name resolution failed for " + hostname);
            }

         m_fd = -1;

         for(addrinfo* rp = res; (m_fd < 0) && (rp != nullptr); rp = rp->ai_next)
            {
            m_fd = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);

            if(m_fd < 0)
               {
               // unsupported socket type?
               continue;
               }

            if(::connect(m_fd, rp->ai_addr, rp->ai_addrlen) != 0)
               {
               ::close(m_fd);
               m_fd = -1;
               continue;
               }
            }

         ::freeaddrinfo(res);

         if(m_fd < 0)
            {
            throw Exception("Connecting to " + hostname +
                            " for service " + service + " failed");
            }
         }

      ~BSD_Socket()
         {
         ::close(m_fd);
         m_fd = -1;
         }

      void write(const uint8_t buf[], size_t len) override
         {
         size_t sent_so_far = 0;
         while(sent_so_far != len)
            {
            const size_t left = len - sent_so_far;
            ssize_t sent = ::write(m_fd, &buf[sent_so_far], left);
            if(sent < 0)
               throw Exception("Socket write failed with error '" +
                               std::string(::strerror(errno)) + "'");
            else
               sent_so_far += static_cast<size_t>(sent);
            }
         }

      size_t read(uint8_t buf[], size_t len) override
         {
         ssize_t got = ::read(m_fd, buf, len);

         if(got < 0)
            throw Exception("Socket read failed with error '" +
                            std::string(::strerror(errno)) + "'");
         return static_cast<size_t>(got);
         }

   private:
      int m_fd;
   };

#endif

}

std::unique_ptr<OS::Socket>
OS::open_socket(const std::string& hostname,
                const std::string& service)
   {
#if defined(BOTAN_HAS_BOOST_ASIO)
   return std::unique_ptr<OS::Socket>(new Asio_Socket(hostname, service));

#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)
   return std::unique_ptr<OS::Socket>(new Winsock_Socket(hostname, service));

#elif defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)
   return std::unique_ptr<OS::Socket>(new BSD_Socket(hostname, service));

#else
   // No sockets for you
   return std::unique_ptr<Socket>();
#endif
   }

}
<|endoftext|>


<commit_before>/*
 * SamplePlayerSW.cpp
 *
 *  Created on: Dec 28, 2013
 *      Author: lukas
 */

#include "SamplePlayer_SW.h"

SamplePlayer_SW::SamplePlayer_SW(std::vector<std::string> params) : SamplePlayer(params) {

    m_StringToLoadPolicyMap["LOAD_ON_DEMAND"]     = LOAD_ON_DEMAND;
    m_StringToLoadPolicyMap["PRELOAD"]            = PRELOAD;
    m_StringToLoadPolicyMap["PRELOAD_DECOMPRESS"] = PRELOAD_DECOMPRESS;

    m_LoadingPolicy = PRELOAD_DECOMPRESS;  /* Set preload as default loading policy */
    m_Playbackstate = STOP;
    m_CompressedDataBuffer   = NULL;
    m_DecompressedDataBuffer = NULL;

    m_CurrentPlaybackOffset  = 0;

    m_DecompressedDataSize   = 0;

    /* First parameter should be the filename */
    if (params.size() > 0) {
        m_SourceFile = params[0];

        m_Codec         = NULL;
        m_Decoded_Frame = NULL;
        m_CodecCtx      = NULL;
        m_ContainerCtx  = NULL;

        if(params.size() > 1){
            std::string policyStr = params[1];

            std::transform(policyStr.begin(), policyStr.end(), policyStr.begin(), ::toupper);

            std::map<std::string, eLoadPolicy>::iterator iter = m_StringToLoadPolicyMap.find(params[1]);

            if(iter != m_StringToLoadPolicyMap.end()){
                m_LoadingPolicy = iter->second;
            }else{
               LOG_WARNING("Unknown loading policy: " << policyStr);
            }
        }
    }
}

SamplePlayer_SW::~SamplePlayer_SW() {

    avcodec_close(m_CodecCtx);
}

void SamplePlayer_SW::initCodec() {

    avcodec_register_all();
    av_register_all();
    AVDictionary* dict;

    int stream_index = -1;

    if (avformat_open_input(&m_ContainerCtx, m_SourceFile.c_str(), NULL, NULL) < 0) {
            LOG_ERROR("Cound not open file: " << m_SourceFile.c_str());
    }

    avformat_find_stream_info(m_ContainerCtx, NULL);

    LOG_INFO("Loading audio file " << m_SourceFile);
    LOG_INFO("#Streams: " << m_ContainerCtx->nb_streams);

    for (unsigned int i = 0; i < m_ContainerCtx->nb_streams; i++) {
        if (m_ContainerCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
            stream_index = i;
            break;
        }
    }

    if(stream_index == -1){
        LOG_ERROR("Could not find audio");
    }

    m_CodecCtx = m_ContainerCtx->streams[stream_index]->codec;

    m_Codec    = avcodec_find_decoder(m_CodecCtx->codec_id);

    if (!m_Codec) {

        LOG_ERROR("Codec not found");
        avformat_close_input(&m_ContainerCtx);
        exit(1);
    }
    /* request internal sample format */

    LOG_INFO("Codec tag: "<< m_Codec->name << ", Codec ID: " << m_Codec->id);

    LOG_DEBUG("#Channels: " << m_CodecCtx->channels);

    /* open it */
    if (avcodec_open2(m_CodecCtx, m_Codec, NULL) < 0) {
        LOG_ERROR("Could not open codec");
        exit(1);
    }
}

void SamplePlayer_SW::init() {

    AVPacket avpkt;
    ReSampleContext* resmplCtx;
    int compressed_bytes_consumed    = 0;
    int compressed_file_size         = 0;
    uint8_t* l_ResampleBuffer;

    initCodec();                /* Initialize audio codec   */
    av_init_packet(&avpkt);     /* Initialize packet        */
//    resmplCtx = av_audio_resample_init(m_CodecCtx->channels,
//                                        m_CodecCtx->channels,
//                                        Synthesizer::config::samplerate,
//                                        m_CodecCtx->sample_rate,
//                                        AV_SAMPLE_FMT_S32,
//                                        m_CodecCtx->sample_fmt,
//                                        16, 10, 0, 1.0);

    m_DecompressedDataBuffer = new uint8_t[AVCODEC_MAX_AUDIO_FRAME_SIZE * MAX_PLAYBACK_LENGTH_SEC];
    memset(m_DecompressedDataBuffer, 0 ,AVCODEC_MAX_AUDIO_FRAME_SIZE * MAX_PLAYBACK_LENGTH_SEC);

    LOG_DEBUG("Decoding audio file");
    LOG_DEBUG("Sample format:" << av_get_sample_fmt_name(m_CodecCtx->sample_fmt));

    while (!av_read_frame(m_ContainerCtx, &avpkt)) {

        int got_frame = 0;

        if (!m_Decoded_Frame) {

            if (!(m_Decoded_Frame = avcodec_alloc_frame())) { /* allocate once */

                LOG_ERROR("Could not allocate audio frame");
                exit(1);
            }
        }else{
            avcodec_get_frame_defaults(m_Decoded_Frame);
        }

        compressed_bytes_consumed = avcodec_decode_audio4(m_CodecCtx, m_Decoded_Frame, &got_frame, &avpkt);

        if (compressed_bytes_consumed < 0) {
            LOG_ERROR("Error while decoding audio frame");
            exit(1);
        }

        if (got_frame) {
            int samples_written = 0;
            int data_size = 0;
            size_t resampled_Bytes = 0;

            /* if a frame has been decoded, output it */
            data_size = av_samples_get_buffer_size(NULL, m_CodecCtx->channels, m_Decoded_Frame->nb_samples, m_CodecCtx->sample_fmt, 1);

            int32_t* buf  = (int32_t*) (m_DecompressedDataBuffer + m_DecompressedDataSize);

            switch(m_CodecCtx->sample_fmt){
            case AV_SAMPLE_FMT_NONE:
            case AV_SAMPLE_FMT_U8:
//                for(int i = 0; i <  m_Decoded_Frame->nb_samples * m_CodecCtx->channels; i++){
//                    buf[i] = (int32_t)( ((int8_t*)  m_Decoded_Frame->data[0])[i] << 24 );
//                }
//                break;

            //FIXME: convert other sample formats
            case AV_SAMPLE_FMT_S16:
                for(int i = 0; i <  m_Decoded_Frame->nb_samples * m_CodecCtx->channels; i++){
                    buf[i] = *(((short*)m_Decoded_Frame->data[0]) + i) << 16;
                }
                m_DecompressedDataSize += m_Decoded_Frame->nb_samples * m_CodecCtx->channels * av_get_bytes_per_sample(AV_SAMPLE_FMT_S32);
                break;

            case AV_SAMPLE_FMT_S32:

                memcpy(m_DecompressedDataBuffer + m_DecompressedDataSize, m_Decoded_Frame->data[0], data_size);

                m_DecompressedDataSize += data_size;

                break;

            case AV_SAMPLE_FMT_FLT:
            case AV_SAMPLE_FMT_DBL:

            case AV_SAMPLE_FMT_U8P:
            case AV_SAMPLE_FMT_S16P:
            case AV_SAMPLE_FMT_S32P:
            case AV_SAMPLE_FMT_FLTP:
            case AV_SAMPLE_FMT_DBLP:

            default:
                LOG_ERROR("Sample format is not supported");
            }

        }
    }

    char* writeLeftPortPtr  = m_SoundOut_Left_1_Port->getWriteBuffer();
    char* writeRightPortPtr = m_SoundOut_Right_2_Port->getWriteBuffer();

    memset(writeLeftPortPtr,  0, Synthesizer::config::bytesPerBlock);
    memset(writeRightPortPtr, 0, Synthesizer::config::bytesPerBlock);

    m_Trigger_1_Port->registerCallback(ICallbackPtr(new OnValueChange<int, ControlPortPtr>(trigger, m_Trigger_1_Port)));
//   audio_resample_close(resmplCtx);
//   av_free(m_CodecCtx);
//   av_free(m_Decoded_Frame);
//  avformat_free_context(m_ContainerCtx);
}

void SamplePlayer_SW::process() {

    int* writeLeftPortPtr  = (int*)m_SoundOut_Left_1_Port->getWriteBuffer();
    int* writeRightPortPtr = (int*)m_SoundOut_Right_2_Port->getWriteBuffer();

    //int trigger = (int) m_Trigger_1_Port->pop();

    if(trigger || (m_CurrentPlaybackOffset > 0 && m_CurrentPlaybackOffset < m_DecompressedDataSize)){

    switch(m_CodecCtx->channels){

        case 1:
            /*
             * Copy samples to left and right channel
             */
            memcpy(writeLeftPortPtr,  m_DecompressedDataBuffer + m_CurrentPlaybackOffset, Synthesizer::config::bytesPerBlock);
            memcpy(writeRightPortPtr, m_DecompressedDataBuffer + m_CurrentPlaybackOffset, Synthesizer::config::bytesPerBlock);

            m_CurrentPlaybackOffset += Synthesizer::config::bytesPerBlock;
            //TODO: Add padding zeros when playbackoffset > n* blocksize
            break;
        case 2:
            /*
             * Copy interleaved audio samples to left and right channel
             */
            for(int i = 0; i < Synthesizer::config::blocksize; i++){

                writeLeftPortPtr[i]  = *((int*)(m_DecompressedDataBuffer + m_CurrentPlaybackOffset));
                writeRightPortPtr[i] = *((int*)(m_DecompressedDataBuffer + m_CurrentPlaybackOffset + Synthesizer::config::bytesPerSample));

                m_CurrentPlaybackOffset += Synthesizer::config::bytesPerSample * 2;

                if(m_CurrentPlaybackOffset >= m_DecompressedDataSize){

                    /* pad with zero */
                    for(int j = i; j < Synthesizer::config::blocksize; j++){
                        writeLeftPortPtr[j]  = 0;
                        writeRightPortPtr[j] = 0;
                    }
                    break;
                }
            }

            break;
        default:
            LOG_ERROR("Unsupported number of channels: " << m_CodecCtx->channels);
        }

        if(m_CurrentPlaybackOffset >= m_DecompressedDataSize){
            m_CurrentPlaybackOffset = 0;
        }

    }else{

         memset((char*)writeLeftPortPtr,  0, Synthesizer::config::bytesPerBlock);
         memset((char*)writeRightPortPtr, 0, Synthesizer::config::bytesPerBlock);
         m_CurrentPlaybackOffset = 0;
     }
}
<commit_msg>Disabled the second sampleplayer channel. Has only one output in the component list and would otherwise be the only component with stereo support anyway<commit_after>/*
 * SamplePlayerSW.cpp
 *
 *  Created on: Dec 28, 2013
 *      Author: lukas
 */

#include "SamplePlayer_SW.h"

SamplePlayer_SW::SamplePlayer_SW(std::vector<std::string> params) : SamplePlayer(params) {

    m_StringToLoadPolicyMap["LOAD_ON_DEMAND"]     = LOAD_ON_DEMAND;
    m_StringToLoadPolicyMap["PRELOAD"]            = PRELOAD;
    m_StringToLoadPolicyMap["PRELOAD_DECOMPRESS"] = PRELOAD_DECOMPRESS;

    m_LoadingPolicy = PRELOAD_DECOMPRESS;  /* Set preload as default loading policy */
    m_Playbackstate = STOP;
    m_CompressedDataBuffer   = NULL;
    m_DecompressedDataBuffer = NULL;

    m_CurrentPlaybackOffset  = 0;

    m_DecompressedDataSize   = 0;

    /* First parameter should be the filename */
    if (params.size() > 0) {
        m_SourceFile = params[0];

        m_Codec         = NULL;
        m_Decoded_Frame = NULL;
        m_CodecCtx      = NULL;
        m_ContainerCtx  = NULL;

        if(params.size() > 1){
            std::string policyStr = params[1];

            std::transform(policyStr.begin(), policyStr.end(), policyStr.begin(), ::toupper);

            std::map<std::string, eLoadPolicy>::iterator iter = m_StringToLoadPolicyMap.find(params[1]);

            if(iter != m_StringToLoadPolicyMap.end()){
                m_LoadingPolicy = iter->second;
            }else{
               LOG_WARNING("Unknown loading policy: " << policyStr);
            }
        }
    }
}

SamplePlayer_SW::~SamplePlayer_SW() {

    avcodec_close(m_CodecCtx);
}

void SamplePlayer_SW::initCodec() {

    avcodec_register_all();
    av_register_all();
    AVDictionary* dict;

    int stream_index = -1;

    if (avformat_open_input(&m_ContainerCtx, m_SourceFile.c_str(), NULL, NULL) < 0) {
            LOG_ERROR("Cound not open file: " << m_SourceFile.c_str());
    }

    avformat_find_stream_info(m_ContainerCtx, NULL);

    LOG_INFO("Loading audio file " << m_SourceFile);
    LOG_INFO("#Streams: " << m_ContainerCtx->nb_streams);

    for (unsigned int i = 0; i < m_ContainerCtx->nb_streams; i++) {
        if (m_ContainerCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
            stream_index = i;
            break;
        }
    }

    if(stream_index == -1){
        LOG_ERROR("Could not find audio");
    }

    m_CodecCtx = m_ContainerCtx->streams[stream_index]->codec;

    m_Codec    = avcodec_find_decoder(m_CodecCtx->codec_id);

    if (!m_Codec) {

        LOG_ERROR("Codec not found");
        avformat_close_input(&m_ContainerCtx);
        exit(1);
    }
    /* request internal sample format */

    LOG_INFO("Codec tag: "<< m_Codec->name << ", Codec ID: " << m_Codec->id);

    LOG_DEBUG("#Channels: " << m_CodecCtx->channels);

    /* open it */
    if (avcodec_open2(m_CodecCtx, m_Codec, NULL) < 0) {
        LOG_ERROR("Could not open codec");
        exit(1);
    }
}

void SamplePlayer_SW::init() {

    AVPacket avpkt;
    ReSampleContext* resmplCtx;
    int compressed_bytes_consumed    = 0;
    int compressed_file_size         = 0;
    uint8_t* l_ResampleBuffer;

    initCodec();                /* Initialize audio codec   */
    av_init_packet(&avpkt);     /* Initialize packet        */
//    resmplCtx = av_audio_resample_init(m_CodecCtx->channels,
//                                        m_CodecCtx->channels,
//                                        Synthesizer::config::samplerate,
//                                        m_CodecCtx->sample_rate,
//                                        AV_SAMPLE_FMT_S32,
//                                        m_CodecCtx->sample_fmt,
//                                        16, 10, 0, 1.0);

    m_DecompressedDataBuffer = new uint8_t[AVCODEC_MAX_AUDIO_FRAME_SIZE * MAX_PLAYBACK_LENGTH_SEC];
    memset(m_DecompressedDataBuffer, 0 ,AVCODEC_MAX_AUDIO_FRAME_SIZE * MAX_PLAYBACK_LENGTH_SEC);

    LOG_DEBUG("Decoding audio file");
    LOG_DEBUG("Sample format:" << av_get_sample_fmt_name(m_CodecCtx->sample_fmt));

    while (!av_read_frame(m_ContainerCtx, &avpkt)) {

        int got_frame = 0;

        if (!m_Decoded_Frame) {

            if (!(m_Decoded_Frame = avcodec_alloc_frame())) { /* allocate once */

                LOG_ERROR("Could not allocate audio frame");
                exit(1);
            }
        }else{
            avcodec_get_frame_defaults(m_Decoded_Frame);
        }

        compressed_bytes_consumed = avcodec_decode_audio4(m_CodecCtx, m_Decoded_Frame, &got_frame, &avpkt);

        if (compressed_bytes_consumed < 0) {
            LOG_ERROR("Error while decoding audio frame");
            exit(1);
        }

        if (got_frame) {
            int samples_written = 0;
            int data_size = 0;
            size_t resampled_Bytes = 0;

            /* if a frame has been decoded, output it */
            data_size = av_samples_get_buffer_size(NULL, m_CodecCtx->channels, m_Decoded_Frame->nb_samples, m_CodecCtx->sample_fmt, 1);

            int32_t* buf  = (int32_t*) (m_DecompressedDataBuffer + m_DecompressedDataSize);

            switch(m_CodecCtx->sample_fmt){
            case AV_SAMPLE_FMT_NONE:
            case AV_SAMPLE_FMT_U8:
//                for(int i = 0; i <  m_Decoded_Frame->nb_samples * m_CodecCtx->channels; i++){
//                    buf[i] = (int32_t)( ((int8_t*)  m_Decoded_Frame->data[0])[i] << 24 );
//                }
//                break;

            //FIXME: convert other sample formats
            case AV_SAMPLE_FMT_S16:
                for(int i = 0; i <  m_Decoded_Frame->nb_samples * m_CodecCtx->channels; i++){
                    buf[i] = *(((short*)m_Decoded_Frame->data[0]) + i) << 16;
                }
                m_DecompressedDataSize += m_Decoded_Frame->nb_samples * m_CodecCtx->channels * av_get_bytes_per_sample(AV_SAMPLE_FMT_S32);
                break;

            case AV_SAMPLE_FMT_S32:

                memcpy(m_DecompressedDataBuffer + m_DecompressedDataSize, m_Decoded_Frame->data[0], data_size);

                m_DecompressedDataSize += data_size;

                break;

            case AV_SAMPLE_FMT_FLT:
            case AV_SAMPLE_FMT_DBL:

            case AV_SAMPLE_FMT_U8P:
            case AV_SAMPLE_FMT_S16P:
            case AV_SAMPLE_FMT_S32P:
            case AV_SAMPLE_FMT_FLTP:
            case AV_SAMPLE_FMT_DBLP:

            default:
                LOG_ERROR("Sample format is not supported");
            }

        }
    }

    char* writeLeftPortPtr  = m_SoundOut_Left_1_Port->getWriteBuffer();
    char* writeRightPortPtr = m_SoundOut_Right_2_Port->getWriteBuffer();

    memset(writeLeftPortPtr,  0, Synthesizer::config::bytesPerBlock);
//    memset(writeRightPortPtr, 0, Synthesizer::config::bytesPerBlock);

    m_Trigger_1_Port->registerCallback(ICallbackPtr(new OnValueChange<int, ControlPortPtr>(trigger, m_Trigger_1_Port)));
//   audio_resample_close(resmplCtx);
//   av_free(m_CodecCtx);
//   av_free(m_Decoded_Frame);
//  avformat_free_context(m_ContainerCtx);
}

void SamplePlayer_SW::process() {

    int* writeLeftPortPtr  = (int*)m_SoundOut_Left_1_Port->getWriteBuffer();
    int* writeRightPortPtr = (int*)m_SoundOut_Right_2_Port->getWriteBuffer();

    //int trigger = (int) m_Trigger_1_Port->pop();

    if(trigger || (m_CurrentPlaybackOffset > 0 && m_CurrentPlaybackOffset < m_DecompressedDataSize)){

    switch(m_CodecCtx->channels){

        case 1:
            /*
             * Copy samples to left and right channel
             */
            memcpy(writeLeftPortPtr,  m_DecompressedDataBuffer + m_CurrentPlaybackOffset, Synthesizer::config::bytesPerBlock);
            memcpy(writeRightPortPtr, m_DecompressedDataBuffer + m_CurrentPlaybackOffset, Synthesizer::config::bytesPerBlock);

            m_CurrentPlaybackOffset += Synthesizer::config::bytesPerBlock;
            //TODO: Add padding zeros when playbackoffset > n* blocksize
            break;
        case 2:
            /*
             * Copy interleaved audio samples to left and right channel
             */
            for(int i = 0; i < Synthesizer::config::blocksize; i++){

                writeLeftPortPtr[i]  = *((int*)(m_DecompressedDataBuffer + m_CurrentPlaybackOffset));
 //               writeRightPortPtr[i] = *((int*)(m_DecompressedDataBuffer + m_CurrentPlaybackOffset + Synthesizer::config::bytesPerSample));

                m_CurrentPlaybackOffset += Synthesizer::config::bytesPerSample * 2;

                if(m_CurrentPlaybackOffset >= m_DecompressedDataSize){

                    /* pad with zero */
                    for(int j = i; j < Synthesizer::config::blocksize; j++){
                        writeLeftPortPtr[j]  = 0;
  //                      writeRightPortPtr[j] = 0;
                    }
                    break;
                }
            }

            break;
        default:
            LOG_ERROR("Unsupported number of channels: " << m_CodecCtx->channels);
        }

        if(m_CurrentPlaybackOffset >= m_DecompressedDataSize){
            m_CurrentPlaybackOffset = 0;
        }

    }else{

         memset((char*)writeLeftPortPtr,  0, Synthesizer::config::bytesPerBlock);
//         memset((char*)writeRightPortPtr, 0, Synthesizer::config::bytesPerBlock);
         m_CurrentPlaybackOffset = 0;
     }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: IDocumentUndoRedo.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-25 12:59:33 $
 *
 *  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 IDOCUMENTUNDOREDO_HXX_INCLUDED
 #define IDOCUMENTUNDOREDO_HXX_INCLUDED

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

 class SwUndoIter;
 class SwRewriter;
 class String;
 class SwUndoIds;
 class SwNodes;
 class SwUndo;

 typedef sal_uInt16 SwUndoNoModifiedPosition;

 /** IDocumentUndoRedo
 */
 class IDocumentUndoRedo
 {
 public:
    /**
    */
    virtual void SetUndoNoResetModified() = 0;

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

    /** UndoHistory am Dokument pflegen
        bei Save, SaveAs, Create wird UndoHistory zurueckgesetzt ???
    */
    virtual void DoUndo(bool bUn) = 0;

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

    /** Zusammenfassen von Kontinuierlichen Insert/Delete/Overwrite von
        Charaktern. Default ist ::com::sun::star::sdbcx::Group-Undo.
    */
    virtual void DoGroupUndo(bool bUn) = 0;

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

    /** macht rueckgaengig:
        0 letzte Aktion, sonst Aktionen bis zum Start der Klammerung nUndoId
        In rUndoRange wird der restaurierte Bereich gesetzt.
    */
    virtual bool Undo( SwUndoIter& ) = 0; // -> #111827#

    /** Opens undo block.

        @param nUndoId        undo ID for the start object
        @param pRewriter      rewriter for comments @see SwUndo::GetComment

        If the given nUndoId is equal to zero an undo object with ID
        UNDO_START will be generated.

        @return the undo ID of the created object
    */
    virtual sal_uInt16 StartUndo( sal_uInt16 nUndoId, const SwRewriter * pRewriter) = 0;

    /**
       Closes undo block.

       @param nUndoId         undo ID for the closure object
       @param pRewriter       rewriter for comments @see SwUndo::GetComment

       If the given nUndoId is equal to zero an undo object with ID
       UNDO_START will be generated.

       If pRewriter is not equal to zero the given rewriter will be
       set for the generated closure object and the corresponding
       start object. Otherwise an existent rewriter in theIDocumentRedlineAccess
       corresponding start object will be propagated to the generated
       closure object.
    */
    virtual sal_uInt16 EndUndo( sal_uInt16 nUndoId, const SwRewriter * pRewriter) = 0;

    /** <- #111827#
        loescht die gesamten UndoObjecte ( fuer Methoden die am Nodes
        Array drehen ohne entsprechendes Undo !!)
    */
    virtual void DelAllUndoObj() = 0;

    /** liefert die Id der letzten undofaehigen Aktion zurueck
        oder USHRT_MAX fuellt ggf. VARARR mit ::com::sun::star::sdbcx::User-UndoIds
    */
    virtual sal_uInt16 GetUndoIds(String* pStr, SwUndoIds *pUndoIds) const = 0;

    /**
    */
    virtual String GetUndoIdsStr(String* pStr, SwUndoIds *pUndoIds) const = 0;

    /** gibt es Klammerung mit der Id?
    */
    virtual bool HasUndoId(sal_uInt16 nId) const = 0;

    /* @@@MAINTAINABILITY-HORROR@@@
       Implementation details made public.
       die drei folgenden Methoden werden beim Undo und nur dort
       benoetigt. Sollten sonst nicht aufgerufen werden.
    */
    virtual const SwNodes* GetUndoNds() const = 0;

    virtual SwUndo* RemoveLastUndo(sal_uInt16 nUndoId) = 0;

    /** 2002-05-31 dvo, #95884#: To prevent an undo array overflow when
        doing nested undos, undo may have to be disabled. Undo-intensive
        actions (like auto-format) should check this manually.
    */
    virtual bool HasTooManyUndos() const = 0;

    /**
    */
    virtual bool Redo( SwUndoIter& ) = 0;

    /** liefert die Id der letzten Redofaehigen Aktion zurueck
        fuellt ggf. VARARR mit RedoIds
    */
    virtual sal_uInt16 GetRedoIds( String* pStr, SwUndoIds *pRedoIds) const = 0;

    /**
    */
    virtual String GetRedoIdsStr( String* pStr, SwUndoIds *pRedoIds) const = 0;

    /**
    */
    virtual bool Repeat( SwUndoIter&, sal_uInt16 nRepeatCnt) = 0;

    /** liefert die Id der letzten Repeatfaehigen Aktion zurueck
        fuellt ggf. VARARR mit RedoIds
    */
    virtual sal_uInt16 GetRepeatIds( String* pStr, SwUndoIds *pRedoIds) const = 0;

    /**
    */
    virtual String GetRepeatIdsStr( String* pStr, SwUndoIds *pRedoIds) const = 0;

    /** interne Verkuerzung fuer Insert am Ende
    */
    virtual void AppendUndo(SwUndo*) = 0;

    /** loescht alle UndoObjecte von nUndoPos
        bis zum Ende des Undo-Arrays
    */
    virtual void ClearRedo() = 0;

    /** Manipulates the position of the undo stack which reset the modified flag
    */
    virtual void setUndoNoModifiedPosition( SwUndoNoModifiedPosition ) = 0;

    /** Gets the position of the undo stack which reset the modified flag
    */
    virtual SwUndoNoModifiedPosition getUndoNoModifiedPosition() const = 0;

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

 #endif
<commit_msg>INTEGRATION: CWS swwarnings (1.3.198); FILE MERGED 2007/08/22 09:17:47 tl 1.3.198.4: #i69287# warning-free code 2007/08/22 09:09:11 tl 1.3.198.3: #i69287# warning-free code 2007/06/28 11:47:57 os 1.3.198.2: RESYNC: (1.3-1.4); FILE MERGED 2007/04/03 12:57:03 tl 1.3.198.1: #i69287# warning-free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: IDocumentUndoRedo.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 07:54:26 $
 *
 *  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 IDOCUMENTUNDOREDO_HXX_INCLUDED
#define IDOCUMENTUNDOREDO_HXX_INCLUDED

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

class SwUndoIter;
class SwRewriter;
class String;
class SwUndoIds;
class SwNodes;
class SwUndo;

typedef sal_uInt16 SwUndoNoModifiedPosition;

/** IDocumentUndoRedo
*/
class IDocumentUndoRedo
{
public:
    /**
    */
    virtual void SetUndoNoResetModified() = 0;

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

    /** UndoHistory am Dokument pflegen
        bei Save, SaveAs, Create wird UndoHistory zurueckgesetzt ???
    */
    virtual void DoUndo(bool bUn) = 0;

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

    /** Zusammenfassen von Kontinuierlichen Insert/Delete/Overwrite von
        Charaktern. Default ist ::com::sun::star::sdbcx::Group-Undo.
    */
    virtual void DoGroupUndo(bool bUn) = 0;

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

    /** macht rueckgaengig:
        0 letzte Aktion, sonst Aktionen bis zum Start der Klammerung nUndoId
        In rUndoRange wird der restaurierte Bereich gesetzt.
    */
    virtual bool Undo( SwUndoIter& ) = 0; // -> #111827#

    /** Opens undo block.

        @param nUndoId        undo ID for the start object
        @param pRewriter      rewriter for comments @see SwUndo::GetComment

        If the given nUndoId is equal to zero an undo object with ID
        UNDO_START will be generated.

        @return the undo ID of the created object
    */
    virtual SwUndoId StartUndo( SwUndoId eUndoId, const SwRewriter * pRewriter) = 0;

    /**
       Closes undo block.

       @param nUndoId         undo ID for the closure object
       @param pRewriter       rewriter for comments @see SwUndo::GetComment

       If the given nUndoId is equal to zero an undo object with ID
       UNDO_START will be generated.

       If pRewriter is not equal to zero the given rewriter will be
       set for the generated closure object and the corresponding
       start object. Otherwise an existent rewriter in theIDocumentRedlineAccess
       corresponding start object will be propagated to the generated
       closure object.
    */
    virtual SwUndoId EndUndo( SwUndoId eUndoId, const SwRewriter * pRewriter) = 0;

    /** <- #111827#
        loescht die gesamten UndoObjecte ( fuer Methoden die am Nodes
        Array drehen ohne entsprechendes Undo !!)
    */
    virtual void DelAllUndoObj() = 0;

    /** liefert die Id der letzten undofaehigen Aktion zurueck
        oder USHRT_MAX fuellt ggf. VARARR mit ::com::sun::star::sdbcx::User-UndoIds
    */
    virtual SwUndoId GetUndoIds(String* pStr, SwUndoIds *pUndoIds) const = 0;

    /**
    */
    virtual String GetUndoIdsStr(String* pStr, SwUndoIds *pUndoIds) const = 0;

    /** gibt es Klammerung mit der Id?
    */
    virtual bool HasUndoId(SwUndoId eId) const = 0;

    /* @@@MAINTAINABILITY-HORROR@@@
       Implementation details made public.
       die drei folgenden Methoden werden beim Undo und nur dort
       benoetigt. Sollten sonst nicht aufgerufen werden.
    */
    virtual const SwNodes* GetUndoNds() const = 0;

    virtual SwUndo* RemoveLastUndo(SwUndoId eUndoId) = 0;

    /** 2002-05-31 dvo, #95884#: To prevent an undo array overflow when
        doing nested undos, undo may have to be disabled. Undo-intensive
        actions (like auto-format) should check this manually.
    */
    virtual bool HasTooManyUndos() const = 0;

    /**
    */
    virtual bool Redo( SwUndoIter& ) = 0;

    /** liefert die Id der letzten Redofaehigen Aktion zurueck
        fuellt ggf. VARARR mit RedoIds
    */
    virtual SwUndoId GetRedoIds( String* pStr, SwUndoIds *pRedoIds) const = 0;

    /**
    */
    virtual String GetRedoIdsStr( String* pStr, SwUndoIds *pRedoIds) const = 0;

    /**
    */
    virtual bool Repeat( SwUndoIter&, sal_uInt16 nRepeatCnt) = 0;

    /** liefert die Id der letzten Repeatfaehigen Aktion zurueck
        fuellt ggf. VARARR mit RedoIds
    */
    virtual SwUndoId GetRepeatIds( String* pStr, SwUndoIds *pRedoIds) const = 0;

    /**
    */
    virtual String GetRepeatIdsStr( String* pStr, SwUndoIds *pRedoIds) const = 0;

    /** interne Verkuerzung fuer Insert am Ende
    */
    virtual void AppendUndo(SwUndo*) = 0;

    /** loescht alle UndoObjecte von nUndoPos
        bis zum Ende des Undo-Arrays
    */
    virtual void ClearRedo() = 0;

    /** Manipulates the position of the undo stack which reset the modified flag
    */
    virtual void setUndoNoModifiedPosition( SwUndoNoModifiedPosition ) = 0;

    /** Gets the position of the undo stack which reset the modified flag
    */
    virtual SwUndoNoModifiedPosition getUndoNoModifiedPosition() const = 0;

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

#endif

<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <vector>
#include <cassert>

#include "structures.h"

#define abs(x) ((x)<0 ? -(x) : (x))

int op(int x) {
    int ret ;
    ret = x&1 ;
    x >>= 1 ;
    for(int i = 0 ; i < 31 ; i++) {
        ret ^= x&1 ;
        x >>= 1 ;
    }
    return ret ;
}

void check(void) {
    assert(op(0b1110101101)) ;
    assert(op(0b11100101100100)) ;
    assert(!op(0b11101101101)) ;
    assert(!op(0b111001011010100)) ;
}

int main(int argc, char *argv[]) {
    if(argc != 2) {
        std::cerr << "Syntax:" << argv[0] << " <size of the S box>" << std::endl ;
        return 1 ;
    }
    std::vector<int> substitution = {7, 3, 6, 1, 13, 9, 10, 11, 2, 12, 0, 4, 5, 15, 8, 14} ;
    std::vector<std::pair<int,int>> goodKeys ;
    int S = atoi(argv[1]) ;
    int nbElt = 1<<S ;
    std::cout << "\\[\n\\bordermatrix{\n& " ;
    for(int b = 0 ; b < nbElt-1 ; b++) {
        std::cout << b << " & " ;
    }
    std::cout << nbElt-1 << "\\cr\n" ;
    for(int a = 0 ; a < nbElt ; a++) {
        std::cout << a << " & " ;
        for(int b = 0 ; b < nbElt ; b++) {
            int nbKey = 0 ;
            for(int c = 0 ; c < nbElt ; c++) {
                Block blockA(a) ;
                Block blockB(b) ;
                Block key(c) ;
                blockA.product(key) ;
                key.substitution() ;
                blockB.product(key) ;
                if(blockA.bitsXor() == blockB.bitsXor()) {
                    nbKey ++ ;
                }
            }
            std::cout << nbKey ;
            double proba = ((double)nbKey)/16 ;
            if(abs(proba - 0.5) > 0.3) {
                // std::cout << nbKey ;
                goodKeys.push_back(std::pair<int,int>(a, b)) ;
            }
            if(b < nbElt-1)
                std::cout << " & " ;
        }
        std::cout << "\\cr\n" ;
    }
    std::cout << "}\n\\]\n";
    std::cout << "Couples (a, b) with the highest probability:\n\\[" ;
    if(goodKeys.size() > 0)
        std::cout << "(" << goodKeys[0].first << ", " << goodKeys[0].second << ")" ;
    for(unsigned i = 1 ; i < goodKeys.size() ; i++) {
        std::cout << ", (" << goodKeys[i].first << ", " << goodKeys[i].second << ")" ;
    }
    std::cout << "\\]\n" ;
    return 0 ;
}
<commit_msg>Remove useless stuff.<commit_after>#include <iostream>
#include <fstream>
#include <vector>
#include <cassert>

#include "structures.h"

int main(int argc, char *argv[]) {
    if(argc != 2) {
        std::cerr << "Syntax:" << argv[0] << " <size of the S box>" << std::endl ;
        return 1 ;
    }
    std::vector<std::pair<int,int>> goodKeys ;
    int S = atoi(argv[1]) ;
    int nbElt = 1<<S ;
    std::cout << "\\[\n\\bordermatrix{\n& " ;
    for(int b = 0 ; b < nbElt-1 ; b++) {
        std::cout << b << " & " ;
    }
    std::cout << nbElt-1 << "\\cr\n" ;
    for(int a = 0 ; a < nbElt ; a++) {
        std::cout << a << " & " ;
        for(int b = 0 ; b < nbElt ; b++) {
            int nbKey = 0 ;
            for(int c = 0 ; c < nbElt ; c++) {
                Block blockA(a) ;
                Block blockB(b) ;
                Block key(c) ;
                blockA.product(key) ;
                key.substitution() ;
                blockB.product(key) ;
                if(blockA.bitsXor() == blockB.bitsXor()) {
                    nbKey ++ ;
                }
            }
            std::cout << nbKey ;
            double proba = ((double)nbKey)/16 ;
            if(abs(proba - 0.5) > 0.3) {
                // std::cout << nbKey ;
                goodKeys.push_back(std::pair<int,int>(a, b)) ;
            }
            if(b < nbElt-1)
                std::cout << " & " ;
        }
        std::cout << "\\cr\n" ;
    }
    std::cout << "}\n\\]\n";
    std::cout << "Couples (a, b) with the highest probability:\n\\[" ;
    if(goodKeys.size() > 0)
        std::cout << "(" << goodKeys[0].first << ", " << goodKeys[0].second << ")" ;
    for(unsigned i = 1 ; i < goodKeys.size() ; i++) {
        std::cout << ", (" << goodKeys[i].first << ", " << goodKeys[i].second << ")" ;
    }
    std::cout << "\\]\n" ;
    return 0 ;
}
<|endoftext|>


<commit_before>#include <vector>
#include <fstream>
#include <string>
#include <sys/stat.h>
#include <Windows.h>
#include <tinydir/tinydir.h>

char appplication_folder[1024];
void set_application_folder( char const* application_path )
{
    int length = strrchr( application_path, '\\' ) - application_path + 1;
    memcpy( appplication_folder, application_path, length );
    appplication_folder[length] = 0;
}

char const* get_application_folder()
{
    return appplication_folder;
}

bool run( char* command_line )
{
	return system( command_line ) == 0;
}

struct compiler
{
    compiler( char const* compiler_path )
    :   path( compiler_path )
    {
        int ext_begin = strrchr(compiler_path, '\\') - compiler_path + 1;
        int ext_end = strrchr(compiler_path, '.') - compiler_path - ext_begin;
        extension = path.substr(ext_begin, ext_end);
    }

    void compile( char const* asset_path, char const* output_folder )
    {
        char command_line[1024];
        sprintf( command_line, "%s \"%s\" \"%s\"", path.c_str(), asset_path, output_folder );
        run( command_line );
    }

    std::string extension;
    std::string path;
};

typedef std::vector< std::string > file_list;
typedef std::vector< compiler* > compiler_list;

void list_files( char const* folder, char const* extension, file_list& files )
{
    char search_key[1024];
    sprintf( search_key, "%s\\*", folder, extension );

    WIN32_FIND_DATA find_data;
    HANDLE find_handle = FindFirstFile( search_key, &find_data );

    if( find_handle != INVALID_HANDLE_VALUE )
    {
        do
        {
            if( strstr( find_data.cFileName, extension ) && strlen( strstr( find_data.cFileName, extension ) ) == strlen( extension ) )
            {
                char file_path[1024];
                sprintf( file_path, "%s\\%s", folder, find_data.cFileName );
                files.push_back( file_path );
            }
            else if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
            {
                if( find_data.cFileName[0] != '.' )
                {
                    char subfolder[2048];
                    sprintf( subfolder, "%s\\%s", folder, find_data.cFileName );

                    list_files( subfolder, extension, files );
                }
            }
        }while( FindNextFile( find_handle, &find_data ) );
    }
}

void list_folders( char const* path, file_list& folders )
{
    char search_key[1024];
    sprintf( search_key, "%s\\*", path );

    WIN32_FIND_DATA find_data;
    HANDLE find_handle = FindFirstFile( search_key, &find_data );

    if( find_handle != INVALID_HANDLE_VALUE )
    {
        do
        {
            if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
            {
                if( find_data.cFileName[0] != '.' )
                {
                    char subfolder[2048];
                    sprintf( subfolder, "%s\\%s", path, find_data.cFileName );

                    folders.push_back( subfolder );
                }
            }
        }while( FindNextFile( find_handle, &find_data ) );
    }
}

compiler_list get_compilers( char const* folder )
{
    file_list paths;
    list_files( folder, "exe", paths );
    compiler_list compilers;
    for( file_list::iterator iter = paths.begin(); iter != paths.end(); ++iter )
    {
        char const* path = (*iter).c_str();
        compilers.push_back( new compiler( path ) );
    }
    return compilers;
}

void compile_folder( compiler* c, char const* asset_folder, char const* mod_folder )
{
    file_list files;
    list_files( asset_folder, c->extension.c_str(), files );
    for( file_list::iterator file_iter = files.begin(); file_iter != files.end(); ++file_iter )
    {
        c->compile( file_iter->c_str(), mod_folder );
    }
}

void get_asset_folders( compiler& c, file_list& asset_folders )
{
    std::string asset_list_path = c.path + std::string( ".txt" );
    std::ifstream in = std::ifstream( asset_list_path.c_str() );

    char path[1024];
    while( !in.eof() )
    {
        in.getline( path, sizeof( path ) );
        asset_folders.push_back( path );
    }
}

int main( int argument_count, char** arguments )
{
    char module_name[1024];
    GetModuleFileName( 0, module_name, 1024 );
    set_application_folder( module_name );

    file_list mod_folders;
    char mods_folder[1024];

    sprintf( mods_folder, "%s..\\..\\mods", get_application_folder() );
    list_folders( mods_folder, mod_folders );

    sprintf( mods_folder, "%s..\\..\\dont_starve\\mods", get_application_folder() );
    list_folders( mods_folder, mod_folders );

    char compilers_folder[1024] ;
    sprintf( compilers_folder, "%scompilers", get_application_folder() );

    compiler_list compilers = get_compilers( compilers_folder );
    for( compiler_list::iterator iter = compilers.begin(); iter != compilers.end(); ++iter )
    {
        compiler* c = *iter;
        file_list asset_folders;
        get_asset_folders( *c, asset_folders );

        for( file_list::iterator mod_folder_iter = mod_folders.begin(); mod_folder_iter != mod_folders.end(); ++mod_folder_iter )
        {
            for( file_list::iterator asset_folder_iter = asset_folders.begin(); asset_folder_iter != asset_folders.end(); ++asset_folder_iter )
            {
                char asset_folder[1024];
                sprintf( asset_folder, "%s/%s", mod_folder_iter->c_str(), asset_folder_iter->c_str() );
                compile_folder( c, asset_folder, mod_folder_iter->c_str() );
            }
        }
   }

    return 0;
}<commit_msg>Just use arg[0] to get application folder.  Removes another windows.h dependency.<commit_after>#include <vector>
#include <fstream>
#include <string>
#include <sys/stat.h>
#include <Windows.h>
#include <tinydir/tinydir.h>

char appplication_folder[1024];
void set_application_folder( char const* application_path )
{
    int length = strrchr( application_path, '\\' ) - application_path + 1;
    memcpy( appplication_folder, application_path, length );
    appplication_folder[length] = 0;
}

char const* get_application_folder()
{
    return appplication_folder;
}

bool run( char* command_line )
{
	return system( command_line ) == 0;
}

struct compiler
{
    compiler( char const* compiler_path )
    :   path( compiler_path )
    {
        int ext_begin = strrchr(compiler_path, '\\') - compiler_path + 1;
        int ext_end = strrchr(compiler_path, '.') - compiler_path - ext_begin;
        extension = path.substr(ext_begin, ext_end);
    }

    void compile( char const* asset_path, char const* output_folder )
    {
        char command_line[1024];
        sprintf( command_line, "%s \"%s\" \"%s\"", path.c_str(), asset_path, output_folder );
        run( command_line );
    }

    std::string extension;
    std::string path;
};

typedef std::vector< std::string > file_list;
typedef std::vector< compiler* > compiler_list;

void list_files( char const* folder, char const* extension, file_list& files )
{
    char search_key[1024];
    sprintf( search_key, "%s\\*", folder, extension );

    WIN32_FIND_DATA find_data;
    HANDLE find_handle = FindFirstFile( search_key, &find_data );

    if( find_handle != INVALID_HANDLE_VALUE )
    {
        do
        {
            if( strstr( find_data.cFileName, extension ) && strlen( strstr( find_data.cFileName, extension ) ) == strlen( extension ) )
            {
                char file_path[1024];
                sprintf( file_path, "%s\\%s", folder, find_data.cFileName );
                files.push_back( file_path );
            }
            else if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
            {
                if( find_data.cFileName[0] != '.' )
                {
                    char subfolder[2048];
                    sprintf( subfolder, "%s\\%s", folder, find_data.cFileName );

                    list_files( subfolder, extension, files );
                }
            }
        }while( FindNextFile( find_handle, &find_data ) );
    }
}

void list_folders( char const* path, file_list& folders )
{
    char search_key[1024];
    sprintf( search_key, "%s\\*", path );

    WIN32_FIND_DATA find_data;
    HANDLE find_handle = FindFirstFile( search_key, &find_data );

    if( find_handle != INVALID_HANDLE_VALUE )
    {
        do
        {
            if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
            {
                if( find_data.cFileName[0] != '.' )
                {
                    char subfolder[2048];
                    sprintf( subfolder, "%s\\%s", path, find_data.cFileName );

                    folders.push_back( subfolder );
                }
            }
        }while( FindNextFile( find_handle, &find_data ) );
    }
}

compiler_list get_compilers( char const* folder )
{
    file_list paths;
    list_files( folder, "exe", paths );
    compiler_list compilers;
    for( file_list::iterator iter = paths.begin(); iter != paths.end(); ++iter )
    {
        char const* path = (*iter).c_str();
        compilers.push_back( new compiler( path ) );
    }
    return compilers;
}

void compile_folder( compiler* c, char const* asset_folder, char const* mod_folder )
{
    file_list files;
    list_files( asset_folder, c->extension.c_str(), files );
    for( file_list::iterator file_iter = files.begin(); file_iter != files.end(); ++file_iter )
    {
        c->compile( file_iter->c_str(), mod_folder );
    }
}

void get_asset_folders( compiler& c, file_list& asset_folders )
{
    std::string asset_list_path = c.path + std::string( ".txt" );
    std::ifstream in = std::ifstream( asset_list_path.c_str() );

    char path[1024];
    while( !in.eof() )
    {
        in.getline( path, sizeof( path ) );
        asset_folders.push_back( path );
    }
}

int main( int argument_count, char** arguments )
{
    set_application_folder( arguments[0] );

    file_list mod_folders;
    char mods_folder[1024];

    sprintf( mods_folder, "%s..\\..\\mods", get_application_folder() );
    list_folders( mods_folder, mod_folders );

    sprintf( mods_folder, "%s..\\..\\dont_starve\\mods", get_application_folder() );
    list_folders( mods_folder, mod_folders );

    char compilers_folder[1024] ;
    sprintf( compilers_folder, "%scompilers", get_application_folder() );

    compiler_list compilers = get_compilers( compilers_folder );
    for( compiler_list::iterator iter = compilers.begin(); iter != compilers.end(); ++iter )
    {
        compiler* c = *iter;
        file_list asset_folders;
        get_asset_folders( *c, asset_folders );

        for( file_list::iterator mod_folder_iter = mod_folders.begin(); mod_folder_iter != mod_folders.end(); ++mod_folder_iter )
        {
            for( file_list::iterator asset_folder_iter = asset_folders.begin(); asset_folder_iter != asset_folders.end(); ++asset_folder_iter )
            {
                char asset_folder[1024];
                sprintf( asset_folder, "%s/%s", mod_folder_iter->c_str(), asset_folder_iter->c_str() );
                compile_folder( c, asset_folder, mod_folder_iter->c_str() );
            }
        }
   }

    return 0;
}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2006 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

#include "arch/sparc/isa_traits.hh"
#include "arch/sparc/registers.hh"
#include "arch/sparc/nativetrace.hh"
#include "cpu/thread_context.hh"
#include "params/SparcNativeTrace.hh"

namespace Trace {

static char *intRegNames[SparcISA::NumIntArchRegs] = {
    //Global registers
    "g0", "g1", "g2", "g3", "g4", "g5", "g6", "g7",
    //Output registers
    "o0", "o1", "o2", "o3", "o4", "o5", "o6", "o7",
    //Local registers
    "l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7",
    //Input registers
    "i0", "i1", "i2", "i3", "i4", "i5", "i6", "i7",
};

void
Trace::SparcNativeTrace::check(NativeTraceRecord *record)
{
    ThreadContext *tc = record->getThread();

    uint64_t regVal, realRegVal;

    // Integer registers

    // I doubt a real SPARC will describe more integer registers than this.
    assert(SparcISA::NumIntArchRegs == 32);
    char **regName = intRegNames;
    for (int i = 0; i < SparcISA::NumIntArchRegs; i++) {
        regVal = tc->readIntReg(i);
        read(&realRegVal, sizeof(realRegVal));
        realRegVal = SparcISA::gtoh(realRegVal);
        checkReg(*(regName++), regVal, realRegVal);
    }

    // PC
    read(&realRegVal, sizeof(realRegVal));
    realRegVal = SparcISA::gtoh(realRegVal);
    regVal = tc->readNextPC();
    checkReg("pc", regVal, realRegVal);

    // NPC
    read(&realRegVal, sizeof(realRegVal));
    realRegVal = SparcISA::gtoh(realRegVal);
    regVal = tc->readNextNPC();
    checkReg("npc", regVal, realRegVal);

    // CCR
    read(&realRegVal, sizeof(realRegVal));
    realRegVal = SparcISA::gtoh(realRegVal);
    regVal = tc->readIntReg(SparcISA::NumIntArchRegs + 2);
    checkReg("ccr", regVal, realRegVal);
}

} /* namespace Trace */

////////////////////////////////////////////////////////////////////////
//
//  ExeTracer Simulation Object
//
Trace::SparcNativeTrace *
SparcNativeTraceParams::create()
{
    return new Trace::SparcNativeTrace(this);
};
<commit_msg>SPARC: Fix a minor compile bug in native trace on gcc > 4.1.<commit_after>/*
 * Copyright (c) 2006 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

#include "arch/sparc/isa_traits.hh"
#include "arch/sparc/registers.hh"
#include "arch/sparc/nativetrace.hh"
#include "cpu/thread_context.hh"
#include "params/SparcNativeTrace.hh"

namespace Trace {

static const char *intRegNames[SparcISA::NumIntArchRegs] = {
    //Global registers
    "g0", "g1", "g2", "g3", "g4", "g5", "g6", "g7",
    //Output registers
    "o0", "o1", "o2", "o3", "o4", "o5", "o6", "o7",
    //Local registers
    "l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7",
    //Input registers
    "i0", "i1", "i2", "i3", "i4", "i5", "i6", "i7",
};

void
Trace::SparcNativeTrace::check(NativeTraceRecord *record)
{
    ThreadContext *tc = record->getThread();

    uint64_t regVal, realRegVal;

    // Integer registers

    // I doubt a real SPARC will describe more integer registers than this.
    assert(SparcISA::NumIntArchRegs == 32);
    const char **regName = intRegNames;
    for (int i = 0; i < SparcISA::NumIntArchRegs; i++) {
        regVal = tc->readIntReg(i);
        read(&realRegVal, sizeof(realRegVal));
        realRegVal = SparcISA::gtoh(realRegVal);
        checkReg(*(regName++), regVal, realRegVal);
    }

    // PC
    read(&realRegVal, sizeof(realRegVal));
    realRegVal = SparcISA::gtoh(realRegVal);
    regVal = tc->readNextPC();
    checkReg("pc", regVal, realRegVal);

    // NPC
    read(&realRegVal, sizeof(realRegVal));
    realRegVal = SparcISA::gtoh(realRegVal);
    regVal = tc->readNextNPC();
    checkReg("npc", regVal, realRegVal);

    // CCR
    read(&realRegVal, sizeof(realRegVal));
    realRegVal = SparcISA::gtoh(realRegVal);
    regVal = tc->readIntReg(SparcISA::NumIntArchRegs + 2);
    checkReg("ccr", regVal, realRegVal);
}

} /* namespace Trace */

////////////////////////////////////////////////////////////////////////
//
//  ExeTracer Simulation Object
//
Trace::SparcNativeTrace *
SparcNativeTraceParams::create()
{
    return new Trace::SparcNativeTrace(this);
};
<|endoftext|>