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

#pragma hdrstop

#ifndef _XTABLE_HXX
#include <svx/xtable.hxx>
#endif
#ifndef _SVX_DLG_NAME_HXX //autogen
#include <svx/dlgname.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#ifndef _SVDOPATH_HXX //autogen
#include <svx/svdopath.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif

#include "strings.hrc"

#ifndef _SD_VIEWSHEL_HXX
#include "viewshel.hxx"
#endif

#include "helpids.h"
#include "sdresid.hxx"
#include "drawdoc.hxx"
#include "sdview.hxx"
#include "sdwindow.hxx"
#include "fulinend.hxx"

#define BITMAP_WIDTH  32
#define BITMAP_HEIGHT 12

TYPEINIT1( FuLineEnd, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuLineEnd::FuLineEnd(SdViewShell* pViewSh, SdWindow* pWin, SdView* pView,
                    SdDrawDocument* pDoc, SfxRequest& rReq)
    : FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
    const SdrMarkList& rMarkList = pView->GetMarkList();

    if( rMarkList.GetMarkCount() == 1 )
    {
        const SdrObject* pObj = rMarkList.GetMark(0)->GetObj();
        const SdrObject* pNewObj;
        SdrObject* pConvPolyObj = NULL;

        if( pObj->ISA( SdrPathObj ) )
        {
            pNewObj = pObj;
        }
        else
        {
            SdrObjTransformInfoRec aInfoRec;
            pObj->TakeObjInfo( aInfoRec );

            if( aInfoRec.bCanConvToPath &&
                pObj->GetObjInventor() == SdrInventor &&
                pObj->GetObjIdentifier() != OBJ_GRUP )
                // bCanConvToPath ist bei Gruppenobjekten TRUE,
                // stuerzt aber bei ConvertToPathObj() ab !
            {
                pNewObj = pConvPolyObj = pObj->ConvertToPolyObj( TRUE, FALSE );

                if( !pNewObj || !pNewObj->ISA( SdrPathObj ) )
                    return; // Abbruch, zusaetzliche Sicherheit, die bei
                            // Gruppenobjekten aber nichts bringt.
            }
            else return; // Abbruch
        }

        const XPolygon aXPoly = ( (SdrPathObj*) pNewObj )->GetPathPoly().GetObject( 0 );

        // Loeschen des angelegten PolyObjektes
        if( pConvPolyObj )
            delete pConvPolyObj;

        XLineEndList* pLineEndList = pDoc->GetLineEndList();
        XLineEndEntry* pEntry;

        String aNewName( SdResId( STR_LINEEND ) );
        String aDesc( SdResId( STR_DESC_LINEEND ) );
        String aName;

        long nCount = pLineEndList->Count();
        long j = 1;
        BOOL bDifferent = FALSE;

        while( !bDifferent )
        {
            aName = aNewName;
            aName.Append( sal_Unicode(' ') );
            aName.Append( UniString::CreateFromInt32( j++ ) );
            bDifferent = TRUE;
            for( long i = 0; i < nCount && bDifferent; i++ )
            {
                if( aName == pLineEndList->Get( i )->GetName() )
                    bDifferent = FALSE;
            }
        }

        SvxNameDialog* pDlg = new SvxNameDialog( NULL, aName, aDesc );
        pDlg->SetEditHelpId( HID_SD_NAMEDIALOG_LINEEND );

        if( pDlg->Execute() == RET_OK )
        {
            pDlg->GetName( aName );
            bDifferent = TRUE;

            for( long i = 0; i < nCount && bDifferent; i++ )
            {
                if( aName == pLineEndList->Get( i )->GetName() )
                    bDifferent = FALSE;
            }

            if( bDifferent )
            {
            /*
                XOutdevItemPool* pItemPool = (XOutdevItemPool*) &pViewSh->GetPool();
                XLineAttrSetItem aXLSet( pItemPool );
                XFillAttrSetItem aXFSet( pItemPool );
                VirtualDevice    aTmpVD ( *pWindow );
                XOutputDevice    aTmpXOut( &aTmpVD, pItemPool );

                aTmpVD.ChangeMapMode( MAP_100TH_MM );
                aTmpVD.SetOutputSize( aTmpVD.PixelToLogic( Size( BITMAP_WIDTH * 2, BITMAP_HEIGHT ) ) );
                aXLSet.GetItemSet().Put( XLineStartWidthItem( aTmpVD.GetOutputSize().Height() ) );
                aXLSet.GetItemSet().Put( XLineEndWidthItem( aTmpVD.GetOutputSize().Height() ) );
                aXFSet.GetItemSet().Put( XFillColorItem( String(), Color( COL_WHITE ) ) );
                aXFSet.GetItemSet().Put( XFillStyleItem( XFILL_SOLID ) );
                aXLSet.GetItemSet().Put( XLineStyleItem( XLINE_NONE ) );

                aTmpXOut.SetLineAttr( ( const XLineAttrSetItem& ) pItemPool->Put( aXLSet ) );
                aTmpXOut.SetFillAttr( ( const XFillAttrSetItem& ) pItemPool->Put( aXFSet ) );
                aTmpXOut.DrawRect( Rectangle( Point(), aTmpVD.GetOutputSize() ) );

                aXLSet.GetItemSet().Put( XLineStyleItem( XLINE_SOLID ) );
                aXLSet.GetItemSet().Put( XLineStartItem( String(), aXPoly ) );
                aXLSet.GetItemSet().Put( XLineEndItem( String(), aXPoly ) );

                aTmpXOut.SetLineAttr( ( const XLineAttrSetItem& ) pItemPool->Put( aXLSet ) );
                aTmpXOut.DrawLine( Point( 0, aTmpVD.GetOutputSize().Height() / 2 ),
                                    Point( aTmpVD.GetOutputSize().Width(), aTmpVD.GetOutputSize().Height() / 2 ) );
                Bitmap* pBitmap = new Bitmap( aTmpVD.GetBitmap( Point(), aTmpVD.GetOutputSize() ) );
            */
                pEntry = new XLineEndEntry( aXPoly, aName );
                pLineEndList->Insert( pEntry, LIST_APPEND);
            }
            else
            {
                String aStr(SdResId( STR_WARN_NAME_DUPLICATE ));
                WarningBox aWarningBox( pWin, WinBits( WB_OK ),
                     aStr );
                aWarningBox.Execute();
            }
        }
        delete pDlg;
    }
}

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

#pragma hdrstop

#include "fulinend.hxx"

#ifndef _XTABLE_HXX
#include <svx/xtable.hxx>
#endif
#ifndef _SVX_DLG_NAME_HXX //autogen
#include <svx/dlgname.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#ifndef _SVDOPATH_HXX //autogen
#include <svx/svdopath.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif

#include "strings.hrc"
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#include "helpids.h"
#include "sdresid.hxx"
#include "drawdoc.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_WINDOW_SHELL_HXX
#include "Window.hxx"
#endif

