<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: view3d1.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 04:59: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"

#define ITEMID_COLOR            SID_ATTR_3D_LIGHTCOLOR

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

#ifndef _SVDITER_HXX
#include "svditer.hxx"
#endif

#ifndef _SVDPOOL_HXX
#include "svdpool.hxx"
#endif

#ifndef _SVDMODEL_HXX
#include "svdmodel.hxx"
#endif

#ifndef _XOUTX_HXX
#include "xoutx.hxx"
#endif

#ifndef _SVX_SVXIDS_HRC
#include "svxids.hrc"
#endif

#ifndef _XTABLE_HXX
#include "xtable.hxx"
#endif

#ifndef _FM_FMVIEW_HXX
#include "fmview.hxx"
#endif

#ifndef _SVX_DIALOGS_HRC
#include "dialogs.hrc"
#endif

#ifndef _SVX_DIALMGR_HXX
#include "dialmgr.hxx"
#endif

#ifndef _E3D_GLOBL3D_HXX
#include "globl3d.hxx"
#endif

#ifndef _E3D_OBJ3D_HXX
#include "obj3d.hxx"
#endif

#ifndef _E3D_POLYSC3D_HXX
#include "polysc3d.hxx"
#endif

#ifndef _SVXE3DITEM_HXX
#include "e3ditem.hxx"
#endif

#ifndef _SVX_COLRITEM_HXX
#include "colritem.hxx"
#endif

#ifndef _E3D_LATHE3D_HXX
#include "lathe3d.hxx"
#endif

#ifndef _E3D_SPHERE3D_HXX
#include "sphere3d.hxx"
#endif

#ifndef _E3D_EXTRUD3D_HXX
#include "extrud3d.hxx"
#endif

#ifndef _E3D_UNDO_HXX
#include "e3dundo.hxx"
#endif

#ifndef _E3D_VIEW3D_HXX
#include "view3d.hxx"
#endif

#ifndef _E3D_CUBE3D_HXX
#include "cube3d.hxx"
#endif

#ifndef _SVX_XFLCLIT_HXX
#include "xflclit.hxx"
#endif

#ifndef _SVDOGRP_HXX
#include "svdogrp.hxx"
#endif

/*************************************************************************
|*
|* Konvertierung in Polygone
|*
\************************************************************************/

void E3dView::ConvertMarkedToPolyObj(BOOL bLineToArea)
{
    SdrObject* pNewObj = NULL;

    if (GetMarkedObjectCount() == 1)
    {
        SdrObject* pObj = GetMarkedObjectByIndex(0);

        if (pObj && pObj->ISA(E3dPolyScene))
        {
            BOOL bBezier = FALSE;
            pNewObj = ((E3dPolyScene*) pObj)->ConvertToPolyObj(bBezier, bLineToArea);

            if (pNewObj)
            {
                BegUndo(SVX_RESSTR(RID_SVX_3D_UNDO_EXTRUDE));
                ReplaceObject(pObj, *GetPageViewPvNum(0), pNewObj);
                EndUndo();
            }
        }
    }

    if (!pNewObj)
    {
        SdrView::ConvertMarkedToPolyObj(bLineToArea);
    }
}

/*************************************************************************
|*
|* Get3DAttributes
|*
\************************************************************************/

void Imp_E3dView_InorderRun3DObjects(const SdrObject* pObj, sal_uInt32& rMask, BOOL bCorrectScenes)
{
    if(pObj->ISA(E3dLatheObj))
    {
        rMask |= 0x0001;
    }
    else if(pObj->ISA(E3dExtrudeObj))
    {
        rMask |= 0x0002;
    }
    else if(pObj->ISA(E3dSphereObj))
    {
        rMask |= 0x0004;
    }
    else if(pObj->ISA(E3dCubeObj))
    {
        rMask |= 0x0008;
    }
    else if(pObj->IsGroupObject())
    {
        if(bCorrectScenes && pObj->ISA(E3dScene))
            ((E3dScene*)pObj)->CorrectSceneDimensions();

        SdrObjList* pList = pObj->GetSubList();
        for(sal_uInt32 a(0); a < pList->GetObjCount(); a++)
            Imp_E3dView_InorderRun3DObjects(pList->GetObj(a), rMask, bCorrectScenes);
    }
}

SfxItemSet E3dView::Get3DAttributes(E3dScene* pInScene, BOOL /*bOnly3DAttr*/) const
{
    // ItemSet mit entspr. Bereich anlegen
    SfxItemSet aSet(
        pMod->GetItemPool(),
        SDRATTR_START,      SDRATTR_END,
        SID_ATTR_3D_INTERN, SID_ATTR_3D_INTERN,
        0, 0);

    sal_uInt32 nSelectedItems(0L);

    if(pInScene)
    {
        // special scene
        aSet.Put(pInScene->GetMergedItemSet());
    }
    else
    {
        // get attributes from all selected objects
        MergeAttrFromMarked(aSet, FALSE);

        // calc flags for SID_ATTR_3D_INTERN
        const SdrMarkList& rMarkList = GetMarkedObjectList();
        sal_uInt32 nMarkCnt(rMarkList.GetMarkCount());

        for(sal_uInt32 a(0); a < nMarkCnt; a++)
        {
            SdrObject* pObj = GetMarkedObjectByIndex(a);
            Imp_E3dView_InorderRun3DObjects(pObj, nSelectedItems, FALSE);
        }
    }

    // setze SID_ATTR_3D_INTERN auf den Status der selektierten Objekte
    aSet.Put(SfxUInt32Item(SID_ATTR_3D_INTERN, nSelectedItems));

    // DefaultValues pflegen
    if(!nSelectedItems  && !pInScene)
    {
        // Defaults holen und hinzufuegen
        SfxItemSet aDefaultSet(pMod->GetItemPool(), SDRATTR_3D_FIRST, SDRATTR_3D_LAST);
        GetAttributes(aDefaultSet);
        aSet.Put(aDefaultSet);

        // ... aber keine Linien fuer 3D
        aSet.Put(XLineStyleItem (XLINE_NONE));

        // #84061# new defaults for distance and focal length
        aSet.Put(Svx3DDistanceItem(100));
        aSet.Put(Svx3DFocalLengthItem(10000));
    }

    // ItemSet zurueckgeben
    return(aSet);
}

/*************************************************************************
|*
|* Set3DAttributes:
|*
\************************************************************************/

void E3dView::Set3DAttributes( const SfxItemSet& rAttr, E3dScene* pInScene, BOOL bReplaceAll)
{
    sal_uInt32 nSelectedItems(0L);

    if(pInScene)
    {
        //pInScene->SetItemSetAndBroadcast(rAttr, bReplaceAll);
        pInScene->SetMergedItemSetAndBroadcast(rAttr, bReplaceAll);
    }
    else
    {
        // set at selected objects
        SetAttrToMarked(rAttr, bReplaceAll);

        // Durchlauf mit Korrektur der veraenderten Szenen,
        // da die enthaltenen Objekte geometrisch veraendert sein koennen
        const SdrMarkList& rMarkList = GetMarkedObjectList();
        sal_uInt32 nMarkCnt(rMarkList.GetMarkCount());

        for(sal_uInt32 a(0); a < nMarkCnt; a++)
        {
            SdrObject* pObj = GetMarkedObjectByIndex(a);
            Imp_E3dView_InorderRun3DObjects(pObj, nSelectedItems, TRUE);
        }

    }

    // DefaultValues pflegen
    if(!nSelectedItems && !pInScene)
    {
        // Defaults setzen
        SfxItemSet aDefaultSet(pMod->GetItemPool(), SDRATTR_3D_FIRST, SDRATTR_3D_LAST);
        aDefaultSet.Put(rAttr);
        SetAttributes(aDefaultSet);

    }
}

double E3dView::GetDefaultCamPosZ()
{
    return (double)((const SfxUInt32Item&)pMod->GetItemPool().GetDefaultItem(SDRATTR_3DSCENE_DISTANCE)).GetValue();
}

double E3dView::GetDefaultCamFocal()
{
    return (double)((const SfxUInt32Item&)pMod->GetItemPool().GetDefaultItem(SDRATTR_3DSCENE_FOCAL_LENGTH)).GetValue();
}

<commit_msg>INTEGRATION: CWS aw024 (1.6.344); FILE MERGED 2006/09/21 18:50:21 aw 1.6.344.6: RESYNC: (1.9-1.10); FILE MERGED 2006/07/04 12:40:10 aw 1.6.344.5: RESYNC: (1.7-1.8); FILE MERGED 2005/09/18 03:45:14 aw 1.6.344.4: RESYNC: (1.6-1.7); FILE MERGED 2005/05/26 11:27:57 aw 1.6.344.3: #i39531# 2005/05/19 12:31:15 aw 1.6.344.2: #i39529# 2004/12/23 16:52:35 aw 1.6.344.1: #i39525<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: view3d1.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: ihi $ $Date: 2006-11-14 13:22:46 $
 *
 *  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"

#define ITEMID_COLOR            SID_ATTR_3D_LIGHTCOLOR

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

#ifndef _SVDITER_HXX
#include "svditer.hxx"
#endif

#ifndef _SVDPOOL_HXX
#include "svdpool.hxx"
#endif

#ifndef _SVDMODEL_HXX
#include "svdmodel.hxx"
#endif

#ifndef _XOUTX_HXX
#include "xoutx.hxx"
#endif

#ifndef _SVX_SVXIDS_HRC
#include "svxids.hrc"
#endif

#ifndef _XTABLE_HXX
#include "xtable.hxx"
#endif

#ifndef _FM_FMVIEW_HXX
#include "fmview.hxx"
#endif

#ifndef _SVX_DIALOGS_HRC
#include "dialogs.hrc"
#endif

#ifndef _SVX_DIALMGR_HXX
#include "dialmgr.hxx"
#endif

#ifndef _E3D_GLOBL3D_HXX
#include "globl3d.hxx"
#endif

#ifndef _E3D_OBJ3D_HXX
#include "obj3d.hxx"
#endif

#ifndef _E3D_POLYSC3D_HXX
#include "polysc3d.hxx"
#endif

#ifndef _SVXE3DITEM_HXX
#include "e3ditem.hxx"
#endif

#ifndef _SVX_COLRITEM_HXX
#include "colritem.hxx"
#endif

#ifndef _E3D_LATHE3D_HXX
#include "lathe3d.hxx"
#endif

#ifndef _E3D_SPHERE3D_HXX
#include "sphere3d.hxx"
#endif

#ifndef _E3D_EXTRUD3D_HXX
#include "extrud3d.hxx"
#endif

#ifndef _E3D_UNDO_HXX
#include "e3dundo.hxx"
#endif

#ifndef _E3D_VIEW3D_HXX
#include "view3d.hxx"
#endif