namespace sd {

#define BITMAP_WIDTH  32
#define BITMAP_HEIGHT 12

TYPEINIT1( FuLineEnd, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuLineEnd::FuLineEnd(ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView,
                    SdDrawDocument* pDoc, SfxRequest& rReq)
    : FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
    const SdrMarkList& rMarkList = pView->GetMarkList();

    if( rMarkList.GetMarkCount() == 1 )
    {
        const SdrObject* pObj = rMarkList.GetMark(0)->GetObj();
        const SdrObject* pNewObj;
        SdrObject* pConvPolyObj = NULL;

        if( pObj->ISA( SdrPathObj ) )
        {
            pNewObj = pObj;
        }
        else
        {
            SdrObjTransformInfoRec aInfoRec;
            pObj->TakeObjInfo( aInfoRec );

            if( aInfoRec.bCanConvToPath &&
                pObj->GetObjInventor() == SdrInventor &&
                pObj->GetObjIdentifier() != OBJ_GRUP )
                // bCanConvToPath ist bei Gruppenobjekten TRUE,
                // stuerzt aber bei ConvertToPathObj() ab !
            {
                pNewObj = pConvPolyObj = pObj->ConvertToPolyObj( TRUE, FALSE );

                if( !pNewObj || !pNewObj->ISA( SdrPathObj ) )
                    return; // Abbruch, zusaetzliche Sicherheit, die bei
                            // Gruppenobjekten aber nichts bringt.
            }
            else return; // Abbruch
        }

        const XPolygon aXPoly = ( (SdrPathObj*) pNewObj )->GetPathPoly().GetObject( 0 );

        // Loeschen des angelegten PolyObjektes
        if( pConvPolyObj )
            delete pConvPolyObj;

        XLineEndList* pLineEndList = pDoc->GetLineEndList();
        XLineEndEntry* pEntry;

        String aNewName( SdResId( STR_LINEEND ) );
        String aDesc( SdResId( STR_DESC_LINEEND ) );
        String aName;

        long nCount = pLineEndList->Count();
        long j = 1;
        BOOL bDifferent = FALSE;

        while( !bDifferent )
        {
            aName = aNewName;
            aName.Append( sal_Unicode(' ') );
            aName.Append( UniString::CreateFromInt32( j++ ) );
            bDifferent = TRUE;
            for( long i = 0; i < nCount && bDifferent; i++ )
            {
                if( aName == pLineEndList->Get( i )->GetName() )
                    bDifferent = FALSE;
            }
        }

        SvxNameDialog* pDlg = new SvxNameDialog( NULL, aName, aDesc );
        pDlg->SetEditHelpId( HID_SD_NAMEDIALOG_LINEEND );

        if( pDlg->Execute() == RET_OK )
        {
            pDlg->GetName( aName );
            bDifferent = TRUE;

            for( long i = 0; i < nCount && bDifferent; i++ )
            {
                if( aName == pLineEndList->Get( i )->GetName() )
                    bDifferent = FALSE;
            }

            if( bDifferent )
            {
            /*
                XOutdevItemPool* pItemPool = (XOutdevItemPool*) &pViewSh->GetPool();
                XLineAttrSetItem aXLSet( pItemPool );
                XFillAttrSetItem aXFSet( pItemPool );
                VirtualDevice    aTmpVD ( *pWindow );
                XOutputDevice    aTmpXOut( &aTmpVD, pItemPool );

                aTmpVD.ChangeMapMode( MAP_100TH_MM );
                aTmpVD.SetOutputSize( aTmpVD.PixelToLogic( Size( BITMAP_WIDTH * 2, BITMAP_HEIGHT ) ) );
                aXLSet.GetItemSet().Put( XLineStartWidthItem( aTmpVD.GetOutputSize().Height() ) );
                aXLSet.GetItemSet().Put( XLineEndWidthItem( aTmpVD.GetOutputSize().Height() ) );
                aXFSet.GetItemSet().Put( XFillColorItem( String(), Color( COL_WHITE ) ) );
                aXFSet.GetItemSet().Put( XFillStyleItem( XFILL_SOLID ) );
                aXLSet.GetItemSet().Put( XLineStyleItem( XLINE_NONE ) );

                aTmpXOut.SetLineAttr( ( const XLineAttrSetItem& ) pItemPool->Put( aXLSet ) );
                aTmpXOut.SetFillAttr( ( const XFillAttrSetItem& ) pItemPool->Put( aXFSet ) );
                aTmpXOut.DrawRect( Rectangle( Point(), aTmpVD.GetOutputSize() ) );

                aXLSet.GetItemSet().Put( XLineStyleItem( XLINE_SOLID ) );
                aXLSet.GetItemSet().Put( XLineStartItem( String(), aXPoly ) );
                aXLSet.GetItemSet().Put( XLineEndItem( String(), aXPoly ) );

                aTmpXOut.SetLineAttr( ( const XLineAttrSetItem& ) pItemPool->Put( aXLSet ) );
                aTmpXOut.DrawLine( Point( 0, aTmpVD.GetOutputSize().Height() / 2 ),
                                    Point( aTmpVD.GetOutputSize().Width(), aTmpVD.GetOutputSize().Height() / 2 ) );
                Bitmap* pBitmap = new Bitmap( aTmpVD.GetBitmap( Point(), aTmpVD.GetOutputSize() ) );
            */
                pEntry = new XLineEndEntry( aXPoly, aName );
                pLineEndList->Insert( pEntry, LIST_APPEND);
            }
            else
            {
                String aStr(SdResId( STR_WARN_NAME_DUPLICATE ));
                WarningBox aWarningBox( pWin, WinBits( WB_OK ),
                     aStr );
                aWarningBox.Execute();
            }
        }
        delete pDlg;
    }
}

} // end of namespace sd
<|endoftext|>


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

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_
#include <com/sun/star/beans/XPropertyState.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPE_HPP_
#include <com/sun/star/drawing/XShape.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTSSUPPLIER_HPP_
#include <com/sun/star/document/XEventsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTSSUPPLIER_HPP_
#include <com/sun/star/document/XEventsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif

#ifndef _SVDPOOL_HXX //autogen
#include <svx/svdpool.hxx>
#endif

#ifndef _SVX_UNOMASTER_HXX
#include <svx/unomaster.hxx>
#endif

#include <svx/unoipset.hxx>

#include <cppuhelper/implbase2.hxx>

class SdrObject;
class SdXImpressDocument;
class SdAnimationInfo;

class SdXShape : public SvxShapeMaster,
                 public ::com::sun::star::document::XEventsSupplier
{
    friend class SdUnoEventsAccess;

private:
    SvxShape* mpShape;
    SvxItemPropertySet  maPropSet;
    const SfxItemPropertyMap* mpMap;
    SdXImpressDocument* mpModel;

    void SetStyleSheet( const ::com::sun::star::uno::Any& rAny ) throw( ::com::sun::star::lang::IllegalArgumentException );
    ::com::sun::star::uno::Any GetStyleSheet() const throw( ::com::sun::star::beans::UnknownPropertyException  );

    // Intern
    SdAnimationInfo* GetAnimationInfo( sal_Bool bCreate = sal_False ) const throw();
    sal_Bool IsPresObj() const throw();
    void SetPresObj( sal_Bool bPresObj ) throw();

    sal_Bool IsEmptyPresObj() const throw();
    void SetEmptyPresObj( sal_Bool bEmpty ) throw();

    sal_Bool IsMasterDepend() const throw();
    void SetMasterDepend( sal_Bool bDepend ) throw();

    SdrObject* GetSdrObject() const throw();
    sal_Int32 GetPresentationOrderPos() const throw();
    void SetPresentationOrderPos( sal_Int32 nPos ) throw();

    com::sun::star::uno::Sequence< sal_Int8 >* mpImplementationId;

public:
    SdXShape() throw();
    SdXShape(SvxShape* pShape, SdXImpressDocument* pModel) throw();
    virtual ~SdXShape() throw();

    virtual sal_Bool queryAggregation( const com::sun::star::uno::Type & rType, com::sun::star::uno::Any& aAny );
    virtual void dispose();

    // XInterface
    virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL acquire() throw();
    virtual void SAL_CALL release() throw();

    // XServiceInfo
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);

    //XPropertySet
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    //XPropertyState
    virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XTypeProvider
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw(::com::sun::star::uno::RuntimeException);

    // XEventsSupplier
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > SAL_CALL getEvents(  ) throw(::com::sun::star::uno::RuntimeException);

private:
    void setOldEffect( const com::sun::star::uno::Any& aValue );
    void setOldTextEffect( const com::sun::star::uno::Any& aValue );
    void setOldSpeed( const com::sun::star::uno::Any& aValue );
    void setOldDimColor( const com::sun::star::uno::Any& aValue );
    void setOldDimHide( const com::sun::star::uno::Any& aValue );
    void setOldDimPrevious( const com::sun::star::uno::Any& aValue );
    void setOldPresOrder( const com::sun::star::uno::Any& aValue );

};

struct SvEventDescription;
const SvEventDescription* ImplGetSupportedMacroItems();

#endif

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

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_
#include <com/sun/star/beans/XPropertyState.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPE_HPP_
#include <com/sun/star/drawing/XShape.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTSSUPPLIER_HPP_
#include <com/sun/star/document/XEventsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTSSUPPLIER_HPP_
#include <com/sun/star/document/XEventsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif

#ifndef _SVDPOOL_HXX //autogen
#include <svx/svdpool.hxx>
#endif

#ifndef _SVX_UNOMASTER_HXX
#include <svx/unomaster.hxx>
#endif

#include <svx/unoipset.hxx>

#include <cppuhelper/implbase2.hxx>

class SdrObject;
class SdXImpressDocument;
class SdAnimationInfo;

class SdXShape : public SvxShapeMaster,
                 public ::com::sun::star::document::XEventsSupplier
{
    friend class SdUnoEventsAccess;

private:
    SvxShape* mpShape;
    SvxItemPropertySet  maPropSet;
    const SfxItemPropertyMap* mpMap;
    SdXImpressDocument* mpModel;

    void SetStyleSheet( const ::com::sun::star::uno::Any& rAny ) throw( ::com::sun::star::lang::IllegalArgumentException );
    ::com::sun::star::uno::Any GetStyleSheet() const throw( ::com::sun::star::beans::UnknownPropertyException  );

    // Intern
    SdAnimationInfo* GetAnimationInfo( sal_Bool bCreate = sal_False ) const throw();
    sal_Bool IsPresObj() const throw();
    void SetPresObj( sal_Bool bPresObj ) throw();

    sal_Bool IsEmptyPresObj() const throw();
    void SetEmptyPresObj( sal_Bool bEmpty ) throw();

    sal_Bool IsMasterDepend() const throw();
    void SetMasterDepend( sal_Bool bDepend ) throw();

    SdrObject* GetSdrObject() const throw();
    sal_Int32 GetPresentationOrderPos() const throw();
    void SetPresentationOrderPos( sal_Int32 nPos ) throw();

    com::sun::star::uno::Sequence< sal_Int8 >* mpImplementationId;

public:
    SdXShape() throw();
    SdXShape(SvxShape* pShape, SdXImpressDocument* pModel) throw();
    virtual ~SdXShape() throw();

    virtual sal_Bool queryAggregation( const com::sun::star::uno::Type & rType, com::sun::star::uno::Any& aAny );
    virtual void dispose();

    // XInterface
    virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL acquire() throw();
    virtual void SAL_CALL release() throw();

    // XServiceInfo
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);

    //XPropertySet
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    //XPropertyState
    virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XTypeProvider
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw(::com::sun::star::uno::RuntimeException);

    // XEventsSupplier
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > SAL_CALL getEvents(  ) throw(::com::sun::star::uno::RuntimeException);

private:
    void setOldEffect( const com::sun::star::uno::Any& aValue );
    void setOldTextEffect( const com::sun::star::uno::Any& aValue );
    void setOldSpeed( const com::sun::star::uno::Any& aValue );
    void setOldDimColor( const com::sun::star::uno::Any& aValue );
    void setOldDimHide( const com::sun::star::uno::Any& aValue );
    void setOldDimPrevious( const com::sun::star::uno::Any& aValue );
    void setOldPresOrder( const com::sun::star::uno::Any& aValue );
    void updateOldSoundEffect( SdAnimationInfo* pInfo );

};

struct SvEventDescription;
const SvEventDescription* ImplGetSupportedMacroItems();

#endif

<|endoftext|>


<commit_before><commit_msg>coverity#1251173 Dereference before null check<commit_after><|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// taskd - Task Server
//
// Copyright 2010 - 2012, Göteborg Bit Factory.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include <sstream>
#include <cstring>
#include <inttypes.h>
#include <unistd.h>
#include <Server.h>
#include <Timer.h>
#include <Log.h>
#include <Date.h>
#include <Duration.h>
#include <Color.h>
#include <cmake.h>
#include <commit.h>
#include <text.h>
#include <taskd.h>

////////////////////////////////////////////////////////////////////////////////
class Daemon : public Server
{
public:
  Daemon (Config&);
  void handler (const std::string& input, std::string& output);

private:
  void handle_statistics (const Msg&, Msg&);
  void handle_sync       (const Msg&, Msg&);

private:
  Config& _config;
  Date _start;
  long _txn_count;
  long _error_count;
  double _busy;
  double _max_time;
  long _bytes_in;
  long _bytes_out;
};

////////////////////////////////////////////////////////////////////////////////
Daemon::Daemon (Config& settings)
: _config (settings)
, _start (Date ())
, _txn_count (0)
, _error_count (0)
, _busy (0.0)
, _max_time (0.0)
, _bytes_in (0)
, _bytes_out (0)
{
}

////////////////////////////////////////////////////////////////////////////////
void Daemon::handler (const std::string& input, std::string& output)
{
  ++_txn_count;

  try
  {
    // Verify input is UTF8.  From RFC4627:
    //
    //   JSON text SHALL be encoded in Unicode.  The default encoding is
    //   UTF-8.
    //
    //   Since the first two characters of a JSON text will always be ASCII
    //   characters [RFC0020], it is possible to determine whether an octet
    //   stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking
    //   at the pattern of nulls in the first four octets.
    //
    //           00 00 00 xx  UTF-32BE
    //           00 xx 00 xx  UTF-16BE
    //           xx 00 00 00  UTF-32LE
    //           xx 00 xx 00  UTF-16LE
    //           xx xx xx xx  UTF-8
    if (input.length () >= 4 &&
        (!input[0]           ||
         !input[1]           ||
         !input[2]           ||
         !input[3]))
      throw 401;

    unsigned int request_limit = (unsigned) _config.getInteger ("request.limit");
    if (request_limit > 0 &&
        input.length () >= request_limit)
      throw 504;

    HighResTimer timer;
    timer.start ();

    // Request-specific processing here.
    Msg in;
    in.parse (input);
    Msg out;

    if (_config.getBoolean ("debug"))
    {
      // TODO dump incoming msg
    }

    // Handle or reject all message types.
    std::string type = in.get ("type");
         if (type == "statistics") handle_statistics (in, out);
    else if (type == "sync")       handle_sync       (in, out);
    else
      throw 500;

    output = out.serialize ();

    // Record response time.
    timer.stop ();
    double total = timer.total ();
    _busy += total;

    // Record high-water mark.
    if (total > _max_time)
      _max_time = total;
  }

  // Handlers can throw a status code, for a generic message.
  catch (int e)
  {
    ++_error_count;
    Msg err;
    err.set ("code", e);
    err.set ("status", taskd_error (e));
    output = err.serialize ();

    if (_log)
      _log->format ("[%d] ERROR %d %s", _txn_count, e, taskd_error (e).c_str ());
  }

  // Handlers can throw a string, for a 500 code with specific text.
  catch (std::string& e)
  {
    ++_error_count;
    Msg err;
    err.set ("code", 500);
    err.set ("status", e);
    output = err.serialize ();

    if (_log)
      _log->format ("[%d] %s", _txn_count, e.c_str ());
  }

  _bytes_in  += input.length ();
  _bytes_out += output.length ();
}

////////////////////////////////////////////////////////////////////////////////
// Statistics request from dev.
void Daemon::handle_statistics (const Msg& in, Msg& out)
{
  if (! taskd_authenticate (_config, *_log, in, out))
    return;

  if (_log)
    _log->format ("[%d] 'statistics' from %s:%d",
                  _txn_count,
                  _client_address.c_str (),
                  _client_port);

  time_t uptime = Date () - _start;
  double idle = 0.0;
  if (uptime != 0)
    idle = 1.0 - (_busy / (double) uptime);

  int average_req          = 0;
  int average_resp         = 0;
  double average_resp_time = 0.0;
  int tps                  = 0;
  if (_txn_count)
  {
    average_req       = _bytes_in  / _txn_count;
    average_resp      = _bytes_out / _txn_count;
    average_resp_time = _busy      / _txn_count;

    // Only calculate tps if average_resp_time is non-trivial.
    if (average_resp_time > 0.000001)
      tps = (int) (1.0 / average_resp_time);
  }

  out.set ("uptime",                 (int) uptime);
  out.set ("transactions",           (int) _txn_count);
  out.set ("errors",                 (int) _error_count);
  out.set ("idle",                         idle);
  out.set ("total bytes in",         (int) _bytes_in);
  out.set ("total bytes out",        (int) _bytes_out);
  out.set ("average request bytes",  (int) average_req);
  out.set ("average response bytes", (int) average_resp);
  out.set ("average response time",        average_resp_time);
  out.set ("maximum response time",        _max_time);
  out.set ("tps",                          tps);

  out.set ("code",                         200);
  out.set ("status",                       taskd_error (200));
}

////////////////////////////////////////////////////////////////////////////////
// Sync request.
void Daemon::handle_sync (const Msg& in, Msg& out)
{
  if (! taskd_authenticate (_config, *_log, in, out))
    return;

  if (_log)
    _log->format ("[%d] 'sync' from %s:%d",
                  _txn_count,
                  _client_address.c_str (),
                  _client_port);

  // TODO Sync logic goes here.

  out.set ("code",   502);
  out.set ("status", taskd_error (502));
}

////////////////////////////////////////////////////////////////////////////////
int command_server (Config& config, const std::vector <std::string>& args)
{
  int status = 0;

  // Standard argument processing.
  bool verbose     = true;
  bool debug       = false;
  bool daemon      = false;
  bool use_ssl     = false;
  std::string root = "";

  std::vector <std::string>::const_iterator i;
  for (i = ++(args.begin ()); i != args.end (); ++i)
  {
         if (closeEnough ("--quiet",  *i, 3)) verbose = false;
    else if (closeEnough ("--debug",  *i, 3)) debug   = true;
    else if (closeEnough ("--daemon", *i, 3)) daemon  = true;
    else if (closeEnough ("--data",   *i, 3)) root    = *(++i);
    else if (closeEnough ("--ssl",    *i, 3)) use_ssl = true;
    else if (closeEnough ("--nossl",  *i, 3)) use_ssl = false;
    else if (taskd_applyOverride (config, *i))   ;
    else
      throw std::string ("ERROR: Unrecognized argument '") + *i + "'";
  }

  // Verify that root exists.
  if (root == "")
    throw std::string ("ERROR: The '--data' option is required.");

  Directory root_dir (root);
  if (!root_dir.exists ())
    throw std::string ("ERROR: The '--data' path does not exist.");

  // Load the config file.
  config.load (root_dir._data + "/config");
  config.set ("root", root_dir._data);

  // Preserve the verbose setting for this run.
  config.set ("verbose", verbose);
  config.set ("debug", debug);

  Log log;

  try
  {
    log.setFile (config.get ("log"));
    log.write (std::string ("==== ")
               + PACKAGE_STRING
               + " "
#ifdef HAVE_COMMIT
               + COMMIT
#endif
               + " ===="
              );

    log.format ("Serving from %s", root.c_str ());

    if (debug)
      log.write ("Debug mode");

    std::string serverDetails = config.get ("server");
    std::string::size_type colon = serverDetails.find (':');

    if (colon == std::string::npos)
      throw std::string ("ERROR: Malformed configuration setting 'server'");

    int port = strtoimax (serverDetails.substr (colon + 1).c_str (), NULL, 10);

    // Create a taskd server object.
    Daemon server        (config);
    server.setLog        (&log);
    server.setPort       (port);
    server.setQueueSize  (config.getInteger ("queue.size"));
    server.setLimit      (config.getInteger ("request.limit"));
    server.setLogClients (config.getBoolean ("ip.log"));

    // Optional daemonization.
    if (daemon)
    {
      server.setDaemon   ();
      server.setPidFile  (config.get ("pid.file"));
    }

    // It just runs until you kill it.
    if (use_ssl)
    {
/*
      // Resolve paths that may include ~.
      File cert (config.get ("certificate_file"));
      server.setCertFile (cert._data);

      File key (config.get ("key_file"));
      server.setKeyFile (key._data);

      server.beginSSLServer ();
*/
      std::cout << "ERROR: SSL not implemented.\n";
    }
    else
    {
      server.beginServer ();
    }
  }

  catch (std::string& error)
  {
    log.write (error);
    return -1;
  }

  catch (...)
  {
    log.write ("Unknown error");
    return -2;
  }

  return status;
}