#ifndef _E3D_CUBE3D_HXX
#include "cube3d.hxx"
#endif

#ifndef _SVX_XFLCLIT_HXX
#include "xflclit.hxx"
#endif

#ifndef _SVDOGRP_HXX
#include "svdogrp.hxx"
#endif

/*************************************************************************
|*
|* Konvertierung in Polygone
|*
\************************************************************************/

void E3dView::ConvertMarkedToPolyObj(BOOL bLineToArea)
{
    SdrObject* pNewObj = NULL;

    if (GetMarkedObjectCount() == 1)
    {
        SdrObject* pObj = GetMarkedObjectByIndex(0);

        if (pObj && pObj->ISA(E3dPolyScene))
        {
            BOOL bBezier = FALSE;
            pNewObj = ((E3dPolyScene*) pObj)->ConvertToPolyObj(bBezier, bLineToArea);

            if (pNewObj)
            {
                BegUndo(SVX_RESSTR(RID_SVX_3D_UNDO_EXTRUDE));
                ReplaceObjectAtView(pObj, *GetSdrPageView(), pNewObj);
                EndUndo();
            }
        }
    }

    if (!pNewObj)
    {
        SdrView::ConvertMarkedToPolyObj(bLineToArea);
    }
}

/*************************************************************************
|*
|* Get3DAttributes
|*
\************************************************************************/

void Imp_E3dView_InorderRun3DObjects(const SdrObject* pObj, sal_uInt32& rMask, BOOL bCorrectScenes)
{
    if(pObj->ISA(E3dLatheObj))
    {
        rMask |= 0x0001;
    }
    else if(pObj->ISA(E3dExtrudeObj))
    {
        rMask |= 0x0002;
    }
    else if(pObj->ISA(E3dSphereObj))
    {
        rMask |= 0x0004;
    }
    else if(pObj->ISA(E3dCubeObj))
    {
        rMask |= 0x0008;
    }
    else if(pObj->IsGroupObject())
    {
        if(bCorrectScenes && pObj->ISA(E3dScene))
            ((E3dScene*)pObj)->CorrectSceneDimensions();

        SdrObjList* pList = pObj->GetSubList();
        for(sal_uInt32 a(0); a < pList->GetObjCount(); a++)
            Imp_E3dView_InorderRun3DObjects(pList->GetObj(a), rMask, bCorrectScenes);
    }
}

SfxItemSet E3dView::Get3DAttributes(E3dScene* pInScene, BOOL /*bOnly3DAttr*/) const
{
    // ItemSet mit entspr. Bereich anlegen
    SfxItemSet aSet(
        pMod->GetItemPool(),
        SDRATTR_START,      SDRATTR_END,
        SID_ATTR_3D_INTERN, SID_ATTR_3D_INTERN,
        0, 0);

    sal_uInt32 nSelectedItems(0L);

    if(pInScene)
    {
        // special scene
        aSet.Put(pInScene->GetMergedItemSet());
    }
    else
    {
        // get attributes from all selected objects
        MergeAttrFromMarked(aSet, FALSE);

        // calc flags for SID_ATTR_3D_INTERN
        const SdrMarkList& rMarkList = GetMarkedObjectList();
        sal_uInt32 nMarkCnt(rMarkList.GetMarkCount());

        for(sal_uInt32 a(0); a < nMarkCnt; a++)
        {
            SdrObject* pObj = GetMarkedObjectByIndex(a);
            Imp_E3dView_InorderRun3DObjects(pObj, nSelectedItems, FALSE);
        }
    }

    // setze SID_ATTR_3D_INTERN auf den Status der selektierten Objekte
    aSet.Put(SfxUInt32Item(SID_ATTR_3D_INTERN, nSelectedItems));

    // DefaultValues pflegen
    if(!nSelectedItems  && !pInScene)
    {
        // Defaults holen und hinzufuegen
        SfxItemSet aDefaultSet(pMod->GetItemPool(), SDRATTR_3D_FIRST, SDRATTR_3D_LAST);
        GetAttributes(aDefaultSet);
        aSet.Put(aDefaultSet);

        // ... aber keine Linien fuer 3D
        aSet.Put(XLineStyleItem (XLINE_NONE));

        // #84061# new defaults for distance and focal length
        aSet.Put(Svx3DDistanceItem(100));
        aSet.Put(Svx3DFocalLengthItem(10000));
    }

    // ItemSet zurueckgeben
    return(aSet);
}

/*************************************************************************
|*
|* Set3DAttributes:
|*
\************************************************************************/

void E3dView::Set3DAttributes( const SfxItemSet& rAttr, E3dScene* pInScene, BOOL bReplaceAll)
{
    sal_uInt32 nSelectedItems(0L);

    if(pInScene)
    {
        //pInScene->SetItemSetAndBroadcast(rAttr, bReplaceAll);
        pInScene->SetMergedItemSetAndBroadcast(rAttr, bReplaceAll);
    }
    else
    {
        // set at selected objects
        SetAttrToMarked(rAttr, bReplaceAll);

        // Durchlauf mit Korrektur der veraenderten Szenen,
        // da die enthaltenen Objekte geometrisch veraendert sein koennen
        const SdrMarkList& rMarkList = GetMarkedObjectList();
        sal_uInt32 nMarkCnt(rMarkList.GetMarkCount());

        for(sal_uInt32 a(0); a < nMarkCnt; a++)
        {
            SdrObject* pObj = GetMarkedObjectByIndex(a);
            Imp_E3dView_InorderRun3DObjects(pObj, nSelectedItems, TRUE);
        }

    }

    // DefaultValues pflegen
    if(!nSelectedItems && !pInScene)
    {
        // Defaults setzen
        SfxItemSet aDefaultSet(pMod->GetItemPool(), SDRATTR_3D_FIRST, SDRATTR_3D_LAST);
        aDefaultSet.Put(rAttr);
        SetAttributes(aDefaultSet);

    }
}

double E3dView::GetDefaultCamPosZ()
{
    return (double)((const SfxUInt32Item&)pMod->GetItemPool().GetDefaultItem(SDRATTR_3DSCENE_DISTANCE)).GetValue();
}