////////////////////////////////////////////////////////////////////////////////
<commit_msg>Sync<commit_after>////////////////////////////////////////////////////////////////////////////////
// taskd - Task Server
//
// Copyright 2010 - 2012, Göteborg Bit Factory.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include <sstream>
#include <cstring>
#include <inttypes.h>
#include <unistd.h>
#include <Server.h>
#include <Timer.h>
#include <Log.h>
#include <Date.h>
#include <Duration.h>
#include <Color.h>
#include <cmake.h>
#include <commit.h>
#include <text.h>
#include <util.h>
#include <taskd.h>

////////////////////////////////////////////////////////////////////////////////
class Daemon : public Server
{
public:
  Daemon (Config&);
  void handler (const std::string& input, std::string& output);

private:
  void handle_statistics (const Msg&, Msg&);
  void handle_sync       (const Msg&, Msg&);

private:
  void parse_sync_payload (const std::string&, std::vector <std::string>&, std::string&) const;
  void load_server_data (const std::string&, const std::string&, std::vector <std::string>&) const;
  unsigned int find_branch_point (const std::vector <std::string>&, const std::string&) const;
  void extract_subset (const std::vector <std::string>&, const unsigned int, std::vector <std::string>&) const;

private:
  Config& _config;
  Date _start;
  long _txn_count;
  long _error_count;
  double _busy;
  double _max_time;
  long _bytes_in;
  long _bytes_out;
};

////////////////////////////////////////////////////////////////////////////////
Daemon::Daemon (Config& settings)
: _config (settings)
, _start (Date ())
, _txn_count (0)
, _error_count (0)
, _busy (0.0)
, _max_time (0.0)
, _bytes_in (0)
, _bytes_out (0)
{
}

////////////////////////////////////////////////////////////////////////////////
void Daemon::handler (const std::string& input, std::string& output)
{
  ++_txn_count;

  try
  {
    // Verify input is UTF8.  From RFC4627:
    //
    //   JSON text SHALL be encoded in Unicode.  The default encoding is
    //   UTF-8.
    //
    //   Since the first two characters of a JSON text will always be ASCII
    //   characters [RFC0020], it is possible to determine whether an octet
    //   stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking
    //   at the pattern of nulls in the first four octets.
    //
    //           00 00 00 xx  UTF-32BE
    //           00 xx 00 xx  UTF-16BE
    //           xx 00 00 00  UTF-32LE
    //           xx 00 xx 00  UTF-16LE
    //           xx xx xx xx  UTF-8
    if (input.length () >= 4 &&
        (!input[0]           ||
         !input[1]           ||
         !input[2]           ||
         !input[3]))
      throw 401;

    unsigned int request_limit = (unsigned) _config.getInteger ("request.limit");
    if (request_limit > 0 &&
        input.length () >= request_limit)
      throw 504;

    HighResTimer timer;
    timer.start ();

    // Request-specific processing here.
    Msg in;
    in.parse (input);
    Msg out;

    if (_config.getBoolean ("debug"))
    {
      // TODO dump incoming msg
    }

    // Handle or reject all message types.
    std::string type = in.get ("type");
         if (type == "statistics") handle_statistics (in, out);
    else if (type == "sync")       handle_sync       (in, out);
    else
      throw 500;

    output = out.serialize ();

    // Record response time.
    timer.stop ();
    double total = timer.total ();
    _busy += total;

    // Record high-water mark.
    if (total > _max_time)
      _max_time = total;
  }

  // Handlers can throw a status code, for a generic message.
  catch (int e)
  {
    ++_error_count;
    Msg err;
    err.set ("code", e);
    err.set ("status", taskd_error (e));
    output = err.serialize ();

    if (_log)
      _log->format ("[%d] ERROR %d %s", _txn_count, e, taskd_error (e).c_str ());
  }

  // Handlers can throw a string, for a 500 code with specific text.
  catch (std::string& e)
  {
    ++_error_count;
    Msg err;
    err.set ("code", 500);
    err.set ("status", e);
    output = err.serialize ();

    if (_log)
      _log->format ("[%d] %s", _txn_count, e.c_str ());
  }

  _bytes_in  += input.length ();
  _bytes_out += output.length ();
}

////////////////////////////////////////////////////////////////////////////////
// Statistics request from dev.
void Daemon::handle_statistics (const Msg& in, Msg& out)
{
  if (! taskd_authenticate (_config, *_log, in, out))
    return;

  if (_log)
    _log->format ("[%d] 'statistics' from %s:%d",
                  _txn_count,
                  _client_address.c_str (),
                  _client_port);

  time_t uptime = Date () - _start;
  double idle = 0.0;
  if (uptime != 0)
    idle = 1.0 - (_busy / (double) uptime);

  int average_req          = 0;
  int average_resp         = 0;
  double average_resp_time = 0.0;
  int tps                  = 0;
  if (_txn_count)
  {
    average_req       = _bytes_in  / _txn_count;
    average_resp      = _bytes_out / _txn_count;
    average_resp_time = _busy      / _txn_count;

    // Only calculate tps if average_resp_time is non-trivial.
    if (average_resp_time > 0.000001)
      tps = (int) (1.0 / average_resp_time);
  }

  out.set ("uptime",                 (int) uptime);
  out.set ("transactions",           (int) _txn_count);
  out.set ("errors",                 (int) _error_count);
  out.set ("idle",                         idle);
  out.set ("total bytes in",         (int) _bytes_in);
  out.set ("total bytes out",        (int) _bytes_out);
  out.set ("average request bytes",  (int) average_req);
  out.set ("average response bytes", (int) average_resp);
  out.set ("average response time",        average_resp_time);
  out.set ("maximum response time",        _max_time);
  out.set ("tps",                          tps);

  out.set ("code",                         200);
  out.set ("status",                       taskd_error (200));
}

////////////////////////////////////////////////////////////////////////////////
// Sync request.
void Daemon::handle_sync (const Msg& in, Msg& out)
{
  if (! taskd_authenticate (_config, *_log, in, out))
    return;

  // Note: org/user already validated during authentication.
  std::string org  = in.get ("org");
  std::string user = in.get ("user");

  if (_log)
    _log->format ("[%d] 'sync' from %s/%s at %s:%d",
                  _txn_count,
                  org.c_str (),
                  user.c_str (),
                  _client_address.c_str (),
                  _client_port);

  // Separate payload into client_data and client_key.
  std::vector <std::string> client_data;
  std::string client_key;
  parse_sync_payload (in.getPayload (), client_data, client_key);

  // TODO A missing client_key implies first-time sync, which results in all
  //      data being sent.

  // TODO Use Cases:
    // TODO Handle: no synch key, no tasks -> return new key
    // TODO Handle: no synch key, tasks    -> process, new key
    // TODO Handle: synch key, no tasks    -> process, new key
    // TODO Handle: synch key, tasks       -> process, new key

  // Load all user data.
  std::vector <std::string> server_data;
  load_server_data (org, user, server_data);

  // Find branch point and extract subset.
  unsigned int branch_point = find_branch_point (server_data, client_key);
  std::vector <std::string> server_subset;
  extract_subset (server_data, branch_point, server_subset);

  // TODO For each incoming
    // TODO If incoming is in subset
      // TODO Find common ancestor
      // TODO 3-way merge
      // TODO append to data
    // TODO else
      // TODO append to data

  // Create a new synch-key.
  std::string new_client_key = uuid ();
  _log->format ("[%d] New synch key: %s", _txn_count, new_client_key.c_str ());

  // TODO Respond with: subset + additions + new_client_key.
  std::string payload;
  // payload += subset;
  // payload += additions;
  payload += new_client_key + "\n";
  //out.setPayload (payload);

  out.set ("code",   502);
  out.set ("status", taskd_error (502));
}

////////////////////////////////////////////////////////////////////////////////
void Daemon::parse_sync_payload (
  const std::string& payload,
  std::vector <std::string>& data,
  std::string& key) const
{
  // Break payload into lines.
  std::vector <std::string> lines;
  split (lines, payload, '\n');
  _log->format ("[%d] Payload contains %d lines", _txn_count, lines.size ());

  // Separate into data and key.
  // TODO Some syntax checking would be nice.
  std::vector <std::string>::iterator i;
  for (i = lines.begin (); i != lines.end (); ++i)
    if ((*i)[0] == '[')
      data.push_back (*i);
    else
      key = *i;

  _log->format ("[%d] Client key: %s", _txn_count, key.c_str ());

  for (i = data.begin (); i != data.end (); ++i)
    _log->format ("[%d] Client data: %s", _txn_count, i->c_str ());
}

////////////////////////////////////////////////////////////////////////////////
void Daemon::load_server_data (
  const std::string& org,
  const std::string& user,
  std::vector <std::string>& data) const
{
  Directory user_dir (_config.get ("root"));
  user_dir += "orgs";
  user_dir += org;
  user_dir += "users";
  user_dir += user;
  File user_data (user_dir._data + "/tx.data");

  if (user_data.exists ())
    user_data.read (data);

  _log->format ("[%d] Read %u lines of server data", _txn_count, data.size ());
}

////////////////////////////////////////////////////////////////////////////////
// Note: A missing client_key implies first-time sync, which means the earliest
//       possible branch point is used.
unsigned int Daemon::find_branch_point (
  const std::vector <std::string>& data,
  const std::string& key) const
{
  unsigned int branch = 0;
  if (key == "")
    return 0;

  bool found = false;
  std::vector <std::string>::const_iterator i;
  for (i = data.begin (); i != data.end (); ++i)
    if (*i == key)
    {
      found = true;
      break;
    }
    else
      ++branch;

  if (!found)
    throw std::string ("Client synch key not found.");

  _log->format ("[%d] Branch point: %u", _txn_count, branch);
  return branch;
}

////////////////////////////////////////////////////////////////////////////////
void Daemon::extract_subset (
  const std::vector <std::string>& data,
  const unsigned int branch_point,
  std::vector <std::string>& subset) const
{
  if (branch_point < data.size ())
    for (unsigned int i = branch_point; i < data.size (); ++i)
      subset.push_back (data[i]);

  _log->format ("[%d] Subset is %u lines", _txn_count, subset.size ());
}

////////////////////////////////////////////////////////////////////////////////
int command_server (Config& config, const std::vector <std::string>& args)
{
  int status = 0;

  // Standard argument processing.
  bool verbose     = true;
  bool debug       = false;
  bool daemon      = false;
  bool use_ssl     = false;
  std::string root = "";

  std::vector <std::string>::const_iterator i;
  for (i = ++(args.begin ()); i != args.end (); ++i)
  {
         if (closeEnough ("--quiet",  *i, 3)) verbose = false;
    else if (closeEnough ("--debug",  *i, 3)) debug   = true;
    else if (closeEnough ("--daemon", *i, 3)) daemon  = true;
    else if (closeEnough ("--data",   *i, 3)) root    = *(++i);
    else if (closeEnough ("--ssl",    *i, 3)) use_ssl = true;
    else if (closeEnough ("--nossl",  *i, 3)) use_ssl = false;
    else if (taskd_applyOverride (config, *i))   ;
    else
      throw std::string ("ERROR: Unrecognized argument '") + *i + "'";
  }

  // Verify that root exists.
  if (root == "")
    throw std::string ("ERROR: The '--data' option is required.");

  Directory root_dir (root);
  if (!root_dir.exists ())
    throw std::string ("ERROR: The '--data' path does not exist.");

  // Load the config file.
  config.load (root_dir._data + "/config");
  config.set ("root", root_dir._data);

  // Preserve the verbose setting for this run.
  config.set ("verbose", verbose);
  config.set ("debug", debug);

  Log log;

  try
  {
    log.setFile (config.get ("log"));
    log.write (std::string ("==== ")
               + PACKAGE_STRING
               + " "
#ifdef HAVE_COMMIT
               + COMMIT
#endif
               + " ===="
              );

    log.format ("Serving from %s", root.c_str ());

    if (debug)
      log.write ("Debug mode");

    std::string serverDetails = config.get ("server");
    std::string::size_type colon = serverDetails.find (':');

    if (colon == std::string::npos)
      throw std::string ("ERROR: Malformed configuration setting 'server'");

    int port = strtoimax (serverDetails.substr (colon + 1).c_str (), NULL, 10);

    // Create a taskd server object.
    Daemon server        (config);
    server.setLog        (&log);
    server.setPort       (port);
    server.setQueueSize  (config.getInteger ("queue.size"));
    server.setLimit      (config.getInteger ("request.limit"));
    server.setLogClients (config.getBoolean ("ip.log"));

    // Optional daemonization.
    if (daemon)
    {
      server.setDaemon   ();
      server.setPidFile  (config.get ("pid.file"));
    }

    // It just runs until you kill it.
    if (use_ssl)
    {
/*
      // Resolve paths that may include ~.
      File cert (config.get ("certificate_file"));
      server.setCertFile (cert._data);

      File key (config.get ("key_file"));
      server.setKeyFile (key._data);

      server.beginSSLServer ();
*/
      std::cout << "ERROR: SSL not implemented.\n";
    }
    else
    {
      server.beginServer ();
    }
  }

  catch (std::string& error)
  {
    log.write (error);
    return -1;
  }

  catch (...)
  {
    log.write ("Unknown error");
    return -2;
  }

  return status;
}

////////////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>/**
 * Copyright (c) Sjors Gielen, 2010
 * See LICENSE for license.
 */

#include "dazeus.h"
#include "database.h"
#include "network.h"
#include "config.h"
#include "plugincomm.h"
#include <cassert>
#include <sstream>

// #define DEBUG
#define VERBOSE

/**
 * @brief Constructor.
 *
 * @param configFileName optional path to the configuration file. Configuration
 * will not be loaded automatically, use loadConfig() for that.
 */
DaZeus::DaZeus( std::string configFileName )
: config_( 0 )
, configFileName_( configFileName )
, plugins_( 0 )
, database_( 0 )
{
}

/**
 * @brief Destructor.
 */
DaZeus::~DaZeus()
{
  std::vector<Network*>::iterator it;
  for(it = networks_.begin(); it != networks_.end(); ++it)
  {
    (*it)->disconnectFromNetwork( Network::ShutdownReason );
    delete *it;
  }
  networks_.clear();

  delete plugins_;
}

/**
 * @brief Add additional sockets to the list defined in the configuration file.
 *
 * The application will listen on the given additional sockets.
 */
void DaZeus::addAdditionalSockets(const std::vector<std::string> &sockets)
{
	config_->addAdditionalSockets(sockets);
}

/**
 * @brief Connect to all networks marked "autoconnect".
 *
 * Warning: This method is usually called outside the event loop, just after
 * initialisation.
 */
void DaZeus::autoConnect()
{
#ifdef DEBUG
  fprintf(stderr, "DaZeus::autoConnect() called: looking for networks to connect to\n");
#endif
  std::vector<Network*>::iterator it;
  for(it = networks_.begin(); it != networks_.end(); ++it)
  {
    Network *n = *it;
    if( n->autoConnectEnabled() )
    {
#ifdef DEBUG
      // TODO: toString
      fprintf(stderr, "Connecting to %p (autoconnect is enabled)\n", n);
#endif
      n->connectToNetwork();
    }
#ifdef DEBUG
    else
    {
      // TODO: toString
      fprintf(stderr, "Not connecting to %p, autoconnect is disabled.\n", n);
    }
#endif
  }
}

std::string DaZeus::configFileName() const {
	return configFileName_;
}

/**
 * @brief Returns whether the configuration is loaded.
 */
bool DaZeus::configLoaded() const
{
  return config_ != 0;
}

/**
 * @brief Start connecting to the database.
 *
 * Does nothing if already connected.
 */
bool DaZeus::connectDatabase()
{
  const DatabaseConfig *dbc = config_->databaseConfig();
  if(dbc == 0) {
    fprintf(stderr, "Database configuration is absent, cannot continue.\n");
    return false;
  }
  database_ = new Database(dbc->hostname, dbc->port);

  if( !database_->open() )
  {
    fprintf(stderr, "Could not connect to database: %s\n", database_->lastError().c_str());
    return false;
  }

  return true;
}

/**
 * @brief Return the database.
 */
Database *DaZeus::database() const
{
  return database_;
}

/**
 * @brief Initialises plugins from the configuration file.
 */
bool DaZeus::initPlugins()
{
  assert(plugins_ != 0);
  plugins_->init();

  return true;
}

/**
 * @brief (Re-)loads configuration from the configuration file.
 *
 * If loading failed, this method returns false.
 * Note: this method is automatically called when setConfigFileName is called,
 * and by the constructor.
 */
bool DaZeus::loadConfig()
{
  assert( configFileName_.length() != 0 );

  if( config_ == 0 )
    config_ = new Config();

  if( !config_ )
    return false;

  config_->reset();
  config_->loadFromFile( configFileName_ );

  const std::vector<NetworkConfig*> &networks = config_->networks();

  if(!connectDatabase()) {
    delete config_;
    config_ = 0;
    return false;
  }

  if(plugins_)
    delete plugins_;
  plugins_ = new PluginComm( database_, config_, this );

  std::vector<NetworkConfig*>::const_iterator it;
  for(it = networks.begin(); it != networks.end(); ++it)
  {
    Network *net = new Network( *it, plugins_ );
    if( net == 0 ) {
      delete config_;
      config_ = 0;
      return false;
    }

    networks_.push_back( net );
  }

  // Pretty number of initialisations viewer -- and also an immediate database
  // check.
  std::stringstream numInitsStr;
  numInitsStr << database_->property("dazeus.numinits");
  int numInits;
  numInitsStr >> numInits;
  if(!numInitsStr)
    numInits = 0;
  ++numInits;
  numInitsStr.str(""); numInitsStr.clear();
  numInitsStr << numInits;
  database_->setProperty("dazeus.numinits", numInitsStr.str());
  const char *suffix = "th";
  if(numInits%100 == 11 ) ;
  else if(numInits%100 == 12) ;
  else if(numInits%100 == 13) ;
  else if(numInits%10 == 1) suffix = "st";
  else if(numInits%10 == 2) suffix = "nd";
  else if(numInits%10 == 3) suffix = "rd";
  printf("Initialising DaZeus for the %d%s time!\n", numInits, suffix);
  return true;
}

void DaZeus::run()
{
	while(1) {
		plugins_->run();
	}
}

void DaZeus::setConfigFileName(std::string filename) {
	configFileName_ = filename;
}
<commit_msg>Also give through other database options, next to just hostname and port.<commit_after>/**
 * Copyright (c) Sjors Gielen, 2010
 * See LICENSE for license.
 */

#include "dazeus.h"
#include "database.h"
#include "network.h"
#include "config.h"
#include "plugincomm.h"
#include <cassert>
#include <sstream>

// #define DEBUG
#define VERBOSE

/**
 * @brief Constructor.
 *
 * @param configFileName optional path to the configuration file. Configuration
 * will not be loaded automatically, use loadConfig() for that.
 */
DaZeus::DaZeus( std::string configFileName )
: config_( 0 )
, configFileName_( configFileName )
, plugins_( 0 )
, database_( 0 )
{
}