double E3dView::GetDefaultCamFocal()
{
    return (double)((const SfxUInt32Item&)pMod->GetItemPool().GetDefaultItem(SDRATTR_3DSCENE_FOCAL_LENGTH)).GetValue();
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: unobtabl.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 01:03:02 $
 *
 *  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 _SFXITEMPOOL_HXX
#include <svtools/itempool.hxx>
#endif

#ifndef _SV_CVTGRF_HXX
#include <vcl/cvtgrf.hxx>
#endif

#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SVX_XIT_HXX
#include <xit.hxx>
#endif
#ifndef SVX_LIGHT
#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif
#endif

#ifndef _SVX_UNONAMEITEMTABLE_HXX_
#include "UnoNameItemTable.hxx"
#endif

#include "xbtmpit.hxx"
#include "svdmodel.hxx"
#include "xflhtit.hxx"
#include "unoapi.hxx"
#include "impgrf.hxx"
#include "unomid.hxx"
#include "unoprnms.hxx"
#include "unofill.hxx"

using namespace ::com::sun::star;
using namespace ::rtl;
using namespace ::cppu;

class SvxUnoBitmapTable : public SvxUnoNameItemTable
{
public:
    SvxUnoBitmapTable( SdrModel* pModel ) throw();
    virtual ~SvxUnoBitmapTable() throw();

    virtual NameOrIndex* createItem() const throw();
    virtual bool isValid( const NameOrIndex* pItem ) const;

    // XServiceInfo
    virtual OUString SAL_CALL getImplementationName(  ) throw( uno::RuntimeException );
    virtual uno::Sequence<  OUString > SAL_CALL getSupportedServiceNames(  ) throw( uno::RuntimeException);

    // XElementAccess
    virtual uno::Type SAL_CALL getElementType(  ) throw( uno::RuntimeException);
};

SvxUnoBitmapTable::SvxUnoBitmapTable( SdrModel* pModel ) throw()
: SvxUnoNameItemTable( pModel, XATTR_FILLBITMAP, MID_GRAFURL )
{
}

SvxUnoBitmapTable::~SvxUnoBitmapTable() throw()
{
}

bool SvxUnoBitmapTable::isValid( const NameOrIndex* pItem ) const
{
    if( SvxUnoNameItemTable::isValid( pItem ) )
    {
        const XFillBitmapItem* pBitmapItem = dynamic_cast< const XFillBitmapItem* >( pItem );
        if( pBitmapItem )
        {
            const GraphicObject& rGraphic = pBitmapItem->GetValue().GetGraphicObject();
            return rGraphic.GetSizeBytes() > 0;
        }
    }

    return false;
}

OUString SAL_CALL SvxUnoBitmapTable::getImplementationName() throw( uno::RuntimeException )
{
    return OUString( RTL_CONSTASCII_USTRINGPARAM("SvxUnoBitmapTable") );
}

uno::Sequence< OUString > SAL_CALL SvxUnoBitmapTable::getSupportedServiceNames(  )
    throw( uno::RuntimeException )
{
    uno::Sequence< OUString > aSNS( 1 );
    aSNS.getArray()[0] = OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.BitmapTable" ));
    return aSNS;
}

NameOrIndex* SvxUnoBitmapTable::createItem() const throw()
{
    return new XFillBitmapItem();
}

// XElementAccess
uno::Type SAL_CALL SvxUnoBitmapTable::getElementType(  )
    throw( uno::RuntimeException )
{
    return ::getCppuType( (const ::rtl::OUString*)0 );
}

/**
 * Create a bitmaptable
 */
uno::Reference< uno::XInterface > SAL_CALL SvxUnoBitmapTable_createInstance( SdrModel* pModel )
{
    return *new SvxUnoBitmapTable(pModel);
}

#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _UNOTOOLS_LOCALFILEHELPER_HXX
#include <unotools/localfilehelper.hxx>
#endif

/** returns a GraphicObject for this URL */
GraphicObject CreateGraphicObjectFromURL( const ::rtl::OUString &rURL ) throw()
{
    const String aURL( rURL ), aPrefix( RTL_CONSTASCII_STRINGPARAM(UNO_NAME_GRAPHOBJ_URLPREFIX) );

    if( aURL.Search( aPrefix ) == 0 )
    {
        // graphic manager url
        ByteString aUniqueID( String(rURL.copy( sizeof( UNO_NAME_GRAPHOBJ_URLPREFIX ) - 1 )), RTL_TEXTENCODING_UTF8 );
        return GraphicObject( aUniqueID );
    }
    else
    {
        Graphic     aGraphic;

#ifndef SVX_LIGHT
        if ( aURL.Len() )
        {
            SfxMedium   aMedium( aURL, STREAM_READ, TRUE );
            SvStream*   pStream = aMedium.GetInStream();

            if( pStream )
                GraphicConverter::Import( *pStream, aGraphic );
        }
#else
        String aSystemPath( rURL );
        utl::LocalFileHelper::ConvertURLToSystemPath( aSystemPath, aSystemPath );
        SvFileStream aFile( aSystemPath, STREAM_READ );
        GraphicConverter::Import( aFile, aGraphic );
#endif

        return GraphicObject( aGraphic );
    }
}
<commit_msg>INTEGRATION: CWS warnings01 (1.15.222); FILE MERGED 2006/04/19 15:12:13 cl 1.15.222.1: fixing BitmapItem access<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: unobtabl.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 16:54:38 $
 *
 *  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 _SFXITEMPOOL_HXX
#include <svtools/itempool.hxx>
#endif

#ifndef _SV_CVTGRF_HXX
#include <vcl/cvtgrf.hxx>
#endif

#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SVX_XIT_HXX
#include <xit.hxx>
#endif
#ifndef SVX_LIGHT
#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif
#endif

#ifndef _SVX_UNONAMEITEMTABLE_HXX_
#include "UnoNameItemTable.hxx"
#endif

#include "xbtmpit.hxx"
#include "svdmodel.hxx"
#include "xflhtit.hxx"
#include "unoapi.hxx"
#include "impgrf.hxx"
#include "unomid.hxx"
#include "unoprnms.hxx"
#include "unofill.hxx"

using namespace ::com::sun::star;
using namespace ::rtl;
using namespace ::cppu;

class SvxUnoBitmapTable : public SvxUnoNameItemTable
{
public:
    SvxUnoBitmapTable( SdrModel* pModel ) throw();
    virtual ~SvxUnoBitmapTable() throw();

    virtual NameOrIndex* createItem() const throw();
    virtual bool isValid( const NameOrIndex* pItem ) const;

    // XServiceInfo
    virtual OUString SAL_CALL getImplementationName(  ) throw( uno::RuntimeException );
    virtual uno::Sequence<  OUString > SAL_CALL getSupportedServiceNames(  ) throw( uno::RuntimeException);

    // XElementAccess
    virtual uno::Type SAL_CALL getElementType(  ) throw( uno::RuntimeException);
};

SvxUnoBitmapTable::SvxUnoBitmapTable( SdrModel* pModel ) throw()
: SvxUnoNameItemTable( pModel, XATTR_FILLBITMAP, MID_GRAFURL )
{
}

SvxUnoBitmapTable::~SvxUnoBitmapTable() throw()
{
}

bool SvxUnoBitmapTable::isValid( const NameOrIndex* pItem ) const
{
    if( SvxUnoNameItemTable::isValid( pItem ) )
    {
        const XFillBitmapItem* pBitmapItem = dynamic_cast< const XFillBitmapItem* >( pItem );
        if( pBitmapItem )
        {
            const GraphicObject& rGraphic = pBitmapItem->GetBitmapValue().GetGraphicObject();
            return rGraphic.GetSizeBytes() > 0;
        }
    }

    return false;
}

OUString SAL_CALL SvxUnoBitmapTable::getImplementationName() throw( uno::RuntimeException )
{
    return OUString( RTL_CONSTASCII_USTRINGPARAM("SvxUnoBitmapTable") );
}

uno::Sequence< OUString > SAL_CALL SvxUnoBitmapTable::getSupportedServiceNames(  )
    throw( uno::RuntimeException )
{
    uno::Sequence< OUString > aSNS( 1 );
    aSNS.getArray()[0] = OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.BitmapTable" ));
    return aSNS;
}

NameOrIndex* SvxUnoBitmapTable::createItem() const throw()
{
    return new XFillBitmapItem();
}

// XElementAccess
uno::Type SAL_CALL SvxUnoBitmapTable::getElementType(  )
    throw( uno::RuntimeException )
{
    return ::getCppuType( (const ::rtl::OUString*)0 );
}

/**
 * Create a bitmaptable
 */
uno::Reference< uno::XInterface > SAL_CALL SvxUnoBitmapTable_createInstance( SdrModel* pModel )
{
    return *new SvxUnoBitmapTable(pModel);
}

#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _UNOTOOLS_LOCALFILEHELPER_HXX
#include <unotools/localfilehelper.hxx>
#endif

/** returns a GraphicObject for this URL */
GraphicObject CreateGraphicObjectFromURL( const ::rtl::OUString &rURL ) throw()
{
    const String aURL( rURL ), aPrefix( RTL_CONSTASCII_STRINGPARAM(UNO_NAME_GRAPHOBJ_URLPREFIX) );

    if( aURL.Search( aPrefix ) == 0 )
    {
        // graphic manager url
        ByteString aUniqueID( String(rURL.copy( sizeof( UNO_NAME_GRAPHOBJ_URLPREFIX ) - 1 )), RTL_TEXTENCODING_UTF8 );
        return GraphicObject( aUniqueID );
    }
    else
    {
        Graphic     aGraphic;

#ifndef SVX_LIGHT
        if ( aURL.Len() )
        {
            SfxMedium   aMedium( aURL, STREAM_READ, TRUE );
            SvStream*   pStream = aMedium.GetInStream();

            if( pStream )
                GraphicConverter::Import( *pStream, aGraphic );
        }
#else
        String aSystemPath( rURL );
        utl::LocalFileHelper::ConvertURLToSystemPath( aSystemPath, aSystemPath );
        SvFileStream aFile( aSystemPath, STREAM_READ );
        GraphicConverter::Import( aFile, aGraphic );
#endif

        return GraphicObject( aGraphic );
    }
}
<|endoftext|>


<commit_before>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "ActionWarehouse.h"
#include "ActionFactory.h"
#include "Parser.h"
#include "MooseObjectAction.h"
#include "InputFileFormatter.h"
#include "InputParameters.h"
#include "MooseMesh.h"
#include "AddVariableAction.h"
#include "AddAuxVariableAction.h"
#include "XTermConstants.h"
#include "InfixIterator.h"
#include "FEProblem.h"

ActionWarehouse::ActionWarehouse(MooseApp & app, Syntax & syntax, ActionFactory & factory)
  : ConsoleStreamInterface(app),
    _app(app),
    _syntax(syntax),
    _action_factory(factory),
    _generator_valid(false),
    _show_actions(false),
    _show_parser(false)
{
}

ActionWarehouse::~ActionWarehouse() {}

void
ActionWarehouse::build()
{
  _ordered_names = _syntax.getSortedTask();
  for (const auto & name : _ordered_names)
    buildBuildableActions(name);
}

void
ActionWarehouse::clear()
{
  for (auto & ptr : _all_ptrs)
    ptr.reset();

  _action_blocks.clear();
  _generator_valid = false;

  // Due to the way ActionWarehouse is cleaned up (see MooseApp's
  // destructor) we must guarantee that ActionWarehouse::clear()
  // releases all the resources which have to be released _before_ the
  // _comm object owned by the MooseApp is destroyed.
  _problem.reset();
  _displaced_mesh.reset();
  _mesh.reset();
}

void
ActionWarehouse::addActionBlock(std::shared_ptr<Action> action)
{
  /**
   * Note: This routine uses the XTerm colors directly which is not advised for general purpose
   * output coloring.
   * Most users should prefer using Problem::colorText() which respects the "color_output" option
   * for terminals
   * that do not support coloring.  Since this routine is intended for debugging only and runs
   * before several
   * objects exist in the system, we are just using the constants directly.
   */

  std::string registered_identifier =
      action->parameters().get<std::string>("registered_identifier");
  std::set<std::string> tasks;

  if (_show_parser)
    Moose::err << COLOR_DEFAULT << "Parsing Syntax:        " << COLOR_GREEN << action->name()
               << '\n'
               << COLOR_DEFAULT << "Building Action:       " << COLOR_DEFAULT << action->type()
               << '\n'
               << COLOR_DEFAULT << "Registered Identifier: " << COLOR_GREEN << registered_identifier
               << '\n'
               << COLOR_DEFAULT << "Specific Task:         " << COLOR_CYAN
               << action->specificTaskName() << '\n';

  /**
   * We need to see if the current Action satisfies multiple tasks. There are a few cases to
   * consider:
   *
   * 1. The current Action is registered with multiple syntax blocks. In this case we can only use
   * the
   *    current instance to satisfy the specific task listed for this syntax block.  We can detect
   * this
   *    case by inspecting whether it has a "specific task name" set in the Action instance.
   *
   * 2. This action does not have a valid "registered identifier" set in the Action instance. This
   * means
   *    that this Action was not built by the Parser.  It was most likely created through a
   * Meta-Action.
   *    In this case, the ActionFactory itself would have already set the task it found from the
   * build
   *    info used to construct the Action.
   *
   * 3. The current Action is registered with only a single syntax block. In this case we can simply
   *    re-use the current instance to act and satisfy _all_ registered tasks. This is the normal
   *    case where we have a Parser-built Action that does not have a specific task name to satisfy.
   *    We will use the Action "type" to retrieve the list of tasks that this Action may satisfy.
   */
  if (action->specificTaskName() != "") // Case 1
    tasks.insert(action->specificTaskName());
  else if (registered_identifier == "") // Case 2
  {
    std::set<std::string> local_tasks = action->getAllTasks();
    mooseAssert(local_tasks.size() == 1, "More than one task inside of the " << action->name());
    tasks.insert(*local_tasks.begin());
  }
  else // Case 3
    tasks = _action_factory.getTasksByAction(action->type());

  // TODO: Now we need to weed out the double registrations!
  for (const auto & task : tasks)
  {
    // Some error checking
    if (!_syntax.hasTask(task))
      mooseError("A(n) ", task, " is not a registered task");

    // Make sure that the ObjectAction task and Action task are consistent
    // otherwise that means that is action was built by the wrong type
    std::shared_ptr<MooseObjectAction> moa = std::dynamic_pointer_cast<MooseObjectAction>(action);
    if (moa.get())
    {
      const InputParameters & mparams = moa->getObjectParams();

      if (mparams.have_parameter<std::string>("_moose_base"))
      {
        const std::string & base = mparams.get<std::string>("_moose_base");

        if (!_syntax.verifyMooseObjectTask(base, task))
          mooseError("Task ", task, " is not registered to build ", base, " derived objects");
      }
      else
        mooseError("Unable to locate registered base parameter for ", moa->getMooseObjectType());
    }

    // Add the current task to current action
    action->appendTask(task);

    if (_show_parser)
      Moose::err << COLOR_YELLOW << "Adding Action:         " << COLOR_DEFAULT << action->type()
                 << " (" << COLOR_YELLOW << task << COLOR_DEFAULT << ")\n";

    // Add it to the warehouse
    _all_ptrs.push_back(action);
    _action_blocks[task].push_back(action.get());
  }

  if (_show_parser)
    Moose::err << std::endl;
}

ActionIterator
ActionWarehouse::actionBlocksWithActionBegin(const std::string & task)
{
  return _action_blocks[task].begin();
}

ActionIterator
ActionWarehouse::actionBlocksWithActionEnd(const std::string & task)
{
  return _action_blocks[task].end();
}

const std::list<Action *> &
ActionWarehouse::getActionListByName(const std::string & task) const
{
  const auto it = _action_blocks.find(task);
  if (it == _action_blocks.end())
    mooseError("The task ", task, " does not exist.");

  return it->second;
}

bool
ActionWarehouse::hasActions(const std::string & task) const
{
  return _action_blocks.find(task) != _action_blocks.end();
}

void
ActionWarehouse::buildBuildableActions(const std::string & task)
{
  if (_syntax.isActionRequired(task) && _action_blocks[task].empty())
  {
    bool ret_value = false;
    std::pair<std::multimap<std::string, std::string>::const_iterator,
              std::multimap<std::string, std::string>::const_iterator>
        range = _action_factory.getActionsByTask(task);
    for (std::multimap<std::string, std::string>::const_iterator it = range.first;
         it != range.second;
         ++it)
    {
      InputParameters params = _action_factory.getValidParams(it->second);
      params.set<ActionWarehouse *>("awh") = this;

      if (params.areAllRequiredParamsValid())
      {
        params.set<std::string>("registered_identifier") = "(AutoBuilt)";
        params.set<std::string>("task") = task;
        addActionBlock(_action_factory.create(it->second, "", params));
        ret_value = true;
      }
    }

    if (!ret_value)
      _unsatisfied_dependencies.insert(task);
  }
}

void
ActionWarehouse::checkUnsatisfiedActions() const
{
  std::stringstream oss;
  bool empty = true;

  for (const auto & udep : _unsatisfied_dependencies)
  {
    if (_action_blocks.find(udep) == _action_blocks.end())
    {
      if (empty)
        empty = false;
      else
        oss << " ";
      oss << udep;
    }
  }

  if (!empty)
    mooseError(
        std::string(
            "The following unsatisfied actions where found while setting up the MOOSE problem:\n") +
        oss.str() + "\n");
}

void
ActionWarehouse::printActionDependencySets() const
{
  /**
   * Note: This routine uses the XTerm colors directly which is not advised for general purpose
   * output coloring.
   * Most users should prefer using Problem::colorText() which respects the "color_output" option
   * for terminals
   * that do not support coloring.  Since this routine is intended for debugging only and runs
   * before several
   * objects exist in the system, we are just using the constants directly.
   */
  std::ostringstream oss;

  const auto & ordered_names = _syntax.getSortedTaskSet();
  for (const auto & task_set : ordered_names)
  {
    oss << "[DBG][ACT] (" << COLOR_YELLOW;
    std::copy(task_set.begin(), task_set.end(), infix_ostream_iterator<std::string>(oss, ", "));
    oss << COLOR_DEFAULT << ")\n";

    for (const auto & task : task_set)
    {
      if (_action_blocks.find(task) == _action_blocks.end())
        continue;

      for (const auto & act : _action_blocks.at(task))
      {
        // The Syntax of the Action if it exists
        if (act->name() != "")
          oss << "[DBG][ACT]\t" << COLOR_GREEN << act->name() << COLOR_DEFAULT << '\n';

        // The task sets
        oss << "[DBG][ACT]\t" << act->type();
        const std::set<std::string> tasks = act->getAllTasks();
        if (tasks.size() > 1)
        {
          oss << " (";
          // Break the current Action's tasks into 2 sets, those intersecting with current set and
          // then the difference.
          std::set<std::string> intersection, difference;
          std::set_intersection(tasks.begin(),
                                tasks.end(),
                                task_set.begin(),
                                task_set.end(),
                                std::inserter(intersection, intersection.end()));
          std::set_difference(tasks.begin(),
                              tasks.end(),
                              intersection.begin(),
                              intersection.end(),
                              std::inserter(difference, difference.end()));

          oss << COLOR_CYAN;
          std::copy(intersection.begin(),
                    intersection.end(),
                    infix_ostream_iterator<std::string>(oss, ", "));
          oss << COLOR_MAGENTA << (difference.empty() ? "" : ", ");
          std::copy(
              difference.begin(), difference.end(), infix_ostream_iterator<std::string>(oss, ", "));
          oss << COLOR_DEFAULT << ")";
        }
        oss << '\n';
      }
    }
  }

  if (_show_actions)
    _console << oss.str() << std::endl;
}

void
ActionWarehouse::executeAllActions()
{
  if (_show_actions)
  {
    _console << "[DBG][ACT] Action Dependency Sets:\n";
    printActionDependencySets();

    _console << "\n[DBG][ACT] Executing actions:" << std::endl;
  }

  for (const auto & task : _ordered_names)
    executeActionsWithAction(task);
}

void
ActionWarehouse::executeActionsWithAction(const std::string & task)
{
  // Set the current task name
  _current_task = task;

  for (ActionIterator act_iter = actionBlocksWithActionBegin(task);
       act_iter != actionBlocksWithActionEnd(task);
       ++act_iter)
  {
    if (_show_actions)
    {
      _console << "[DBG][ACT] "
               << "TASK (" << COLOR_YELLOW << std::setw(24) << task << COLOR_DEFAULT << ") "
               << "TYPE (" << COLOR_YELLOW << std::setw(32) << (*act_iter)->type() << COLOR_DEFAULT
               << ") "
               << "NAME (" << COLOR_YELLOW << std::setw(16) << (*act_iter)->name() << COLOR_DEFAULT
               << ") \n";

      (*act_iter)->act();
    }
    else
      (*act_iter)->act();
  }
}

void
ActionWarehouse::printInputFile(std::ostream & out)
{
  InputFileFormatter tree(false);

  std::map<std::string, std::vector<Action *>>::iterator iter;

  std::vector<Action *> ordered_actions;
  for (const auto & block : _action_blocks)
    for (const auto & act : block.second)
      ordered_actions.push_back(act);

  for (const auto & act : ordered_actions)
  {
    std::string name;
    if (act->isParamValid("parser_syntax"))
      name = act->getParam<std::string>("parser_syntax");
    else
      name = act->name();
    const std::set<std::string> & tasks = act->getAllTasks();
    mooseAssert(!tasks.empty(), "Task list is empty");

    bool is_parent;
    if (_syntax.isAssociated(name, &is_parent) != "")
    {
      InputParameters params = act->parameters();

      // TODO: Do we need to insert more nodes for each task?
      tree.insertNode(name, *tasks.begin(), true, &params);

      MooseObjectAction * moose_object_action = dynamic_cast<MooseObjectAction *>(act);
      if (moose_object_action)
      {
        InputParameters obj_params = moose_object_action->getObjectParams();
        tree.insertNode(name, *tasks.begin(), false, &obj_params);
      }
    }
  }

  out << tree.print("");
}

std::shared_ptr<FEProblem>
ActionWarehouse::problem()
{
  mooseDeprecated(
      "ActionWarehouse::problem() is deprecated, please use ActionWarehouse::problemBase() \n");
  return std::dynamic_pointer_cast<FEProblem>(_problem);
}
<commit_msg>Make sure set is used for set_intersection (#9390)<commit_after>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "ActionWarehouse.h"
#include "ActionFactory.h"
#include "Parser.h"
#include "MooseObjectAction.h"
#include "InputFileFormatter.h"
#include "InputParameters.h"
#include "MooseMesh.h"
#include "AddVariableAction.h"
#include "AddAuxVariableAction.h"
#include "XTermConstants.h"
#include "InfixIterator.h"
#include "FEProblem.h"

ActionWarehouse::ActionWarehouse(MooseApp & app, Syntax & syntax, ActionFactory & factory)
  : ConsoleStreamInterface(app),
    _app(app),
    _syntax(syntax),
    _action_factory(factory),
    _generator_valid(false),
    _show_actions(false),
    _show_parser(false)
{
}

ActionWarehouse::~ActionWarehouse() {}

void
ActionWarehouse::build()
{
  _ordered_names = _syntax.getSortedTask();
  for (const auto & name : _ordered_names)
    buildBuildableActions(name);
}

void
ActionWarehouse::clear()
{
  for (auto & ptr : _all_ptrs)
    ptr.reset();

  _action_blocks.clear();
  _generator_valid = false;

  // Due to the way ActionWarehouse is cleaned up (see MooseApp's
  // destructor) we must guarantee that ActionWarehouse::clear()
  // releases all the resources which have to be released _before_ the
  // _comm object owned by the MooseApp is destroyed.
  _problem.reset();
  _displaced_mesh.reset();
  _mesh.reset();
}

void
ActionWarehouse::addActionBlock(std::shared_ptr<Action> action)
{
  /**
   * Note: This routine uses the XTerm colors directly which is not advised for general purpose
   * output coloring.
   * Most users should prefer using Problem::colorText() which respects the "color_output" option
   * for terminals
   * that do not support coloring.  Since this routine is intended for debugging only and runs
   * before several
   * objects exist in the system, we are just using the constants directly.
   */

  std::string registered_identifier =
      action->parameters().get<std::string>("registered_identifier");
  std::set<std::string> tasks;

  if (_show_parser)
    Moose::err << COLOR_DEFAULT << "Parsing Syntax:        " << COLOR_GREEN << action->name()
               << '\n'
               << COLOR_DEFAULT << "Building Action:       " << COLOR_DEFAULT << action->type()
               << '\n'
               << COLOR_DEFAULT << "Registered Identifier: " << COLOR_GREEN << registered_identifier
               << '\n'
               << COLOR_DEFAULT << "Specific Task:         " << COLOR_CYAN
               << action->specificTaskName() << '\n';

  /**
   * We need to see if the current Action satisfies multiple tasks. There are a few cases to
   * consider:
   *
   * 1. The current Action is registered with multiple syntax blocks. In this case we can only use
   * the
   *    current instance to satisfy the specific task listed for this syntax block.  We can detect
   * this
   *    case by inspecting whether it has a "specific task name" set in the Action instance.
   *
   * 2. This action does not have a valid "registered identifier" set in the Action instance. This
   * means
   *    that this Action was not built by the Parser.  It was most likely created through a
   * Meta-Action.
   *    In this case, the ActionFactory itself would have already set the task it found from the
   * build
   *    info used to construct the Action.
   *
   * 3. The current Action is registered with only a single syntax block. In this case we can simply
   *    re-use the current instance to act and satisfy _all_ registered tasks. This is the normal
   *    case where we have a Parser-built Action that does not have a specific task name to satisfy.
   *    We will use the Action "type" to retrieve the list of tasks that this Action may satisfy.
   */
  if (action->specificTaskName() != "") // Case 1
    tasks.insert(action->specificTaskName());
  else if (registered_identifier == "") // Case 2
  {
    std::set<std::string> local_tasks = action->getAllTasks();
    mooseAssert(local_tasks.size() == 1, "More than one task inside of the " << action->name());
    tasks.insert(*local_tasks.begin());
  }
  else // Case 3
    tasks = _action_factory.getTasksByAction(action->type());

  // TODO: Now we need to weed out the double registrations!
  for (const auto & task : tasks)
  {
    // Some error checking
    if (!_syntax.hasTask(task))
      mooseError("A(n) ", task, " is not a registered task");

    // Make sure that the ObjectAction task and Action task are consistent
    // otherwise that means that is action was built by the wrong type
    std::shared_ptr<MooseObjectAction> moa = std::dynamic_pointer_cast<MooseObjectAction>(action);
    if (moa.get())
    {
      const InputParameters & mparams = moa->getObjectParams();

      if (mparams.have_parameter<std::string>("_moose_base"))
      {
        const std::string & base = mparams.get<std::string>("_moose_base");

        if (!_syntax.verifyMooseObjectTask(base, task))
          mooseError("Task ", task, " is not registered to build ", base, " derived objects");
      }
      else
        mooseError("Unable to locate registered base parameter for ", moa->getMooseObjectType());
    }

    // Add the current task to current action
    action->appendTask(task);

    if (_show_parser)
      Moose::err << COLOR_YELLOW << "Adding Action:         " << COLOR_DEFAULT << action->type()
                 << " (" << COLOR_YELLOW << task << COLOR_DEFAULT << ")\n";

    // Add it to the warehouse
    _all_ptrs.push_back(action);
    _action_blocks[task].push_back(action.get());
  }

  if (_show_parser)
    Moose::err << std::endl;
}

ActionIterator
ActionWarehouse::actionBlocksWithActionBegin(const std::string & task)
{
  return _action_blocks[task].begin();
}

ActionIterator
ActionWarehouse::actionBlocksWithActionEnd(const std::string & task)
{
  return _action_blocks[task].end();
}

const std::list<Action *> &
ActionWarehouse::getActionListByName(const std::string & task) const
{
  const auto it = _action_blocks.find(task);
  if (it == _action_blocks.end())
    mooseError("The task ", task, " does not exist.");

  return it->second;
}

bool
ActionWarehouse::hasActions(const std::string & task) const
{
  return _action_blocks.find(task) != _action_blocks.end();
}

void
ActionWarehouse::buildBuildableActions(const std::string & task)
{
  if (_syntax.isActionRequired(task) && _action_blocks[task].empty())
  {
    bool ret_value = false;
    std::pair<std::multimap<std::string, std::string>::const_iterator,
              std::multimap<std::string, std::string>::const_iterator>
        range = _action_factory.getActionsByTask(task);
    for (std::multimap<std::string, std::string>::const_iterator it = range.first;
         it != range.second;
         ++it)
    {
      InputParameters params = _action_factory.getValidParams(it->second);
      params.set<ActionWarehouse *>("awh") = this;

      if (params.areAllRequiredParamsValid())
      {
        params.set<std::string>("registered_identifier") = "(AutoBuilt)";
        params.set<std::string>("task") = task;
        addActionBlock(_action_factory.create(it->second, "", params));
        ret_value = true;
      }
    }

    if (!ret_value)
      _unsatisfied_dependencies.insert(task);
  }
}

void
ActionWarehouse::checkUnsatisfiedActions() const
{
  std::stringstream oss;
  bool empty = true;

  for (const auto & udep : _unsatisfied_dependencies)
  {
    if (_action_blocks.find(udep) == _action_blocks.end())
    {
      if (empty)
        empty = false;
      else
        oss << " ";
      oss << udep;
    }
  }

  if (!empty)
    mooseError(
        std::string(
            "The following unsatisfied actions where found while setting up the MOOSE problem:\n") +
        oss.str() + "\n");
}

void
ActionWarehouse::printActionDependencySets() const
{
  /**
   * Note: This routine uses the XTerm colors directly which is not advised for general purpose
   * output coloring.
   * Most users should prefer using Problem::colorText() which respects the "color_output" option
   * for terminals
   * that do not support coloring.  Since this routine is intended for debugging only and runs
   * before several
   * objects exist in the system, we are just using the constants directly.
   */
  std::ostringstream oss;

  const auto & ordered_names = _syntax.getSortedTaskSet();
  for (const auto & task_vector : ordered_names)
  {
    oss << "[DBG][ACT] (" << COLOR_YELLOW;
    std::copy(
        task_vector.begin(), task_vector.end(), infix_ostream_iterator<std::string>(oss, ", "));
    oss << COLOR_DEFAULT << ")\n";

    std::set<std::string> task_set(task_vector.begin(), task_vector.end());
    for (const auto & task : task_set)
    {
      if (_action_blocks.find(task) == _action_blocks.end())
        continue;

      for (const auto & act : _action_blocks.at(task))
      {
        // The Syntax of the Action if it exists
        if (act->name() != "")
          oss << "[DBG][ACT]\t" << COLOR_GREEN << act->name() << COLOR_DEFAULT << '\n';

        // The task sets
        oss << "[DBG][ACT]\t" << act->type();
        const std::set<std::string> tasks = act->getAllTasks();
        if (tasks.size() > 1)
        {
          oss << " (";
          // Break the current Action's tasks into 2 sets, those intersecting with current set and
          // then the difference.
          std::set<std::string> intersection, difference;
          std::set_intersection(tasks.begin(),
                                tasks.end(),
                                task_set.begin(),
                                task_set.end(),
                                std::inserter(intersection, intersection.end()));
          std::set_difference(tasks.begin(),
                              tasks.end(),
                              intersection.begin(),
                              intersection.end(),
                              std::inserter(difference, difference.end()));

          oss << COLOR_CYAN;
          std::copy(intersection.begin(),
                    intersection.end(),
                    infix_ostream_iterator<std::string>(oss, ", "));
          oss << COLOR_MAGENTA << (difference.empty() ? "" : ", ");
          std::copy(
              difference.begin(), difference.end(), infix_ostream_iterator<std::string>(oss, ", "));
          oss << COLOR_DEFAULT << ")";
        }
        oss << '\n';
      }
    }
  }

  if (_show_actions)
    _console << oss.str() << std::endl;
}

void
ActionWarehouse::executeAllActions()
{
  if (_show_actions)
  {
    _console << "[DBG][ACT] Action Dependency Sets:\n";
    printActionDependencySets();

    _console << "\n[DBG][ACT] Executing actions:" << std::endl;
  }

  for (const auto & task : _ordered_names)
    executeActionsWithAction(task);
}

void
ActionWarehouse::executeActionsWithAction(const std::string & task)
{
  // Set the current task name
  _current_task = task;

  for (ActionIterator act_iter = actionBlocksWithActionBegin(task);
       act_iter != actionBlocksWithActionEnd(task);
       ++act_iter)
  {
    if (_show_actions)
    {
      _console << "[DBG][ACT] "
               << "TASK (" << COLOR_YELLOW << std::setw(24) << task << COLOR_DEFAULT << ") "
               << "TYPE (" << COLOR_YELLOW << std::setw(32) << (*act_iter)->type() << COLOR_DEFAULT
               << ") "
               << "NAME (" << COLOR_YELLOW << std::setw(16) << (*act_iter)->name() << COLOR_DEFAULT
               << ") \n";

      (*act_iter)->act();
    }
    else
      (*act_iter)->act();
  }
}

void
ActionWarehouse::printInputFile(std::ostream & out)
{
  InputFileFormatter tree(false);

  std::map<std::string, std::vector<Action *>>::iterator iter;

  std::vector<Action *> ordered_actions;
  for (const auto & block : _action_blocks)
    for (const auto & act : block.second)
      ordered_actions.push_back(act);

  for (const auto & act : ordered_actions)
  {
    std::string name;
    if (act->isParamValid("parser_syntax"))
      name = act->getParam<std::string>("parser_syntax");
    else
      name = act->name();
    const std::set<std::string> & tasks = act->getAllTasks();
    mooseAssert(!tasks.empty(), "Task list is empty");

    bool is_parent;
    if (_syntax.isAssociated(name, &is_parent) != "")
    {
      InputParameters params = act->parameters();

      // TODO: Do we need to insert more nodes for each task?
      tree.insertNode(name, *tasks.begin(), true, &params);

      MooseObjectAction * moose_object_action = dynamic_cast<MooseObjectAction *>(act);
      if (moose_object_action)
      {
        InputParameters obj_params = moose_object_action->getObjectParams();
        tree.insertNode(name, *tasks.begin(), false, &obj_params);
      }
    }
  }

  out << tree.print("");
}

std::shared_ptr<FEProblem>
ActionWarehouse::problem()
{
  mooseDeprecated(
      "ActionWarehouse::problem() is deprecated, please use ActionWarehouse::problemBase() \n");
  return std::dynamic_pointer_cast<FEProblem>(_problem);
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef BACK_END_H
#define BACK_END_H

#include <memory>
#include <string>

#include "StringPool.hpp"
#include "mtac/Program.hpp"

namespace eddic {

/**
 * \class BackEnd
 * \brief Represent the back end part of the compilation process.
 */
class BackEnd {
    public:
        /**
         * Generates the backend output from the MTAC Program.
         * \param mtacProgram The MTAC Program that has been generated by the front end.
         */
        virtual void generate(std::shared_ptr<mtac::Program> mtacProgram) = 0;

        /**
         * Set the string pool.
         * \param pool The string pool.
         */
        void set_string_pool(std::shared_ptr<StringPool> pool);

        /**
         * Returns the string pool.
         * \return The string pool.
         */
        std::shared_ptr<StringPool> get_string_pool();

    protected:
        std::shared_ptr<StringPool> pool; /**< The string pool that is used during this compilation */
};

}

#endif
<commit_msg>Use the same Doxygen convention everywhere<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef BACK_END_H
#define BACK_END_H

#include <memory>
#include <string>

#include "StringPool.hpp"
#include "mtac/Program.hpp"

namespace eddic {

/*!
 * \class BackEnd
 * \brief Represent the back end part of the compilation process.
 */
class BackEnd {
    public:
        /*!
         * Generates the backend output from the MTAC Program.
         * \param mtacProgram The MTAC Program that has been generated by the front end.
         */
        virtual void generate(std::shared_ptr<mtac::Program> mtacProgram) = 0;

        /*!
         * Set the string pool.
         * \param pool The string pool.
         */
        void set_string_pool(std::shared_ptr<StringPool> pool);

        /*!
         * Returns the string pool.
         * \return The string pool.
         */
        std::shared_ptr<StringPool> get_string_pool();

    protected:
        std::shared_ptr<StringPool> pool; /**< The string pool that is used during this compilation */
};

}

#endif
<|endoftext|>


<commit_before>/**
Copyright (c) 2016, Ubiquity Robotics
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 ubiquity_motor 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 HOLDER 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.
**/

#include <ubiquity_motor/motor_message.h>
// #include <ubiquity_motor/motor_message_registers.h>
#include <ros/console.h>
#include <numeric>

uint8_t const MotorMessage::valid_types[] = {TYPE_READ, TYPE_WRITE,
                                             TYPE_RESPONSE, TYPE_ERROR};

uint8_t const MotorMessage::valid_registers[] = {REG_STOP_START,
                                                 REG_BRAKE_STOP,
                                                 REG_CRUISE_STOP,
                                                 REG_LEFT_PWM,
                                                 REG_RIGHT_PWM,
                                                 REG_LEFT_SPEED_SET,
                                                 REG_RIGHT_SPEED_SET,
                                                 REG_LEFT_RAMP,
                                                 REG_RIGHT_RAMP,
                                                 REG_LEFT_ODOM,
                                                 REG_RIGHT_ODOM,
                                                 REG_DEADMAN,
                                                 REG_LEFT_CURRENT,
                                                 REG_RIGHT_CURRENT,
                                                 REG_ERROR_COUNT,
                                                 REG_5V_MAIN_ERROR,
                                                 REG_5V_AUX_ERROR,
                                                 REG_12V_MAIN_ERROR,
                                                 REG_12V_AUX_ERROR,
                                                 REG_5V_MAIN_OL,
                                                 REG_5V_AUX_OL,
                                                 REG_12V_MAIN_OL,
                                                 REG_12V_AUX_OL,
                                                 REG_LEFT_MOTOR_ERROR,
                                                 REG_RIGHT_MOTOR_ERROR,
                                                 REG_PARAM_P,
                                                 REG_PARAM_I,
                                                 REG_PARAM_D,
                                                 REG_PARAM_C,
                                                 REG_LED_1,
                                                 REG_LED_2,
                                                 REG_HARDWARE_VERSION,
                                                 REG_FIRMWARE_VERSION,
                                                 REG_BATTERY_VOLTAGE,
                                                 REG_5V_MAIN_CURRENT,
                                                 REG_12V_MAIN_CURRENT,
                                                 REG_5V_AUX_CURRENT,
                                                 REG_12V_AUX_CURRENT,
                                                 REG_LEFT_SPEED_MEASURED,
                                                 REG_RIGHT_SPEED_MEASURED,
                                                 REG_BOTH_SPEED_SET,
                                                 REG_MOVING_BUF_SIZE,
                                                 REG_BOTH_ODOM,
                                                 REG_LIMIT_REACHED,
                                                 REG_BOTH_ERROR,
                                                 DEBUG_50,
                                                 DEBUG_51,
                                                 DEBUG_52,
                                                 DEBUG_53,
                                                 DEBUG_54,
                                                 DEBUG_55,
                                                 DEBUG_56,
                                                 DEBUG_57,
                                                 DEBUG_58};

void MotorMessage::setType(MotorMessage::MessageTypes type) {
    if (verifyType(type)) {
        this->type = type;
    }
}

MotorMessage::MessageTypes MotorMessage::getType() const {
    return static_cast<MotorMessage::MessageTypes>(this->type);
}

void MotorMessage::setRegister(MotorMessage::Registers reg) {
    if (verifyRegister(reg)) {
        this->register_addr = reg;
    }
}

MotorMessage::Registers MotorMessage::getRegister() const {
    return static_cast<MotorMessage::Registers>(this->register_addr);
}

/*bool MotorMessage::isDelimeter(uint8_t data) {
  return (delimeter == data);
  }*/

void MotorMessage::setData(int32_t data) {
    // Spilt 32 bit data (system byte order) into 4 8bit elements in big endian
    // (network byte order)
    this->data[3] = (data >> 0) & 0xFF;
    this->data[2] = (data >> 8) & 0xFF;
    this->data[1] = (data >> 16) & 0xFF;
    this->data[0] = (data >> 24) & 0xFF;
}

int32_t MotorMessage::getData() const {
    // Take big endian (network byte order) elements and return 32 bit int
    return (this->data[0] << 24) | (this->data[1] << 16) |
           (this->data[2] << 8) | (this->data[3] << 0);
}

RawMotorMessage MotorMessage::serialize() const {
    RawMotorMessage out;
    out[0] = delimeter;
    out[1] = (protocol_version << 4) | type;
    out[2] = register_addr;
    out[3] = data[0];
    out[4] = data[1];
    out[5] = data[2];
    out[6] = data[3];
    out[7] = generateChecksum(out);
    return out;
}

int MotorMessage::deserialize(const RawMotorMessage &serialized) {
    if (serialized[0] == delimeter) {
        if ((serialized[1] & 0xF0) == (protocol_version << 4)) {
            if (generateChecksum(serialized) == serialized[7]) {
                if (verifyType(serialized[1] & 0x0F)) {
                    if (verifyRegister(serialized[2])) {
                        this->type = serialized[1] & 0x0F;
                        this->register_addr = serialized[2];
                        this->data[0] = serialized[3];
                        this->data[1] = serialized[4];
                        this->data[2] = serialized[5];
                        this->data[3] = serialized[6];
                        return 0;
                    } else
                        return 5;
                } else
                    return 4;
            } else
                return 3;
        } else
            return 2;
    } else
        return 1;

    // TODO use exceptions instead of cryptic error codes

    // ERROR codes returned:
    // 1 First char not delimiter
    // 2 wrong protocol version
    // 3 bad checksum
    // 4 bad type
    // 5 bad register
}

int MotorMessage::verifyType(uint8_t t) {
    // Return 1 good
    // Return 0 for bad
    for (size_t i = 0; i < sizeof(valid_types) / sizeof(valid_types[0]); ++i) {
        if (t == valid_types[i]) return 1;
    }
    return 0;
}

int MotorMessage::verifyRegister(uint8_t r) {
    // Return 1 good
    // Return 0 for bad
    for (size_t i = 0; i < sizeof(valid_registers) / sizeof(valid_registers[0]);
         ++i) {
        if (r == valid_registers[i]) return 1;
    }
    return 0;
}

uint8_t MotorMessage::generateChecksum(const std::vector<uint8_t> &data) {
    int sum = std::accumulate(data.begin() + 1, data.end() - 1, 0);

    if (sum > 0xFF) {
        int tmp;
        tmp = sum >> 8;
        tmp = tmp << 8;
        return 0xFF - (sum - tmp);
    } else {
        return 0xFF - sum;
    }
}

uint8_t MotorMessage::generateChecksum(const RawMotorMessage &data) {
    int sum = std::accumulate(data.begin() + 1, data.end() - 1, 0);

    if (sum > 0xFF) {
        int tmp;
        tmp = sum >> 8;
        tmp = tmp << 8;
        return 0xFF - (sum - tmp);
    } else {
        return 0xFF - sum;
    }
}
<commit_msg>Use std::copy in motor message<commit_after>/**
Copyright (c) 2016, Ubiquity Robotics
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 ubiquity_motor 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 HOLDER 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.
**/

#include <ubiquity_motor/motor_message.h>
// #include <ubiquity_motor/motor_message_registers.h>
#include <ros/console.h>
#include <numeric>

uint8_t const MotorMessage::valid_types[] = {TYPE_READ, TYPE_WRITE,
                                             TYPE_RESPONSE, TYPE_ERROR};

uint8_t const MotorMessage::valid_registers[] = {REG_STOP_START,
                                                 REG_BRAKE_STOP,
                                                 REG_CRUISE_STOP,
                                                 REG_LEFT_PWM,
                                                 REG_RIGHT_PWM,
                                                 REG_LEFT_SPEED_SET,
                                                 REG_RIGHT_SPEED_SET,
                                                 REG_LEFT_RAMP,
                                                 REG_RIGHT_RAMP,
                                                 REG_LEFT_ODOM,
                                                 REG_RIGHT_ODOM,
                                                 REG_DEADMAN,
                                                 REG_LEFT_CURRENT,
                                                 REG_RIGHT_CURRENT,
                                                 REG_ERROR_COUNT,
                                                 REG_5V_MAIN_ERROR,
                                                 REG_5V_AUX_ERROR,
                                                 REG_12V_MAIN_ERROR,
                                                 REG_12V_AUX_ERROR,
                                                 REG_5V_MAIN_OL,
                                                 REG_5V_AUX_OL,
                                                 REG_12V_MAIN_OL,
                                                 REG_12V_AUX_OL,
                                                 REG_LEFT_MOTOR_ERROR,
                                                 REG_RIGHT_MOTOR_ERROR,
                                                 REG_PARAM_P,
                                                 REG_PARAM_I,
                                                 REG_PARAM_D,
                                                 REG_PARAM_C,
                                                 REG_LED_1,
                                                 REG_LED_2,
                                                 REG_HARDWARE_VERSION,
                                                 REG_FIRMWARE_VERSION,
                                                 REG_BATTERY_VOLTAGE,
                                                 REG_5V_MAIN_CURRENT,
                                                 REG_12V_MAIN_CURRENT,
                                                 REG_5V_AUX_CURRENT,
                                                 REG_12V_AUX_CURRENT,
                                                 REG_LEFT_SPEED_MEASURED,
                                                 REG_RIGHT_SPEED_MEASURED,
                                                 REG_BOTH_SPEED_SET,
                                                 REG_MOVING_BUF_SIZE,
                                                 REG_BOTH_ODOM,
                                                 REG_LIMIT_REACHED,
                                                 REG_BOTH_ERROR,
                                                 DEBUG_50,
                                                 DEBUG_51,
                                                 DEBUG_52,
                                                 DEBUG_53,
                                                 DEBUG_54,
                                                 DEBUG_55,
                                                 DEBUG_56,
                                                 DEBUG_57,
                                                 DEBUG_58};

void MotorMessage::setType(MotorMessage::MessageTypes type) {
    if (verifyType(type)) {
        this->type = type;
    }
}

MotorMessage::MessageTypes MotorMessage::getType() const {
    return static_cast<MotorMessage::MessageTypes>(this->type);
}

void MotorMessage::setRegister(MotorMessage::Registers reg) {
    if (verifyRegister(reg)) {
        this->register_addr = reg;
    }
}

MotorMessage::Registers MotorMessage::getRegister() const {
    return static_cast<MotorMessage::Registers>(this->register_addr);
}

/*bool MotorMessage::isDelimeter(uint8_t data) {
  return (delimeter == data);
  }*/

void MotorMessage::setData(int32_t data) {
    // Spilt 32 bit data (system byte order) into 4 8bit elements in big endian
    // (network byte order)
    this->data[3] = (data >> 0) & 0xFF;
    this->data[2] = (data >> 8) & 0xFF;
    this->data[1] = (data >> 16) & 0xFF;
    this->data[0] = (data >> 24) & 0xFF;
}

int32_t MotorMessage::getData() const {
    // Take big endian (network byte order) elements and return 32 bit int
    return (this->data[0] << 24) | (this->data[1] << 16) |
           (this->data[2] << 8) | (this->data[3] << 0);
}

RawMotorMessage MotorMessage::serialize() const {
    RawMotorMessage out;
    out[0] = delimeter;
    out[1] = (protocol_version << 4) | type;
    out[2] = register_addr;
    std::copy(data.begin(), data.end(), out.begin() + 3);
    out[7] = generateChecksum(out);
    return out;
}

int MotorMessage::deserialize(const RawMotorMessage &serialized) {
    if (serialized[0] == delimeter) {
        if ((serialized[1] & 0xF0) == (protocol_version << 4)) {
            if (generateChecksum(serialized) == serialized[7]) {
                if (verifyType(serialized[1] & 0x0F)) {
                    if (verifyRegister(serialized[2])) {
                        this->type = serialized[1] & 0x0F;
                        this->register_addr = serialized[2];
                        std::copy(serialized.begin() + 3,
                                  serialized.begin() + 7, data.begin());
                        return 0;
                    } else
                        return 5;
                } else
                    return 4;
            } else
                return 3;
        } else
            return 2;
    } else
        return 1;

    // TODO use exceptions instead of cryptic error codes

    // ERROR codes returned:
    // 1 First char not delimiter
    // 2 wrong protocol version
    // 3 bad checksum
    // 4 bad type
    // 5 bad register
}

int MotorMessage::verifyType(uint8_t t) {
    // Return 1 good
    // Return 0 for bad
    for (size_t i = 0; i < sizeof(valid_types) / sizeof(valid_types[0]); ++i) {
        if (t == valid_types[i]) return 1;
    }
    return 0;
}

int MotorMessage::verifyRegister(uint8_t r) {
    // Return 1 good
    // Return 0 for bad
    for (size_t i = 0; i < sizeof(valid_registers) / sizeof(valid_registers[0]);
         ++i) {
        if (r == valid_registers[i]) return 1;
    }
    return 0;
}

uint8_t MotorMessage::generateChecksum(const std::vector<uint8_t> &data) {
    int sum = std::accumulate(data.begin() + 1, data.end() - 1, 0);

    if (sum > 0xFF) {
        int tmp;
        tmp = sum >> 8;
        tmp = tmp << 8;
        return 0xFF - (sum - tmp);
    } else {
        return 0xFF - sum;
    }
}

uint8_t MotorMessage::generateChecksum(const RawMotorMessage &data) {
    int sum = std::accumulate(data.begin() + 1, data.end() - 1, 0);

    if (sum > 0xFF) {
        int tmp;
        tmp = sum >> 8;
        tmp = tmp << 8;
        return 0xFF - (sum - tmp);
    } else {
        return 0xFF - sum;
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: docbasic.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2003-11-18 17:27:32 $
 *
 *  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 _HINTIDS_HXX
#include <hintids.hxx>
#endif

#ifndef _RTL_USTRING_HXX //autogen
#include <rtl/ustring.hxx>
#endif
#ifndef _IMAP_HXX //autogen
#include <svtools/imap.hxx>
#endif
#ifndef _GOODIES_IMAPOBJ_HXX
#include <svtools/imapobj.hxx>
#endif
#ifndef _SBXCLASS_HXX
#include <svtools/sbx.hxx>
#endif
#ifndef _SBXCORE_HXX
#include <svtools/sbxcore.hxx>
#endif
#ifndef __SBX_SBXVALUE
#include <svtools/sbxvar.hxx>
#endif
#ifndef _OFF_APP_HXX //autogen
#include <offmgr/app.hxx>
#endif

#ifndef _FRMFMT_HXX //autogen
#include <frmfmt.hxx>
#endif
#ifndef _FMTINFMT_HXX //autogen
#include <fmtinfmt.hxx>
#endif
#ifndef _FMTURL_HXX //autogen
#include <fmturl.hxx>
#endif
#ifndef _FRMATR_HXX
#include <frmatr.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _SWEVENT_HXX
#include <swevent.hxx>
#endif

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

Sequence<Any> *lcl_docbasic_convertArgs( SbxArray& rArgs )
{
    Sequence<Any> *pRet = 0;

#if 0
    switch( nEvent )
    {
    case SW_EVENT_FRM_KEYINPUT_ALPHA:
    case SW_EVENT_FRM_KEYINPUT_NOALPHA:
    case SW_EVENT_FRM_MOVE:
    case SW_EVENT_FRM_RESIZE:
    }
#endif

    USHORT nCount = rArgs.Count();
    if( nCount > 1 )
    {
        nCount--;
        pRet = new Sequence<Any>( nCount );
        Any *pUnoArgs = pRet->getArray();
        for( USHORT i=0; i<nCount; i++ )
        {
            SbxVariable *pVar = rArgs.Get( i+1 );
            switch( pVar->GetType() )
            {
            case SbxSTRING:
                pUnoArgs[i] <<= OUString( pVar->GetString() );
                break;
            case SbxCHAR:
                pUnoArgs[i] <<= (sal_Int16)pVar->GetChar() ;
                break;
            case SbxUSHORT:
                pUnoArgs[i] <<= (sal_Int16)pVar->GetUShort();
                break;
            case SbxLONG:
                pUnoArgs[i] <<= (sal_Int32)pVar->GetLong();
                break;
            default:
                pUnoArgs[i].setValue(0, ::getVoidCppuType());
                break;
            }
        }
    }

    return pRet;
}

BOOL SwDoc::ExecMacro( const SvxMacro& rMacro, String* pRet, SbxArray* pArgs )
{
    ErrCode eErr = 0;
    switch( rMacro.GetScriptType() )
    {
    case STARBASIC:
        {
            SbxBaseRef aRef;
            SbxValue* pRetValue = new SbxValue;
            aRef = pRetValue;
            eErr = pDocShell->CallBasic( rMacro.GetMacName(),
                                         rMacro.GetLibName(),
                                         0, pArgs, pRet ? pRetValue : 0 );

            if( pRet && SbxNULL <  pRetValue->GetType() &&
                        SbxVOID != pRetValue->GetType() )
                // gueltiger Wert, also setzen
                *pRet = pRetValue->GetString();
        }
        break;
    case JAVASCRIPT:
        // ignore JavaScript calls
        break;
    case EXTENDED_STYPE:
        {
            Sequence<Any> *pUnoArgs = 0;
            if( pArgs )
            {
                // better to rename the local function to lcl_translateBasic2Uno and
                // a much shorter routine can be found in sfx2/source/doc/objmisc.cxx
                pUnoArgs = lcl_docbasic_convertArgs( *pArgs );
            }

            if (!pUnoArgs)
            {
                pUnoArgs = new Sequence< Any > (0);
            }

            // TODO - return value is not handled
            Any aRet;
            Sequence< sal_Int16 > aOutArgsIndex;
            Sequence< Any > aOutArgs;

            OSL_TRACE( "SwDoc::ExecMacro URL is %s", ByteString( rMacro.GetMacName(),
                RTL_TEXTENCODING_UTF8).GetBuffer() );

            eErr = pDocShell->CallXScript(
                rMacro.GetMacName(), *pUnoArgs, aRet, aOutArgsIndex, aOutArgs);

            //*pRet = pRetValue->GetString();
            // use the AnyConverter to return a String if appropriate?

            // need to call something like lcl_translateUno2Basic
            // pArgs = lcl_translateUno2Basic( pUnoArgs );

            delete pUnoArgs;
            break;
        }
    }

    return 0 == eErr;
}

USHORT SwDoc::CallEvent( USHORT nEvent, const SwCallMouseEvent& rCallEvent,
                    BOOL bCheckPtr, SbxArray* pArgs, const Link* pCallBack )
{
    if( !pDocShell )        // ohne DocShell geht das nicht!
        return 0;

    USHORT nRet = 0;
    const SvxMacroTableDtor* pTbl = 0;
    switch( rCallEvent.eType )
    {
    case EVENT_OBJECT_INETATTR:
        if( bCheckPtr  )
        {
            const SfxPoolItem* pItem;
            USHORT n, nMaxItems = GetAttrPool().GetItemCount( RES_TXTATR_INETFMT );
            for( n = 0; n < nMaxItems; ++n )
                if( 0 != (pItem = GetAttrPool().GetItem( RES_TXTATR_INETFMT, n ) )
                    && rCallEvent.PTR.pINetAttr == pItem )
                {
                    bCheckPtr = FALSE;      // als Flag missbrauchen
                    break;
                }
        }
        if( !bCheckPtr )
            pTbl = rCallEvent.PTR.pINetAttr->GetMacroTbl();
        break;

    case EVENT_OBJECT_URLITEM:
    case EVENT_OBJECT_IMAGE:
        {
            const SwFrmFmtPtr pFmt = (SwFrmFmtPtr)rCallEvent.PTR.pFmt;
            if( bCheckPtr )
            {
                USHORT nPos = GetSpzFrmFmts()->GetPos( pFmt );
                if( USHRT_MAX != nPos )
                    bCheckPtr = FALSE;      // als Flag missbrauchen
            }
            if( !bCheckPtr )
                pTbl = &pFmt->GetMacro().GetMacroTable();
        }
        break;

    case EVENT_OBJECT_IMAGEMAP:
        {
            const IMapObject* pIMapObj = rCallEvent.PTR.IMAP.pIMapObj;
            if( bCheckPtr )
            {
                const SwFrmFmtPtr pFmt = (SwFrmFmtPtr)rCallEvent.PTR.IMAP.pFmt;
                USHORT nPos = GetSpzFrmFmts()->GetPos( pFmt );
                const ImageMap* pIMap;
                if( USHRT_MAX != nPos &&
                    0 != (pIMap = pFmt->GetURL().GetMap()) )
                {
                    for( nPos = pIMap->GetIMapObjectCount(); nPos; )
                        if( pIMapObj == pIMap->GetIMapObject( --nPos ))
                        {
                            bCheckPtr = FALSE;      // als Flag missbrauchen
                            break;
                        }
                }
            }
            if( !bCheckPtr )
                pTbl = &pIMapObj->GetMacroTable();
        }
        break;
    }

    if( pTbl )
    {
        nRet = 0x1;
        if( pTbl->IsKeyValid( nEvent ) )
        {
            const SvxMacro& rMacro = *pTbl->Get( nEvent );
            if( STARBASIC == rMacro.GetScriptType() )
            {
                nRet += 0 == pDocShell->CallBasic( rMacro.GetMacName(),
                                    rMacro.GetLibName(), 0, pArgs ) ? 1 : 0;
            }
            else if( EXTENDED_STYPE == rMacro.GetScriptType() )
            {
                Sequence<Any> *pUnoArgs = 0;

                if( pArgs )
                {
                    pUnoArgs = lcl_docbasic_convertArgs( *pArgs );
                }

                if (!pUnoArgs)
                {
                    pUnoArgs = new Sequence <Any> (0);
                }

                Any aRet;
                Sequence< sal_Int16 > aOutArgsIndex;
                Sequence< Any > aOutArgs;

                OSL_TRACE( "SwDoc::CallEvent URL is %s", ByteString(
                    rMacro.GetMacName(), RTL_TEXTENCODING_UTF8).GetBuffer() );

                nRet += 0 == pDocShell->CallXScript(
                    rMacro.GetMacName(), *pUnoArgs,aRet, aOutArgsIndex, aOutArgs);

                //*pRet = pRetValue->GetString();
                // use the AnyConverter to return a String if appropriate?

                // need to call something like lcl_translateUno2Basic
                // pArgs = lcl_translateUno2Basic( pUnoArgs );

                delete pUnoArgs;
            }
            // JavaScript calls are ignored
        }
    }
    return nRet;
}

<commit_msg>INTEGRATION: CWS dialogdiet (1.4.276); FILE MERGED 2003/12/01 18:16:49 mba 1.4.276.2: RESYNC: (1.4-1.5); FILE MERGED 2003/11/28 18:01:02 mba 1.4.276.1: #i22972#: obsolete include<commit_after>/*************************************************************************
 *
 *  $RCSfile: docbasic.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2004-02-03 14:35:47 $
 *
 *  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 _HINTIDS_HXX
#include <hintids.hxx>
#endif

#ifndef _RTL_USTRING_HXX //autogen
#include <rtl/ustring.hxx>
#endif
#ifndef _IMAP_HXX //autogen
#include <svtools/imap.hxx>
#endif
#ifndef _GOODIES_IMAPOBJ_HXX
#include <svtools/imapobj.hxx>
#endif
#ifndef _SBXCLASS_HXX
#include <svtools/sbx.hxx>
#endif
#ifndef _SBXCORE_HXX
#include <svtools/sbxcore.hxx>
#endif
#ifndef __SBX_SBXVALUE
#include <svtools/sbxvar.hxx>
#endif

#ifndef _FRMFMT_HXX //autogen
#include <frmfmt.hxx>
#endif
#ifndef _FMTINFMT_HXX //autogen
#include <fmtinfmt.hxx>
#endif
#ifndef _FMTURL_HXX //autogen
#include <fmturl.hxx>
#endif
#ifndef _FRMATR_HXX
#include <frmatr.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _SWEVENT_HXX
#include <swevent.hxx>
#endif

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

Sequence<Any> *lcl_docbasic_convertArgs( SbxArray& rArgs )
{
    Sequence<Any> *pRet = 0;

#if 0
    switch( nEvent )
    {
    case SW_EVENT_FRM_KEYINPUT_ALPHA:
    case SW_EVENT_FRM_KEYINPUT_NOALPHA:
    case SW_EVENT_FRM_MOVE:
    case SW_EVENT_FRM_RESIZE:
    }
#endif

    USHORT nCount = rArgs.Count();
    if( nCount > 1 )
    {
        nCount--;
        pRet = new Sequence<Any>( nCount );
        Any *pUnoArgs = pRet->getArray();
        for( USHORT i=0; i<nCount; i++ )
        {
            SbxVariable *pVar = rArgs.Get( i+1 );
            switch( pVar->GetType() )
            {
            case SbxSTRING:
                pUnoArgs[i] <<= OUString( pVar->GetString() );
                break;
            case SbxCHAR:
                pUnoArgs[i] <<= (sal_Int16)pVar->GetChar() ;
                break;
            case SbxUSHORT:
                pUnoArgs[i] <<= (sal_Int16)pVar->GetUShort();
                break;
            case SbxLONG:
                pUnoArgs[i] <<= (sal_Int32)pVar->GetLong();
                break;
            default:
                pUnoArgs[i].setValue(0, ::getVoidCppuType());
                break;
            }
        }
    }

    return pRet;
}

BOOL SwDoc::ExecMacro( const SvxMacro& rMacro, String* pRet, SbxArray* pArgs )
{
    ErrCode eErr = 0;
    switch( rMacro.GetScriptType() )
    {
    case STARBASIC:
        {
            SbxBaseRef aRef;
            SbxValue* pRetValue = new SbxValue;
            aRef = pRetValue;
            eErr = pDocShell->CallBasic( rMacro.GetMacName(),
                                         rMacro.GetLibName(),
                                         0, pArgs, pRet ? pRetValue : 0 );

            if( pRet && SbxNULL <  pRetValue->GetType() &&
                        SbxVOID != pRetValue->GetType() )
                // gueltiger Wert, also setzen
                *pRet = pRetValue->GetString();
        }
        break;
    case JAVASCRIPT:
        // ignore JavaScript calls
        break;
    case EXTENDED_STYPE:
        {
            Sequence<Any> *pUnoArgs = 0;
            if( pArgs )
            {
                // better to rename the local function to lcl_translateBasic2Uno and
                // a much shorter routine can be found in sfx2/source/doc/objmisc.cxx
                pUnoArgs = lcl_docbasic_convertArgs( *pArgs );
            }

            if (!pUnoArgs)
            {
                pUnoArgs = new Sequence< Any > (0);
            }

            // TODO - return value is not handled
            Any aRet;
            Sequence< sal_Int16 > aOutArgsIndex;
            Sequence< Any > aOutArgs;

            OSL_TRACE( "SwDoc::ExecMacro URL is %s", ByteString( rMacro.GetMacName(),
                RTL_TEXTENCODING_UTF8).GetBuffer() );

            eErr = pDocShell->CallXScript(
                rMacro.GetMacName(), *pUnoArgs, aRet, aOutArgsIndex, aOutArgs);

            //*pRet = pRetValue->GetString();
            // use the AnyConverter to return a String if appropriate?

            // need to call something like lcl_translateUno2Basic
            // pArgs = lcl_translateUno2Basic( pUnoArgs );

            delete pUnoArgs;
            break;
        }
    }

    return 0 == eErr;
}

USHORT SwDoc::CallEvent( USHORT nEvent, const SwCallMouseEvent& rCallEvent,
                    BOOL bCheckPtr, SbxArray* pArgs, const Link* pCallBack )
{
    if( !pDocShell )        // ohne DocShell geht das nicht!
        return 0;

    USHORT nRet = 0;
    const SvxMacroTableDtor* pTbl = 0;
    switch( rCallEvent.eType )
    {
    case EVENT_OBJECT_INETATTR:
        if( bCheckPtr  )
        {
            const SfxPoolItem* pItem;
            USHORT n, nMaxItems = GetAttrPool().GetItemCount( RES_TXTATR_INETFMT );
            for( n = 0; n < nMaxItems; ++n )
                if( 0 != (pItem = GetAttrPool().GetItem( RES_TXTATR_INETFMT, n ) )
                    && rCallEvent.PTR.pINetAttr == pItem )
                {
                    bCheckPtr = FALSE;      // als Flag missbrauchen
                    break;
                }
        }
        if( !bCheckPtr )
            pTbl = rCallEvent.PTR.pINetAttr->GetMacroTbl();
        break;

    case EVENT_OBJECT_URLITEM:
    case EVENT_OBJECT_IMAGE:
        {
            const SwFrmFmtPtr pFmt = (SwFrmFmtPtr)rCallEvent.PTR.pFmt;
            if( bCheckPtr )
            {
                USHORT nPos = GetSpzFrmFmts()->GetPos( pFmt );
                if( USHRT_MAX != nPos )
                    bCheckPtr = FALSE;      // als Flag missbrauchen
            }
            if( !bCheckPtr )
                pTbl = &pFmt->GetMacro().GetMacroTable();
        }
        break;

    case EVENT_OBJECT_IMAGEMAP:
        {
            const IMapObject* pIMapObj = rCallEvent.PTR.IMAP.pIMapObj;
            if( bCheckPtr )
            {
                const SwFrmFmtPtr pFmt = (SwFrmFmtPtr)rCallEvent.PTR.IMAP.pFmt;
                USHORT nPos = GetSpzFrmFmts()->GetPos( pFmt );
                const ImageMap* pIMap;
                if( USHRT_MAX != nPos &&
                    0 != (pIMap = pFmt->GetURL().GetMap()) )
                {
                    for( nPos = pIMap->GetIMapObjectCount(); nPos; )
                        if( pIMapObj == pIMap->GetIMapObject( --nPos ))
                        {
                            bCheckPtr = FALSE;      // als Flag missbrauchen
                            break;
                        }
                }
            }
            if( !bCheckPtr )
                pTbl = &pIMapObj->GetMacroTable();
        }
        break;
    }

    if( pTbl )
    {
        nRet = 0x1;
        if( pTbl->IsKeyValid( nEvent ) )
        {
            const SvxMacro& rMacro = *pTbl->Get( nEvent );
            if( STARBASIC == rMacro.GetScriptType() )
            {
                nRet += 0 == pDocShell->CallBasic( rMacro.GetMacName(),
                                    rMacro.GetLibName(), 0, pArgs ) ? 1 : 0;
            }
            else if( EXTENDED_STYPE == rMacro.GetScriptType() )
            {
                Sequence<Any> *pUnoArgs = 0;

                if( pArgs )
                {
                    pUnoArgs = lcl_docbasic_convertArgs( *pArgs );
                }

                if (!pUnoArgs)
                {
                    pUnoArgs = new Sequence <Any> (0);
                }

                Any aRet;
                Sequence< sal_Int16 > aOutArgsIndex;
                Sequence< Any > aOutArgs;

                OSL_TRACE( "SwDoc::CallEvent URL is %s", ByteString(
                    rMacro.GetMacName(), RTL_TEXTENCODING_UTF8).GetBuffer() );

                nRet += 0 == pDocShell->CallXScript(
                    rMacro.GetMacName(), *pUnoArgs,aRet, aOutArgsIndex, aOutArgs);

                //*pRet = pRetValue->GetString();
                // use the AnyConverter to return a String if appropriate?

                // need to call something like lcl_translateUno2Basic
                // pArgs = lcl_translateUno2Basic( pUnoArgs );

                delete pUnoArgs;
            }
            // JavaScript calls are ignored
        }
    }
    return nRet;
}

<|endoftext|>