/**
 * @brief Destructor.
 */
DaZeus::~DaZeus()
{
  std::vector<Network*>::iterator it;
  for(it = networks_.begin(); it != networks_.end(); ++it)
  {
    (*it)->disconnectFromNetwork( Network::ShutdownReason );
    delete *it;
  }
  networks_.clear();

  delete plugins_;
}

/**
 * @brief Add additional sockets to the list defined in the configuration file.
 *
 * The application will listen on the given additional sockets.
 */
void DaZeus::addAdditionalSockets(const std::vector<std::string> &sockets)
{
	config_->addAdditionalSockets(sockets);
}

/**
 * @brief Connect to all networks marked "autoconnect".
 *
 * Warning: This method is usually called outside the event loop, just after
 * initialisation.
 */
void DaZeus::autoConnect()
{
#ifdef DEBUG
  fprintf(stderr, "DaZeus::autoConnect() called: looking for networks to connect to\n");
#endif
  std::vector<Network*>::iterator it;
  for(it = networks_.begin(); it != networks_.end(); ++it)
  {
    Network *n = *it;
    if( n->autoConnectEnabled() )
    {
#ifdef DEBUG
      // TODO: toString
      fprintf(stderr, "Connecting to %p (autoconnect is enabled)\n", n);
#endif
      n->connectToNetwork();
    }
#ifdef DEBUG
    else
    {
      // TODO: toString
      fprintf(stderr, "Not connecting to %p, autoconnect is disabled.\n", n);
    }
#endif
  }
}

std::string DaZeus::configFileName() const {
	return configFileName_;
}

/**
 * @brief Returns whether the configuration is loaded.
 */
bool DaZeus::configLoaded() const
{
  return config_ != 0;
}

/**
 * @brief Start connecting to the database.
 *
 * Does nothing if already connected.
 */
bool DaZeus::connectDatabase()
{
  const DatabaseConfig *dbc = config_->databaseConfig();
  if(dbc == 0) {
    fprintf(stderr, "Database configuration is absent, cannot continue.\n");
    return false;
  }
  database_ = new Database(dbc->hostname, dbc->port, dbc->database, dbc->username, dbc->password);

  if( !database_->open() )
  {
    fprintf(stderr, "Could not connect to database: %s\n", database_->lastError().c_str());
    return false;
  }

  return true;
}

/**
 * @brief Return the database.
 */
Database *DaZeus::database() const
{
  return database_;
}

/**
 * @brief Initialises plugins from the configuration file.
 */
bool DaZeus::initPlugins()
{
  assert(plugins_ != 0);
  plugins_->init();

  return true;
}

/**
 * @brief (Re-)loads configuration from the configuration file.
 *
 * If loading failed, this method returns false.
 * Note: this method is automatically called when setConfigFileName is called,
 * and by the constructor.
 */
bool DaZeus::loadConfig()
{
  assert( configFileName_.length() != 0 );

  if( config_ == 0 )
    config_ = new Config();

  if( !config_ )
    return false;

  config_->reset();
  config_->loadFromFile( configFileName_ );

  const std::vector<NetworkConfig*> &networks = config_->networks();

  if(!connectDatabase()) {
    delete config_;
    config_ = 0;
    return false;
  }

  if(plugins_)
    delete plugins_;
  plugins_ = new PluginComm( database_, config_, this );

  std::vector<NetworkConfig*>::const_iterator it;
  for(it = networks.begin(); it != networks.end(); ++it)
  {
    Network *net = new Network( *it, plugins_ );
    if( net == 0 ) {
      delete config_;
      config_ = 0;
      return false;
    }

    networks_.push_back( net );
  }

  // Pretty number of initialisations viewer -- and also an immediate database
  // check.
  std::stringstream numInitsStr;
  numInitsStr << database_->property("dazeus.numinits");
  int numInits;
  numInitsStr >> numInits;
  if(!numInitsStr)
    numInits = 0;
  ++numInits;
  numInitsStr.str(""); numInitsStr.clear();
  numInitsStr << numInits;
  database_->setProperty("dazeus.numinits", numInitsStr.str());
  const char *suffix = "th";
  if(numInits%100 == 11 ) ;
  else if(numInits%100 == 12) ;
  else if(numInits%100 == 13) ;
  else if(numInits%10 == 1) suffix = "st";
  else if(numInits%10 == 2) suffix = "nd";
  else if(numInits%10 == 3) suffix = "rd";
  printf("Initialising DaZeus for the %d%s time!\n", numInits, suffix);
  return true;
}

void DaZeus::run()
{
	while(1) {
		plugins_->run();
	}
}

void DaZeus::setConfigFileName(std::string filename) {
	configFileName_ = filename;
}
<|endoftext|>


<commit_before>/************************************************************************************\
This source file is part of the KS(X) audio library                                  *
For latest info, see http://code.google.com/p/libxal/                                *
**************************************************************************************
Copyright (c) 2010 Kresimir Spes (kreso@cateia.com), Boris Mikic                     *
*                                                                                *
* This program is free software; you can redistribute it and/or modify it under      *
* the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php   *
\************************************************************************************/
#ifndef __APPLE__
#include <AL/al.h>
#else
#include <OpenAL/al.h>
#endif

#include <hltypes/harray.h>
#include <hltypes/hfile.h>
#include <hltypes/hstring.h>
#include <hltypes/util.h>

#include "Endianess.h"
#include "SoundBuffer.h"
#include "Source.h"
#include "AudioManager.h"

namespace xal
{
/******* CONSTRUCT / DESTRUCT ******************************************/

	SoundBuffer::SoundBuffer(chstr fileName, chstr category, chstr prefix) : Sound(),
		duration(0.0f), sources(harray<xal::Source*>()), loaded(false)
	{
		this->fileName = hstr(fileName);
		this->virtualFileName = this->fileName;
		this->name = prefix + hstr(fileName).replace("\\", "/").rsplit("/").pop_back().rsplit(".", 1).pop_front();
		this->category = xal::mgr->getCategoryByName(category);
	}

	SoundBuffer::~SoundBuffer()
	{
		xal::mgr->logMessage("destroying sound " + this->name);
	}

	void SoundBuffer::destroySources()
	{
		Source* source;
		while (this->sources.size() > 0)
		{
			source = this->sources.front();
			source->unlock();
			source->stopSoft();
			source->unbind();
		}
	}

/******* METHODS *******************************************************/

	bool SoundBuffer::load()
	{
		bool result = false;
		if (this->isLink())
		{
			this->virtualFileName = this->_findLinkedFile();
		}
		if (!xal::mgr->isEnabled())
		{
			result = this->isOgg();
		}
		if (this->isOgg())
		{
			result = this->_loadOgg();
		}
		if (result)
		{
			this->loaded = result;
		}
		return result;
	}

	hstr SoundBuffer::_findLinkedFile()
	{
		char buffer[1024];
		if (!hfile::exists(this->fileName))
		{
			return this->fileName;
		}
		harray<hstr> newFolders = hfile::hread(this->fileName).split("/");
		harray<hstr> folders = this->fileName.split("/");
		folders.pop_back();
		foreach (hstr, it, newFolders)
		{
			if ((*it) != "..")
			{
				folders += (*it);
			}
			else
			{
				folders.pop_back();
			}
		}
		return folders.join("/");
	}

	void SoundBuffer::bindSource(Source* source)
	{
#ifdef _DEBUG
		xal::mgr->logMessage(hsprintf("binding source %d to sound %s", source->getSourceId(), this->virtualFileName.c_str()));
#endif
		this->sources += source;
	}

	void SoundBuffer::unbindSource(Source* source)
	{
#ifdef _DEBUG
		xal::mgr->logMessage(hsprintf("unbinding source from sound %s", this->virtualFileName.c_str()));
#endif
		this->sources -= source;
	}

	void SoundBuffer::lock()
	{
		if (this->sources.size() > 0)
		{
			this->sources[0]->lock();
		}
	}

	void SoundBuffer::unlock()
	{
		if (this->sources.size() > 0)
		{
			this->sources[0]->unlock();
		}
	}

	bool SoundBuffer::isLocked()
	{
		if (this->sources.size() == 0)
		{
			return false;
		}
		return this->sources[0]->isLocked();
	}

	float SoundBuffer::getSampleOffset()
	{
		if (this->getBuffer() == 0 || this->sources.size() == 0)
		{
			return 0;
		}
		return this->sources[0]->getSampleOffset();
	}

	void SoundBuffer::setGain(float gain)
	{
		if (this->getBuffer() != 0 && this->sources.size() > 0)
		{
			this->sources[0]->setGain(gain);
		}
	}

	float SoundBuffer::getGain()
	{
		if (this->getBuffer() == 0 || this->sources.size() == 0)
		{
			return 1;
		}
		return this->sources[0]->getGain();
	}

	bool SoundBuffer::isPlaying()
	{
		return (this->sources.size() > 0 && this->sources[0]->isPlaying());
	}

	bool SoundBuffer::isPaused()
	{
		return (this->sources.size() > 0 && this->sources[0]->isPaused());
	}

	bool SoundBuffer::isFading()
	{
		return (this->sources.size() > 0 && this->sources[0]->isFading());
	}

	bool SoundBuffer::isFadingIn()
	{
		return (this->sources.size() > 0 && this->sources[0]->isFadingIn());
	}

	bool SoundBuffer::isFadingOut()
	{
		return (this->sources.size() > 0 && this->sources[0]->isFadingOut());
	}

	bool SoundBuffer::isLooping()
	{
		return (this->sources.size() > 0 && this->sources[0]->isLooping());
	}

	bool SoundBuffer::isLink()
	{
		return this->fileName.ends_with(".xln");
	}

	bool SoundBuffer::isOgg()
	{
		return this->virtualFileName.ends_with(".ogg");
	}

/******* PLAY CONTROLS *************************************************/

	Sound* SoundBuffer::play(float fadeTime, bool looping)
	{
		if (!this->loaded)
		{
			this->load();
		}
		if (this->getBuffer() == 0)
		{
			return NULL;
		}
		Source* source = NULL;
		if (this->sources.size() == 0 || this->sources[0]->isPlaying() && !this->sources[0]->isFading())
		{
			unsigned int sourceId = xal::mgr->allocateSourceId();
			if (sourceId == 0)
			{
				return NULL;
			}
#ifdef _DEBUG
			xal::mgr->logMessage(hsprintf("allocated new source %d", sourceId));
#endif
			source = xal::mgr->createSource(this, sourceId);
			this->bindSource(source);
		}
		else
		{
#ifdef _DEBUG
			xal::mgr->logMessage("using allocated source");
#endif
			source = this->sources[0];
		}
		source->play(fadeTime, looping);
		return source;
	}

	void SoundBuffer::stop(float fadeTime)
	{
		if (this->getBuffer() != 0 && this->sources.size() > 0)
		{
			this->sources[0]->stop(fadeTime);
		}
	}

	void SoundBuffer::_stopSoft(float fadeTime)
	{
		if (this->getBuffer() != 0 && this->sources.size() > 0)
		{
			this->sources[0]->stopSoft(fadeTime);
		}
	}

	void SoundBuffer::stopAll(float fadeTime)
	{
		if (this->getBuffer() != 0)
		{
#ifdef _DEBUG
			xal::mgr->logMessage("stop all");
#endif
			foreach (Source*, it, this->sources)
			{
				(*it)->stop(fadeTime);
			}
		}
	}

	void SoundBuffer::pause(float fadeTime)
	{
		if (this->getBuffer() != 0 && this->sources.size() > 0)
		{
			this->sources[0]->pause(fadeTime);
		}
	}

}
<commit_msg>- removed unnecessary local variable declaration<commit_after>/************************************************************************************\
This source file is part of the KS(X) audio library                                  *
For latest info, see http://code.google.com/p/libxal/                                *
**************************************************************************************
Copyright (c) 2010 Kresimir Spes (kreso@cateia.com), Boris Mikic                     *
*                                                                                *
* This program is free software; you can redistribute it and/or modify it under      *
* the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php   *
\************************************************************************************/
#ifndef __APPLE__
#include <AL/al.h>
#else
#include <OpenAL/al.h>
#endif

#include <hltypes/harray.h>
#include <hltypes/hfile.h>
#include <hltypes/hstring.h>
#include <hltypes/util.h>

#include "Endianess.h"
#include "SoundBuffer.h"
#include "Source.h"
#include "AudioManager.h"

namespace xal
{
/******* CONSTRUCT / DESTRUCT ******************************************/

	SoundBuffer::SoundBuffer(chstr fileName, chstr category, chstr prefix) : Sound(),
		duration(0.0f), sources(harray<xal::Source*>()), loaded(false)
	{
		this->fileName = hstr(fileName);
		this->virtualFileName = this->fileName;
		this->name = prefix + hstr(fileName).replace("\\", "/").rsplit("/").pop_back().rsplit(".", 1).pop_front();
		this->category = xal::mgr->getCategoryByName(category);
	}

	SoundBuffer::~SoundBuffer()
	{
		xal::mgr->logMessage("destroying sound " + this->name);
	}

	void SoundBuffer::destroySources()
	{
		Source* source;
		while (this->sources.size() > 0)
		{
			source = this->sources.front();
			source->unlock();
			source->stopSoft();
			source->unbind();
		}
	}

/******* METHODS *******************************************************/

	bool SoundBuffer::load()
	{
		bool result = false;
		if (this->isLink())
		{
			this->virtualFileName = this->_findLinkedFile();
		}
		if (!xal::mgr->isEnabled())
		{
			result = this->isOgg();
		}
		if (this->isOgg())
		{
			result = this->_loadOgg();
		}
		if (result)
		{
			this->loaded = result;
		}
		return result;
	}

	hstr SoundBuffer::_findLinkedFile()
	{
		if (!hfile::exists(this->fileName))
		{
			return this->fileName;
		}
		harray<hstr> newFolders = hfile::hread(this->fileName).split("/");
		harray<hstr> folders = this->fileName.split("/");
		folders.pop_back();
		foreach (hstr, it, newFolders)
		{
			if ((*it) != "..")
			{
				folders += (*it);
			}
			else
			{
				folders.pop_back();
			}
		}
		return folders.join("/");
	}

	void SoundBuffer::bindSource(Source* source)
	{
#ifdef _DEBUG
		xal::mgr->logMessage(hsprintf("binding source %d to sound %s", source->getSourceId(), this->virtualFileName.c_str()));
#endif
		this->sources += source;
	}

	void SoundBuffer::unbindSource(Source* source)
	{
#ifdef _DEBUG
		xal::mgr->logMessage(hsprintf("unbinding source from sound %s", this->virtualFileName.c_str()));
#endif
		this->sources -= source;
	}

	void SoundBuffer::lock()
	{
		if (this->sources.size() > 0)
		{
			this->sources[0]->lock();
		}
	}

	void SoundBuffer::unlock()
	{
		if (this->sources.size() > 0)
		{
			this->sources[0]->unlock();
		}
	}

	bool SoundBuffer::isLocked()
	{
		if (this->sources.size() == 0)
		{
			return false;
		}
		return this->sources[0]->isLocked();
	}

	float SoundBuffer::getSampleOffset()
	{
		if (this->getBuffer() == 0 || this->sources.size() == 0)
		{
			return 0;
		}
		return this->sources[0]->getSampleOffset();
	}

	void SoundBuffer::setGain(float gain)
	{
		if (this->getBuffer() != 0 && this->sources.size() > 0)
		{
			this->sources[0]->setGain(gain);
		}
	}

	float SoundBuffer::getGain()
	{
		if (this->getBuffer() == 0 || this->sources.size() == 0)
		{
			return 1;
		}
		return this->sources[0]->getGain();
	}

	bool SoundBuffer::isPlaying()
	{
		return (this->sources.size() > 0 && this->sources[0]->isPlaying());
	}

	bool SoundBuffer::isPaused()
	{
		return (this->sources.size() > 0 && this->sources[0]->isPaused());
	}

	bool SoundBuffer::isFading()
	{
		return (this->sources.size() > 0 && this->sources[0]->isFading());
	}

	bool SoundBuffer::isFadingIn()
	{
		return (this->sources.size() > 0 && this->sources[0]->isFadingIn());
	}

	bool SoundBuffer::isFadingOut()
	{
		return (this->sources.size() > 0 && this->sources[0]->isFadingOut());
	}

	bool SoundBuffer::isLooping()
	{
		return (this->sources.size() > 0 && this->sources[0]->isLooping());
	}

	bool SoundBuffer::isLink()
	{
		return this->fileName.ends_with(".xln");
	}

	bool SoundBuffer::isOgg()
	{
		return this->virtualFileName.ends_with(".ogg");
	}

/******* PLAY CONTROLS *************************************************/

	Sound* SoundBuffer::play(float fadeTime, bool looping)
	{
		if (!this->loaded)
		{
			this->load();
		}
		if (this->getBuffer() == 0)
		{
			return NULL;
		}
		Source* source = NULL;
		if (this->sources.size() == 0 || this->sources[0]->isPlaying() && !this->sources[0]->isFading())
		{
			unsigned int sourceId = xal::mgr->allocateSourceId();
			if (sourceId == 0)
			{
				return NULL;
			}
#ifdef _DEBUG
			xal::mgr->logMessage(hsprintf("allocated new source %d", sourceId));
#endif
			source = xal::mgr->createSource(this, sourceId);
			this->bindSource(source);
		}
		else
		{
#ifdef _DEBUG
			xal::mgr->logMessage("using allocated source");
#endif
			source = this->sources[0];
		}
		source->play(fadeTime, looping);
		return source;
	}

	void SoundBuffer::stop(float fadeTime)
	{
		if (this->getBuffer() != 0 && this->sources.size() > 0)
		{
			this->sources[0]->stop(fadeTime);
		}
	}

	void SoundBuffer::_stopSoft(float fadeTime)
	{
		if (this->getBuffer() != 0 && this->sources.size() > 0)
		{
			this->sources[0]->stopSoft(fadeTime);
		}
	}

	void SoundBuffer::stopAll(float fadeTime)
	{
		if (this->getBuffer() != 0)
		{
#ifdef _DEBUG
			xal::mgr->logMessage("stop all");
#endif
			foreach (Source*, it, this->sources)
			{
				(*it)->stop(fadeTime);
			}
		}
	}

	void SoundBuffer::pause(float fadeTime)
	{
		if (this->getBuffer() != 0 && this->sources.size() > 0)
		{
			this->sources[0]->pause(fadeTime);
		}
	}

}
<|endoftext|>


<commit_before>#ifndef GUARD_MIOPEN_DRIVER_HPP
#define GUARD_MIOPEN_DRIVER_HPP

#include <cstdio>
#include <vector>
#include <cstdlib>
#include <miopen.h>
#include "InputFlags.hpp"
#include <algorithm>
#include <float.h>
#include <memory>
#include <numeric>

#if MIOPEN_BACKEND_OPENCL

#if defined(__APPLE__) || defined(__MACOSX)
#include <OpenCL/cl.h>
#else
#include <CL/cl.h>
#endif

#elif MIOPEN_BACKEND_HIP
#include <hip/hip_runtime_api.h>

#define printf(...) fprintf(stdout, __VA_ARGS__)

#endif

#define UNPACK_VEC4(v) (v[0]), (v[1]), (v[2]), (v[3])

struct GPUMem {

#if MIOPEN_BACKEND_OPENCL
	GPUMem() {};
	GPUMem(cl_context &ctx, size_t psz, size_t pdata_sz) : sz(psz), data_sz(pdata_sz) {	buf = clCreateBuffer(ctx, CL_MEM_READ_WRITE, data_sz*sz, NULL, NULL); }

	int ToGPU(cl_command_queue &q, void *p) { return clEnqueueWriteBuffer(q, buf, CL_TRUE, 0, data_sz*sz, p, 0, NULL, NULL); }
	int FromGPU(cl_command_queue &q, void *p) { return clEnqueueReadBuffer(q, buf, CL_TRUE, 0, data_sz*sz, p, 0, NULL, NULL); }

	cl_mem GetMem() { return buf; }
	size_t GetSize() { return sz*data_sz; }

	~GPUMem() { clReleaseMemObject(buf); }

	cl_mem buf;
	size_t sz;
	size_t data_sz;

#elif MIOPEN_BACKEND_HIP

	GPUMem() {};
	GPUMem(uint32_t ctx, size_t psz, size_t pdata_sz) : _ctx(ctx), sz(psz), data_sz(pdata_sz) {	hipMalloc((void**)&buf, data_sz*sz); }

	int ToGPU(hipStream_t q, void *p) { _q = q; return (int)hipMemcpy(buf, p, data_sz*sz, hipMemcpyHostToDevice); }
	int FromGPU(hipStream_t q, void *p) { _q = q; return (int)hipMemcpy(p, buf, data_sz*sz, hipMemcpyDeviceToHost); }

	void* GetMem() { return buf; }
	size_t GetSize() { return sz*data_sz; }

	~GPUMem() { hipFree(buf); }
	hipStream_t _q; // Place holder for opencl context
	uint32_t _ctx;
	void* buf;
	size_t sz;
	size_t data_sz;
#endif
};

[[gnu::noreturn]] void Usage() {
	printf("Usage: ./driver *base_arg* *other_args*\n");
	printf("Supported Base Arguments: conv, pool, lrn, activ, softmax, gemm\n");
	exit(0);
}

std::string ParseBaseArg(int argc, char *argv[]) {
	if(argc < 2) {
		printf("Invalid Number of Input Arguments\n");
		Usage();
	}

	std::string arg = argv[1];

	if(arg != "conv" && arg != "pool" && arg != "lrn" && arg != "activ" && arg != "softmax" && arg != "gemm") {
		printf("Invalid Base Input Argument\n");
		Usage();
	}
	else if(arg == "-h" || arg == "--help" || arg == "-?")
		Usage();
	else
		return arg;

	return 0;
}

class Driver
{
	public:
	Driver() {
#if MIOPEN_BACKEND_OPENCL
		miopenCreate(&handle);
#elif MIOPEN_BACKEND_HIP
        hipStream_t s;
        hipStreamCreate(&s);
        miopenCreateWithStream(&handle,s);
#endif

		miopenGetStream(handle, &q);
	}

	miopenHandle_t GetHandle() { return handle; }
#if MIOPEN_BACKEND_OPENCL
	cl_command_queue& GetStream() { return q; }
#elif MIOPEN_BACKEND_HIP
	hipStream_t& GetStream() { return q; }
#endif
	virtual ~Driver() {
		miopenDestroy(handle);
	}

	// TODO: add timing APIs
	virtual int AddCmdLineArgs() = 0;
	virtual int ParseCmdLineArgs(int argc, char *argv[]) = 0;
	virtual InputFlags & GetInputFlags() = 0;
	virtual int GetandSetData() = 0;
	virtual int AllocateBuffersAndCopy() = 0;
	virtual int RunForwardGPU() = 0;
	virtual int VerifyForward() = 0;
	virtual int RunBackwardGPU() = 0;
	virtual int VerifyBackward() = 0;

	protected:

	miopenHandle_t handle;
#if MIOPEN_BACKEND_OPENCL
	cl_command_queue q;
#elif MIOPEN_BACKEND_HIP
	hipStream_t q;
#endif
};

#endif // GUARD_MIOPEN_DRIVER_HPP
<commit_msg>fixed warnings for hip-backend<commit_after>#ifndef GUARD_MIOPEN_DRIVER_HPP
#define GUARD_MIOPEN_DRIVER_HPP

#include <cstdio>
#include <vector>
#include <cstdlib>
#include <miopen.h>
#include "InputFlags.hpp"
#include <algorithm>
#include <float.h>
#include <memory>
#include <numeric>

#if MIOPEN_BACKEND_OPENCL

#if defined(__APPLE__) || defined(__MACOSX)
#include <OpenCL/cl.h>
#else
#include <CL/cl.h>
#endif

#elif MIOPEN_BACKEND_HIP
#include <hip/hip_runtime_api.h>

#define printf(...) fprintf(stdout, __VA_ARGS__)

#endif

#define UNPACK_VEC4(v) (v[0]), (v[1]), (v[2]), (v[3])

struct GPUMem {

#if MIOPEN_BACKEND_OPENCL
	GPUMem() {};
	GPUMem(cl_context &ctx, size_t psz, size_t pdata_sz) : sz(psz), data_sz(pdata_sz) {	buf = clCreateBuffer(ctx, CL_MEM_READ_WRITE, data_sz*sz, NULL, NULL); }

	int ToGPU(cl_command_queue &q, void *p) { return clEnqueueWriteBuffer(q, buf, CL_TRUE, 0, data_sz*sz, p, 0, NULL, NULL); }
	int FromGPU(cl_command_queue &q, void *p) { return clEnqueueReadBuffer(q, buf, CL_TRUE, 0, data_sz*sz, p, 0, NULL, NULL); }

	cl_mem GetMem() { return buf; }
	size_t GetSize() { return sz*data_sz; }

	~GPUMem() { clReleaseMemObject(buf); }

	cl_mem buf;
	size_t sz;
	size_t data_sz;

#elif MIOPEN_BACKEND_HIP

	GPUMem() {};
	GPUMem(uint32_t ctx, size_t psz, size_t pdata_sz) : _ctx(ctx), sz(psz), data_sz(pdata_sz) {	hipMalloc(static_cast<void**>(&buf), data_sz*sz); }

	int ToGPU(hipStream_t q, void *p) { _q = q; return static_cast<int>(hipMemcpy(buf, p, data_sz*sz, hipMemcpyHostToDevice)); }
	int FromGPU(hipStream_t q, void *p) { _q = q; return static_cast<int>(hipMemcpy(p, buf, data_sz*sz, hipMemcpyDeviceToHost)); }

	void* GetMem() { return buf; }
	size_t GetSize() { return sz*data_sz; }

	~GPUMem() { hipFree(buf); }
	hipStream_t _q; // Place holder for opencl context
	uint32_t _ctx;
	void* buf;
	size_t sz;
	size_t data_sz;
#endif
};

[[gnu::noreturn]] void Usage() {
	printf("Usage: ./driver *base_arg* *other_args*\n");
	printf("Supported Base Arguments: conv, pool, lrn, activ, softmax, gemm\n");
	exit(0);
}

std::string ParseBaseArg(int argc, char *argv[]) {
	if(argc < 2) {
		printf("Invalid Number of Input Arguments\n");
		Usage();
	}

	std::string arg = argv[1];

	if(arg != "conv" && arg != "pool" && arg != "lrn" && arg != "activ" && arg != "softmax" && arg != "gemm") {
		printf("Invalid Base Input Argument\n");
		Usage();
	}
	else if(arg == "-h" || arg == "--help" || arg == "-?")
		Usage();
	else
		return arg;

	return 0;
}

class Driver
{
	public:
	Driver() {
#if MIOPEN_BACKEND_OPENCL
		miopenCreate(&handle);
#elif MIOPEN_BACKEND_HIP
        hipStream_t s;
        hipStreamCreate(&s);
        miopenCreateWithStream(&handle,s);
#endif

		miopenGetStream(handle, &q);
	}

	miopenHandle_t GetHandle() { return handle; }
#if MIOPEN_BACKEND_OPENCL
	cl_command_queue& GetStream() { return q; }
#elif MIOPEN_BACKEND_HIP
	hipStream_t& GetStream() { return q; }
#endif
	virtual ~Driver() {
		miopenDestroy(handle);
	}

	// TODO: add timing APIs
	virtual int AddCmdLineArgs() = 0;
	virtual int ParseCmdLineArgs(int argc, char *argv[]) = 0;
	virtual InputFlags & GetInputFlags() = 0;
	virtual int GetandSetData() = 0;
	virtual int AllocateBuffersAndCopy() = 0;
	virtual int RunForwardGPU() = 0;
	virtual int VerifyForward() = 0;
	virtual int RunBackwardGPU() = 0;
	virtual int VerifyBackward() = 0;

	protected:

	miopenHandle_t handle;
#if MIOPEN_BACKEND_OPENCL
	cl_command_queue q;
#elif MIOPEN_BACKEND_HIP
	hipStream_t q;
#endif
};

#endif // GUARD_MIOPEN_DRIVER_HPP
<|endoftext|>