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

#ifndef _SC_ACCESSIBLEDOCUMENT_HXX
#define _SC_ACCESSIBLEDOCUMENT_HXX

#ifndef _SC_ACCESSIBLEDOCUMENTBASE_HXX
#include "AccessibleDocumentBase.hxx"
#endif
#ifndef SC_VIEWDATA_HXX
#include "viewdata.hxx"
#endif

#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESELECTION_HPP_
#include <com/sun/star/accessibility/XAccessibleSelection.hpp>
#endif
#ifndef _COM_SUN_STAR_VIEW_XSELECTIONCHANGELISTENER_HPP_
#include <com/sun/star/view/XSelectionChangeListener.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

#ifndef _SVX_ACCESSIBILITY_IACCESSIBLE_VIEW_FORWARDER_HXX
#include <svx/IAccessibleViewForwarder.hxx>
#endif

class ScTabViewShell;
class ScAccessibleSpreadsheet;
class ScChildrenShapes;
class ScAccessibleEditObject;

namespace accessibility
{
    class AccessibleShape;
}
namespace utl
{
    class AccessibleRelationSetHelper;
}

/** @descr
        This base class provides an implementation of the
        AccessibleContext service.
*/

typedef cppu::ImplHelper2< ::com::sun::star::accessibility::XAccessibleSelection,
                            ::com::sun::star::view::XSelectionChangeListener >
                    ScAccessibleDocumentImpl;

class ScAccessibleDocument
    :   public ScAccessibleDocumentBase,
        public ScAccessibleDocumentImpl,
        public accessibility::IAccessibleViewForwarder
{
public:
    //=====  internal  ========================================================
    ScAccessibleDocument(
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>& rxParent,
        ScTabViewShell* pViewShell,
        ScSplitPos eSplitPos);

    virtual void Init();

    DECL_LINK( WindowChildEventListener, VclSimpleEvent* );
protected:
    virtual ~ScAccessibleDocument(void);
public:

     virtual void SAL_CALL disposing();

   ///=====  SfxListener  =====================================================

    virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    ///=====  XInterface  =====================================================

    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(
        ::com::sun::star::uno::Type const & rType )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL acquire() throw ();

    virtual void SAL_CALL release() throw ();

    ///=====  XAccessibleComponent  ============================================

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
        SAL_CALL getAccessibleAtPoint(
        const ::com::sun::star::awt::Point& rPoint )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL grabFocus(  )
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XAccessibleContext  ==============================================

    /// Return the number of currently visible children.
    virtual long SAL_CALL
        getAccessibleChildCount(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the specified child or NULL if index is invalid.
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL
        getAccessibleChild(long nIndex)
        throw (::com::sun::star::uno::RuntimeException,
                ::com::sun::star::lang::IndexOutOfBoundsException);

    /// Return the set of current states.
    virtual ::com::sun::star::uno::Reference<
            ::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL
        getAccessibleStateSet(void)
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XAccessibleSelection  ===========================================

    virtual void SAL_CALL
        selectAccessibleChild( sal_Int32 nChildIndex )
        throw (::com::sun::star::lang::IndexOutOfBoundsException,
        ::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL
        isAccessibleChildSelected( sal_Int32 nChildIndex )
        throw (::com::sun::star::lang::IndexOutOfBoundsException,
        ::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL
        clearAccessibleSelection(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL
        selectAllAccessibleChildren(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Int32 SAL_CALL
        getSelectedAccessibleChildCount(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible > SAL_CALL
        getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex )
        throw (::com::sun::star::lang::IndexOutOfBoundsException,
        ::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL
        deselectAccessibleChild( sal_Int32 nChildIndex )
        throw (::com::sun::star::lang::IndexOutOfBoundsException,
        ::com::sun::star::uno::RuntimeException);

    ///=====  XSelectionListener  =============================================

    virtual void SAL_CALL selectionChanged( const ::com::sun::star::lang::EventObject& aEvent )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XServiceInfo  ===================================================

    /** Returns an identifier for the implementation of this object.
    */
    virtual ::rtl::OUString SAL_CALL
        getImplementationName(void)
        throw (::com::sun::star::uno::RuntimeException);

    /** Returns a list of all supported services.
    */
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
        getSupportedServiceNames(void)
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XTypeProvider  ===================================================

    /// returns the possible types
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL
        getTypes()
        throw (::com::sun::star::uno::RuntimeException);

    /** Returns a implementation id.
    */
    virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL
        getImplementationId(void)
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  IAccessibleViewForwarder  ========================================

    /** This method informs you about the state of the forwarder.  Do not
        use it when the returned value is <false/>.

        @return
            Return <true/> if the view forwarder is valid and <false/> else.
     */
    virtual sal_Bool IsValid (void) const;

    /** Returns the area of the underlying document that is visible in the
    * corresponding window.

        @return
            The rectangle of the visible part of the document. The values
            are, contrary to the base class, in internal coordinates.
     */
    virtual Rectangle GetVisibleArea() const;

    /** Transform the specified point from internal coordinates to an
        absolute screen position.

        @param rPoint
            Point in internal coordinates.

        @return
            The same point but in screen coordinates relative to the upper
            left corner of the (current) screen.
     */
    virtual Point LogicToPixel (const Point& rPoint) const;

    /** Transform the specified size from internal coordinates to a screen
    * oriented pixel size.

        @param rSize
            Size in internal coordinates.

        @return
            The same size but in screen coordinates.
     */
    virtual Size LogicToPixel (const Size& rSize) const;

    /** Transform the specified point from absolute screen coordinates to
        internal coordinates.

        @param rPoint
            Point in screen coordinates relative to the upper left corner of
            the (current) screen.

        @return
            The same point but in internal coordinates.
     */
    virtual Point PixelToLogic (const Point& rPoint) const;

    /** Transform the specified size from screen coordinates to internal
        coordinates.

        @param rSize
            Size in screen coordinates.

        @return
            The same size but in internal coordinates.
     */
    virtual Size PixelToLogic (const Size& rSize) const;

    ///======== internal =====================================================

    utl::AccessibleRelationSetHelper* GetRelationSet(const ScAddress* pAddress) const;

    ::com::sun::star::uno::Reference
        < ::com::sun::star::accessibility::XAccessible >
        GetAccessibleSpreadsheet();

protected:
    /// Return this object's description.
    virtual ::rtl::OUString SAL_CALL
        createAccessibleDescription(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current name.
    virtual ::rtl::OUString SAL_CALL
        createAccessibleName(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current bounding box relative to the desktop.
    virtual Rectangle GetBoundingBoxOnScreen(void) const
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current bounding box relative to the parent object.
    virtual Rectangle GetBoundingBox(void) const
        throw (::com::sun::star::uno::RuntimeException);

private:
    ScTabViewShell* mpViewShell;
    ScSplitPos      meSplitPos;
    ScAccessibleSpreadsheet* mpAccessibleSpreadsheet;
    ScChildrenShapes* mpChildrenShapes;
    ScAccessibleEditObject* mpTempAccEdit;
    com::sun::star::uno::Reference<com::sun::star::accessibility::XAccessible> mxTempAcc;
    Rectangle maVisArea;
    sal_Bool mbCompleteSheetSelected;

public:
    sal_uInt16 getVisibleTable() const; // use it in ScChildrenShapes

private:
    void FreeAccessibleSpreadsheet();

    sal_Bool IsTableSelected() const;

    sal_Bool IsDefunc(
        const com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);
    sal_Bool IsEditable(
        const com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);

    void AddChild(const com::sun::star::uno::Reference<com::sun::star::accessibility::XAccessible>& xAcc, sal_Bool bFireEvent);
    void RemoveChild(const com::sun::star::uno::Reference<com::sun::star::accessibility::XAccessible>& xAcc, sal_Bool bFireEvent);

    rtl::OUString GetCurrentCellName() const;
    rtl::OUString GetCurrentCellDescription() const;

    Rectangle GetVisibleArea_Impl() const;
};

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

#ifndef _SC_ACCESSIBLEDOCUMENT_HXX
#define _SC_ACCESSIBLEDOCUMENT_HXX

#ifndef _SC_ACCESSIBLEDOCUMENTBASE_HXX
#include "AccessibleDocumentBase.hxx"
#endif
#ifndef SC_VIEWDATA_HXX
#include "viewdata.hxx"
#endif

#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESELECTION_HPP_
#include <com/sun/star/accessibility/XAccessibleSelection.hpp>
#endif
#ifndef _COM_SUN_STAR_VIEW_XSELECTIONCHANGELISTENER_HPP_
#include <com/sun/star/view/XSelectionChangeListener.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

#ifndef _SVX_ACCESSIBILITY_IACCESSIBLE_VIEW_FORWARDER_HXX
#include <svx/IAccessibleViewForwarder.hxx>
#endif

class ScTabViewShell;
class ScAccessibleSpreadsheet;
class ScChildrenShapes;
class ScAccessibleEditObject;

namespace accessibility
{
    class AccessibleShape;
}
namespace utl
{
    class AccessibleRelationSetHelper;
}

/** @descr
        This base class provides an implementation of the
        AccessibleContext service.
*/

typedef cppu::ImplHelper2< ::com::sun::star::accessibility::XAccessibleSelection,
                            ::com::sun::star::view::XSelectionChangeListener >
                    ScAccessibleDocumentImpl;

class ScAccessibleDocument
    :   public ScAccessibleDocumentBase,
        public ScAccessibleDocumentImpl,
        public accessibility::IAccessibleViewForwarder
{
public:
    //=====  internal  ========================================================
    ScAccessibleDocument(
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>& rxParent,
        ScTabViewShell* pViewShell,
        ScSplitPos eSplitPos);

    virtual void Init();

    DECL_LINK( WindowChildEventListener, VclSimpleEvent* );
protected:
    virtual ~ScAccessibleDocument(void);
public:

     virtual void SAL_CALL disposing();

   ///=====  SfxListener  =====================================================

    virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    ///=====  XInterface  =====================================================

    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(
        ::com::sun::star::uno::Type const & rType )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL acquire() throw ();

    virtual void SAL_CALL release() throw ();

    ///=====  XAccessibleComponent  ============================================

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
        SAL_CALL getAccessibleAtPoint(
        const ::com::sun::star::awt::Point& rPoint )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL grabFocus(  )
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XAccessibleContext  ==============================================

    /// Return the number of currently visible children.
    virtual long SAL_CALL
        getAccessibleChildCount(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the specified child or NULL if index is invalid.
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL
        getAccessibleChild(long nIndex)
        throw (::com::sun::star::uno::RuntimeException,
                ::com::sun::star::lang::IndexOutOfBoundsException);

    /// Return the set of current states.
    virtual ::com::sun::star::uno::Reference<
            ::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL
        getAccessibleStateSet(void)
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XAccessibleSelection  ===========================================

    virtual void SAL_CALL
        selectAccessibleChild( sal_Int32 nChildIndex )
        throw (::com::sun::star::lang::IndexOutOfBoundsException,
        ::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL
        isAccessibleChildSelected( sal_Int32 nChildIndex )
        throw (::com::sun::star::lang::IndexOutOfBoundsException,
        ::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL
        clearAccessibleSelection(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL
        selectAllAccessibleChildren(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Int32 SAL_CALL
        getSelectedAccessibleChildCount(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible > SAL_CALL
        getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex )
        throw (::com::sun::star::lang::IndexOutOfBoundsException,
        ::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL
        deselectAccessibleChild( sal_Int32 nChildIndex )
        throw (::com::sun::star::lang::IndexOutOfBoundsException,
        ::com::sun::star::uno::RuntimeException);

    ///=====  XSelectionListener  =============================================

    virtual void SAL_CALL selectionChanged( const ::com::sun::star::lang::EventObject& aEvent )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XServiceInfo  ===================================================

    /** Returns an identifier for the implementation of this object.
    */
    virtual ::rtl::OUString SAL_CALL
        getImplementationName(void)
        throw (::com::sun::star::uno::RuntimeException);

    /** Returns a list of all supported services.
    */
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
        getSupportedServiceNames(void)
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XTypeProvider  ===================================================

    /// returns the possible types
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL
        getTypes()
        throw (::com::sun::star::uno::RuntimeException);

    /** Returns a implementation id.
    */
    virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL
        getImplementationId(void)
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  IAccessibleViewForwarder  ========================================

    /** This method informs you about the state of the forwarder.  Do not
        use it when the returned value is <false/>.

        @return
            Return <true/> if the view forwarder is valid and <false/> else.
     */
    virtual sal_Bool IsValid (void) const;

    /** Returns the area of the underlying document that is visible in the
    * corresponding window.

        @return
            The rectangle of the visible part of the document. The values
            are, contrary to the base class, in internal coordinates.
     */
    virtual Rectangle GetVisibleArea() const;

    /** Transform the specified point from internal coordinates to an
        absolute screen position.

        @param rPoint
            Point in internal coordinates.

        @return
            The same point but in screen coordinates relative to the upper
            left corner of the (current) screen.
     */
    virtual Point LogicToPixel (const Point& rPoint) const;

    /** Transform the specified size from internal coordinates to a screen
    * oriented pixel size.

        @param rSize
            Size in internal coordinates.

        @return
            The same size but in screen coordinates.
     */
    virtual Size LogicToPixel (const Size& rSize) const;

    /** Transform the specified point from absolute screen coordinates to
        internal coordinates.

        @param rPoint
            Point in screen coordinates relative to the upper left corner of
            the (current) screen.

        @return
            The same point but in internal coordinates.
     */
    virtual Point PixelToLogic (const Point& rPoint) const;

    /** Transform the specified size from screen coordinates to internal
        coordinates.

        @param rSize
            Size in screen coordinates.

        @return
            The same size but in internal coordinates.
     */
    virtual Size PixelToLogic (const Size& rSize) const;

    ///======== internal =====================================================

    utl::AccessibleRelationSetHelper* GetRelationSet(const ScAddress* pAddress) const;

    ::com::sun::star::uno::Reference
        < ::com::sun::star::accessibility::XAccessible >
        GetAccessibleSpreadsheet();

protected:
    /// Return this object's description.
    virtual ::rtl::OUString SAL_CALL
        createAccessibleDescription(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current name.
    virtual ::rtl::OUString SAL_CALL
        createAccessibleName(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current bounding box relative to the desktop.
    virtual Rectangle GetBoundingBoxOnScreen(void) const
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current bounding box relative to the parent object.
    virtual Rectangle GetBoundingBox(void) const
        throw (::com::sun::star::uno::RuntimeException);

private:
    ScTabViewShell* mpViewShell;
    ScSplitPos      meSplitPos;
    ScAccessibleSpreadsheet* mpAccessibleSpreadsheet;
    ScChildrenShapes* mpChildrenShapes;
    ScAccessibleEditObject* mpTempAccEdit;
    com::sun::star::uno::Reference<com::sun::star::accessibility::XAccessible> mxTempAcc;
    Rectangle maVisArea;
    sal_Bool mbCompleteSheetSelected;

public:
    SCTAB getVisibleTable() const; // use it in ScChildrenShapes

private:
    void FreeAccessibleSpreadsheet();

    sal_Bool IsTableSelected() const;

    sal_Bool IsDefunc(
        const com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);
    sal_Bool IsEditable(
        const com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);

    void AddChild(const com::sun::star::uno::Reference<com::sun::star::accessibility::XAccessible>& xAcc, sal_Bool bFireEvent);
    void RemoveChild(const com::sun::star::uno::Reference<com::sun::star::accessibility::XAccessible>& xAcc, sal_Bool bFireEvent);

    rtl::OUString GetCurrentCellName() const;
    rtl::OUString GetCurrentCellDescription() const;

    Rectangle GetVisibleArea_Impl() const;
};

#endif
<|endoftext|>


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

#ifndef _SCRIPTING_STORAGE_SCRIPTDATA_HXX_
#define _SCRIPTING_STORAGE_SCRIPTDATA_HXX_

#include <vector>
#include <hash_map>

#include <cppu/macros.hxx>
#include <rtl/ustring.hxx>

namespace scripting_impl
{

typedef ::std::pair< ::rtl::OUString, ::rtl::OUString > str_pair;
typedef ::std::vector< str_pair > props_vec;
typedef ::std::hash_map< ::rtl::OUString, props_vec, ::rtl::OUStringHash,
    ::std::equal_to< ::rtl::OUString > > strpairvec_map;
typedef ::std::hash_map< ::rtl::OUString, ::std::pair< ::rtl::OUString,
    ::rtl::OUString >, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > strpair_map;
typedef ::std::hash_map< ::rtl::OUString, ::std::pair< props_vec, strpairvec_map >, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > filesets_map;

struct ScriptData
{

    inline ScriptData::ScriptData() SAL_THROW( () )
       : parcelURI()
       , language()
       , locales()
       , functionname()
       , logicalname()
       , languagedepprops()
       , filesets()
   {
   }

   inline ScriptData::ScriptData( const ::rtl::OUString __parcelURI,
       const ::rtl::OUString& __language,
       const strpair_map& __locales,
       const ::rtl::OUString& __functionname,
       const ::rtl::OUString& __logicalname,
       const props_vec& __languagedepprops,
       const filesets_map& __filesets ) SAL_THROW( () )
       : parcelURI( __parcelURI )
       , language( __language )
       , locales( __locales )
       , functionname( __functionname )
       , logicalname( __logicalname )
       , languagedepprops( __languagedepprops )
       , filesets( __filesets )
   {
   }

   ::rtl::OUString parcelURI;
   ::rtl::OUString language;
   strpair_map locales;
   ::rtl::OUString functionname;
   ::rtl::OUString logicalname;
   props_vec languagedepprops;
   filesets_map filesets;
};
} // namespace scripting_impl
#endif // _SCRIPTING_STORAGE_ScriptData_HXX_

<commit_msg>INTEGRATION: CWS ooo19126 (1.4.90); FILE MERGED 2005/09/05 12:05:26 rt 1.4.90.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ScriptData.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:35:25 $
 *
 *  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 _SCRIPTING_STORAGE_SCRIPTDATA_HXX_
#define _SCRIPTING_STORAGE_SCRIPTDATA_HXX_

#include <vector>
#include <hash_map>

#include <cppu/macros.hxx>
#include <rtl/ustring.hxx>

namespace scripting_impl
{

typedef ::std::pair< ::rtl::OUString, ::rtl::OUString > str_pair;
typedef ::std::vector< str_pair > props_vec;
typedef ::std::hash_map< ::rtl::OUString, props_vec, ::rtl::OUStringHash,
    ::std::equal_to< ::rtl::OUString > > strpairvec_map;
typedef ::std::hash_map< ::rtl::OUString, ::std::pair< ::rtl::OUString,
    ::rtl::OUString >, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > strpair_map;
typedef ::std::hash_map< ::rtl::OUString, ::std::pair< props_vec, strpairvec_map >, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > filesets_map;

struct ScriptData
{

    inline ScriptData::ScriptData() SAL_THROW( () )
       : parcelURI()
       , language()
       , locales()
       , functionname()
       , logicalname()
       , languagedepprops()
       , filesets()
   {
   }

   inline ScriptData::ScriptData( const ::rtl::OUString __parcelURI,
       const ::rtl::OUString& __language,
       const strpair_map& __locales,
       const ::rtl::OUString& __functionname,
       const ::rtl::OUString& __logicalname,
       const props_vec& __languagedepprops,
       const filesets_map& __filesets ) SAL_THROW( () )
       : parcelURI( __parcelURI )
       , language( __language )
       , locales( __locales )
       , functionname( __functionname )
       , logicalname( __logicalname )
       , languagedepprops( __languagedepprops )
       , filesets( __filesets )
   {
   }

   ::rtl::OUString parcelURI;
   ::rtl::OUString language;
   strpair_map locales;
   ::rtl::OUString functionname;
   ::rtl::OUString logicalname;
   props_vec languagedepprops;
   filesets_map filesets;
};
} // namespace scripting_impl
#endif // _SCRIPTING_STORAGE_ScriptData_HXX_

<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	Foobar 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file peer.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 * Peer Network test functions.
 */

#include <PeerNetwork.h>
using namespace std;
using namespace eth;
using boost::asio::ip::tcp;

int peerTest(int argc, char** argv)
{
	short listenPort = 30303;
	string remoteHost;
	short remotePort = 30303;

	for (int i = 1; i < argc; ++i)
	{
		string arg = argv[i];
		if (arg == "-l" && i + 1 < argc)
			listenPort = atoi(argv[++i]);
		else if (arg == "-r" && i + 1 < argc)
			remoteHost = argv[++i];
		else if (arg == "-p" && i + 1 < argc)
			remotePort = atoi(argv[++i]);
		else
			remoteHost = argv[i];
	}

	PeerServer pn(0, listenPort);

	if (!remoteHost.empty())
		pn.connect(remoteHost, remotePort);

	for (int i = 0; ; ++i)
	{
		usleep(100000);
		pn.process();
		if (!(i % 10))
			pn.pingAll();
	}

	return 0;
}

<commit_msg>Added client API & prototypal GUI.<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	Foobar 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file peer.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 * Peer Network test functions.
 */

#include <BlockChain.h>
#include <PeerNetwork.h>
using namespace std;
using namespace eth;
using boost::asio::ip::tcp;

int peerTest(int argc, char** argv)
{
	short listenPort = 30303;
	string remoteHost;
	short remotePort = 30303;

	for (int i = 1; i < argc; ++i)
	{
		string arg = argv[i];
		if (arg == "-l" && i + 1 < argc)
			listenPort = atoi(argv[++i]);
		else if (arg == "-r" && i + 1 < argc)
			remoteHost = argv[++i];
		else if (arg == "-p" && i + 1 < argc)
			remotePort = atoi(argv[++i]);
		else
			remoteHost = argv[i];
	}

	BlockChain ch("/tmp");
	PeerServer pn(ch, 0, listenPort);

	if (!remoteHost.empty())
		pn.connect(remoteHost, remotePort);

	for (int i = 0; ; ++i)
	{
		usleep(100000);
		pn.process();
		if (!(i % 10))
			pn.pingAll();
	}

	return 0;
}

<|endoftext|>


<commit_before>//
// Copyright © 2021 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include <armnn/backends/ICustomAllocator.hpp>
#include <armnn/Descriptors.hpp>
#include <armnn/Exceptions.hpp>
#include <armnn/INetwork.hpp>
#include <armnn/IRuntime.hpp>
#include <armnn/Utils.hpp>
#include <armnn/BackendRegistry.hpp>
#include <cl/ClBackend.hpp>

#include <doctest/doctest.h>

// Contains the OpenCl interfaces for mapping memory in the Gpu Page Tables
// Requires the OpenCl backend to be included (GpuAcc)
#include <arm_compute/core/CL/CLKernelLibrary.h>
#include <CL/cl_ext.h>
#include <arm_compute/runtime/CL/CLScheduler.h>

/** Sample implementation of ICustomAllocator for use with the ClBackend.
 *  Note: any memory allocated must be host accessible with write access to allow for weights and biases
 *  to be passed in. Read access is not required.. */
class SampleClBackendCustomAllocator : public armnn::ICustomAllocator
{
public:
    SampleClBackendCustomAllocator() = default;

    void* allocate(size_t size, size_t alignment)
    {
        // If alignment is 0 just use the CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE for alignment
        if (alignment == 0)
        {
            alignment = arm_compute::CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE>();
        }
        size_t space = size + alignment + alignment;
        auto allocatedMemPtr = std::malloc(space * sizeof(size_t));

        if (std::align(alignment, size, allocatedMemPtr, space) == nullptr)
        {
            throw armnn::Exception("SampleClBackendCustomAllocator::Alignment failed");
        }
        return allocatedMemPtr;
    }

    /** Interface to be implemented by the child class to free the allocated tensor */
    void free(void* ptr)
    {
        std::free(ptr);
    }

    armnn::MemorySource GetMemorySourceType()
    {
        return armnn::MemorySource::Malloc;
    }
};

armnn::INetworkPtr CreateTestNetwork(armnn::TensorInfo& inputTensorInfo)
{
    using namespace armnn;
    INetworkPtr myNetwork = INetwork::Create();

    armnn::FullyConnectedDescriptor fullyConnectedDesc;
    float weightsData[] = {1.0f}; // Identity
    TensorInfo weightsInfo(TensorShape({1, 1}), DataType::Float32);
    weightsInfo.SetConstant(true);
    armnn::ConstTensor weights(weightsInfo, weightsData);

    ARMNN_NO_DEPRECATE_WARN_BEGIN
    IConnectableLayer* fullyConnected = myNetwork->AddFullyConnectedLayer(fullyConnectedDesc,
                                                                          weights,
                                                                          EmptyOptional(),
                                                                          "fully connected");
    ARMNN_NO_DEPRECATE_WARN_END
    IConnectableLayer* InputLayer = myNetwork->AddInputLayer(0);
    IConnectableLayer* OutputLayer = myNetwork->AddOutputLayer(0);
    InputLayer->GetOutputSlot(0).Connect(fullyConnected->GetInputSlot(0));
    fullyConnected->GetOutputSlot(0).Connect(OutputLayer->GetInputSlot(0));

    //Set the tensors in the network.

    InputLayer->GetOutputSlot(0).SetTensorInfo(inputTensorInfo);

    TensorInfo outputTensorInfo(TensorShape({1, 1}), DataType::Float32);
    fullyConnected->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);

    return myNetwork;
}

TEST_SUITE("ClCustomAllocatorTests")
{

// This is a copy of the SimpleSample app modified to use a custom
// allocator for the clbackend. It creates a FullyConnected network with a single layer
// taking a single number as an input
TEST_CASE("ClCustomAllocatorTest")
{
    using namespace armnn;

    float number = 3;

    // Construct ArmNN network
    armnn::NetworkId networkIdentifier;

    TensorInfo inputTensorInfo(TensorShape({1, 1}), DataType::Float32);

    INetworkPtr myNetwork = CreateTestNetwork(inputTensorInfo);

    // Create ArmNN runtime
    IRuntime::CreationOptions options; // default options
    auto customAllocator = std::make_shared<SampleClBackendCustomAllocator>();
    options.m_CustomAllocatorMap = {{"GpuAcc", std::move(customAllocator)}};
    IRuntimePtr run = IRuntime::Create(options);

    // Optimise ArmNN network
    OptimizerOptions optOptions;
    optOptions.m_ImportEnabled = true;
    armnn::IOptimizedNetworkPtr optNet = Optimize(*myNetwork, {"GpuAcc"}, run->GetDeviceSpec(), optOptions);
    CHECK(optNet);

    // Load graph into runtime
    std::string ignoredErrorMessage;
    INetworkProperties networkProperties(false, MemorySource::Malloc, MemorySource::Malloc);
    run->LoadNetwork(networkIdentifier, std::move(optNet), ignoredErrorMessage, networkProperties);

    // Creates structures for input & output
    unsigned int numElements = inputTensorInfo.GetNumElements();
    size_t totalBytes = numElements * sizeof(float);

    const size_t alignment =
            arm_compute::CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE>();

    void* alignedInputPtr = options.m_CustomAllocatorMap["GpuAcc"]->allocate(totalBytes, alignment);

    // Input with negative values
    auto* inputPtr = reinterpret_cast<float*>(alignedInputPtr);
    std::fill_n(inputPtr, numElements, number);

    void* alignedOutputPtr = options.m_CustomAllocatorMap["GpuAcc"]->allocate(totalBytes, alignment);
    auto* outputPtr = reinterpret_cast<float*>(alignedOutputPtr);
    std::fill_n(outputPtr, numElements, -10.0f);

    armnn::InputTensors inputTensors
    {
        {0, armnn::ConstTensor(run->GetInputTensorInfo(networkIdentifier, 0), alignedInputPtr)},
    };
    armnn::OutputTensors outputTensors
    {
        {0, armnn::Tensor(run->GetOutputTensorInfo(networkIdentifier, 0), alignedOutputPtr)}
    };

    // Execute network
    run->EnqueueWorkload(networkIdentifier, inputTensors, outputTensors);
    run->UnloadNetwork(networkIdentifier);

    // Tell the CLBackend to sync memory so we can read the output.
    arm_compute::CLScheduler::get().sync();
    auto* outputResult = reinterpret_cast<float*>(alignedOutputPtr);

    run->UnloadNetwork(networkIdentifier);
    CHECK(outputResult[0] == number);
    auto& backendRegistry = armnn::BackendRegistryInstance();
    backendRegistry.DeregisterAllocator(ClBackend::GetIdStatic());
}

TEST_CASE("ClCustomAllocatorCpuAccNegativeTest")
{
    using namespace armnn;

    // Create ArmNN runtime
    IRuntime::CreationOptions options; // default options
    auto customAllocator = std::make_shared<SampleClBackendCustomAllocator>();
    options.m_CustomAllocatorMap = {{"CpuAcc", std::move(customAllocator)}};
    IRuntimePtr run = IRuntime::Create(options);

    TensorInfo inputTensorInfo(TensorShape({1, 1}), DataType::Float32);
    INetworkPtr myNetwork = CreateTestNetwork(inputTensorInfo);

    // Optimise ArmNN network
    OptimizerOptions optOptions;
    optOptions.m_ImportEnabled = true;
    IOptimizedNetworkPtr optNet(nullptr, nullptr);
    std::vector<std::string> errMessages;

    try
    {
        optNet = Optimize(*myNetwork, {"CpuAcc"}, run->GetDeviceSpec(), optOptions, errMessages);
        FAIL("Should have thrown an exception as GetAvailablePreferredBackends() should be empty in Optimize().");
    }
    catch (const armnn::InvalidArgumentException& e)
    {
        // Different exceptions are thrown on different backends
    }
    CHECK(errMessages.size() > 0);

    auto& backendRegistry = armnn::BackendRegistryInstance();
    backendRegistry.DeregisterAllocator(ClBackend::GetIdStatic());
}

TEST_CASE("ClCustomAllocatorGpuAccNullptrTest")
{
    using namespace armnn;

    // Create ArmNN runtime
    IRuntime::CreationOptions options; // default options
    auto customAllocator = std::make_shared<SampleClBackendCustomAllocator>();
    options.m_CustomAllocatorMap = {{"GpuAcc", nullptr}};

    try
    {
        IRuntimePtr run = IRuntime::Create(options);
        FAIL("Should have thrown an exception in RuntimeImpl::RuntimeImpl().");
    }
    catch (const armnn::Exception& e)
    {
        // Caught successfully
    }

    auto& backendRegistry = armnn::BackendRegistryInstance();
    backendRegistry.DeregisterAllocator(ClBackend::GetIdStatic());
}

} // test suite ClCustomAllocatorTests<commit_msg>Bugfix: Only run ClCustomAllocatorCpuAccNegativeTest if Neon Enabled<commit_after>//
// Copyright © 2021 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include <armnn/backends/ICustomAllocator.hpp>
#include <armnn/Descriptors.hpp>
#include <armnn/Exceptions.hpp>
#include <armnn/INetwork.hpp>
#include <armnn/IRuntime.hpp>
#include <armnn/Utils.hpp>
#include <armnn/BackendRegistry.hpp>
#include <cl/ClBackend.hpp>
#if defined(ARMCOMPUTENEON_ENABLED)
#include <neon/NeonBackend.hpp>
#endif

#include <doctest/doctest.h>

// Contains the OpenCl interfaces for mapping memory in the Gpu Page Tables
// Requires the OpenCl backend to be included (GpuAcc)
#include <arm_compute/core/CL/CLKernelLibrary.h>
#include <CL/cl_ext.h>
#include <arm_compute/runtime/CL/CLScheduler.h>

/** Sample implementation of ICustomAllocator for use with the ClBackend.
 *  Note: any memory allocated must be host accessible with write access to allow for weights and biases
 *  to be passed in. Read access is not required.. */
class SampleClBackendCustomAllocator : public armnn::ICustomAllocator
{
public:
    SampleClBackendCustomAllocator() = default;

    void* allocate(size_t size, size_t alignment)
    {
        // If alignment is 0 just use the CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE for alignment
        if (alignment == 0)
        {
            alignment = arm_compute::CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE>();
        }
        size_t space = size + alignment + alignment;
        auto allocatedMemPtr = std::malloc(space * sizeof(size_t));

        if (std::align(alignment, size, allocatedMemPtr, space) == nullptr)
        {
            throw armnn::Exception("SampleClBackendCustomAllocator::Alignment failed");
        }
        return allocatedMemPtr;
    }

    /** Interface to be implemented by the child class to free the allocated tensor */
    void free(void* ptr)
    {
        std::free(ptr);
    }

    armnn::MemorySource GetMemorySourceType()
    {
        return armnn::MemorySource::Malloc;
    }
};

armnn::INetworkPtr CreateTestNetwork(armnn::TensorInfo& inputTensorInfo)
{
    using namespace armnn;
    INetworkPtr myNetwork = INetwork::Create();

    armnn::FullyConnectedDescriptor fullyConnectedDesc;
    float weightsData[] = {1.0f}; // Identity
    TensorInfo weightsInfo(TensorShape({1, 1}), DataType::Float32);
    weightsInfo.SetConstant(true);
    armnn::ConstTensor weights(weightsInfo, weightsData);

    ARMNN_NO_DEPRECATE_WARN_BEGIN
    IConnectableLayer* fullyConnected = myNetwork->AddFullyConnectedLayer(fullyConnectedDesc,
                                                                          weights,
                                                                          EmptyOptional(),
                                                                          "fully connected");
    ARMNN_NO_DEPRECATE_WARN_END
    IConnectableLayer* InputLayer = myNetwork->AddInputLayer(0);
    IConnectableLayer* OutputLayer = myNetwork->AddOutputLayer(0);
    InputLayer->GetOutputSlot(0).Connect(fullyConnected->GetInputSlot(0));
    fullyConnected->GetOutputSlot(0).Connect(OutputLayer->GetInputSlot(0));

    //Set the tensors in the network.

    InputLayer->GetOutputSlot(0).SetTensorInfo(inputTensorInfo);

    TensorInfo outputTensorInfo(TensorShape({1, 1}), DataType::Float32);
    fullyConnected->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);

    return myNetwork;
}

TEST_SUITE("ClCustomAllocatorTests")
{

// This is a copy of the SimpleSample app modified to use a custom
// allocator for the clbackend. It creates a FullyConnected network with a single layer
// taking a single number as an input
TEST_CASE("ClCustomAllocatorTest")
{
    using namespace armnn;

    float number = 3;

    // Construct ArmNN network
    armnn::NetworkId networkIdentifier;

    TensorInfo inputTensorInfo(TensorShape({1, 1}), DataType::Float32);

    INetworkPtr myNetwork = CreateTestNetwork(inputTensorInfo);

    // Create ArmNN runtime
    IRuntime::CreationOptions options; // default options
    auto customAllocator = std::make_shared<SampleClBackendCustomAllocator>();
    options.m_CustomAllocatorMap = {{"GpuAcc", std::move(customAllocator)}};
    IRuntimePtr run = IRuntime::Create(options);

    // Optimise ArmNN network
    OptimizerOptions optOptions;
    optOptions.m_ImportEnabled = true;
    armnn::IOptimizedNetworkPtr optNet = Optimize(*myNetwork, {"GpuAcc"}, run->GetDeviceSpec(), optOptions);
    CHECK(optNet);

    // Load graph into runtime
    std::string ignoredErrorMessage;
    INetworkProperties networkProperties(false, MemorySource::Malloc, MemorySource::Malloc);
    run->LoadNetwork(networkIdentifier, std::move(optNet), ignoredErrorMessage, networkProperties);

    // Creates structures for input & output
    unsigned int numElements = inputTensorInfo.GetNumElements();
    size_t totalBytes = numElements * sizeof(float);

    const size_t alignment =
            arm_compute::CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE>();

    void* alignedInputPtr = options.m_CustomAllocatorMap["GpuAcc"]->allocate(totalBytes, alignment);

    // Input with negative values
    auto* inputPtr = reinterpret_cast<float*>(alignedInputPtr);
    std::fill_n(inputPtr, numElements, number);

    void* alignedOutputPtr = options.m_CustomAllocatorMap["GpuAcc"]->allocate(totalBytes, alignment);
    auto* outputPtr = reinterpret_cast<float*>(alignedOutputPtr);
    std::fill_n(outputPtr, numElements, -10.0f);

    armnn::InputTensors inputTensors
    {
        {0, armnn::ConstTensor(run->GetInputTensorInfo(networkIdentifier, 0), alignedInputPtr)},
    };
    armnn::OutputTensors outputTensors
    {
        {0, armnn::Tensor(run->GetOutputTensorInfo(networkIdentifier, 0), alignedOutputPtr)}
    };

    // Execute network
    run->EnqueueWorkload(networkIdentifier, inputTensors, outputTensors);
    run->UnloadNetwork(networkIdentifier);

    // Tell the CLBackend to sync memory so we can read the output.
    arm_compute::CLScheduler::get().sync();
    auto* outputResult = reinterpret_cast<float*>(alignedOutputPtr);

    run->UnloadNetwork(networkIdentifier);
    CHECK(outputResult[0] == number);
    auto& backendRegistry = armnn::BackendRegistryInstance();
    backendRegistry.DeregisterAllocator(ClBackend::GetIdStatic());
}

// Only run this test if NEON is enabled
#if defined(ARMCOMPUTENEON_ENABLED)

TEST_CASE("ClCustomAllocatorCpuAccNegativeTest")
{
    using namespace armnn;

    // Create ArmNN runtime
    IRuntime::CreationOptions options; // default options
    auto customAllocator = std::make_shared<SampleClBackendCustomAllocator>();
    options.m_CustomAllocatorMap = {{"CpuAcc", std::move(customAllocator)}};
    IRuntimePtr run = IRuntime::Create(options);

    TensorInfo inputTensorInfo(TensorShape({1, 1}), DataType::Float32);
    INetworkPtr myNetwork = CreateTestNetwork(inputTensorInfo);

    // Optimise ArmNN network
    OptimizerOptions optOptions;
    optOptions.m_ImportEnabled = true;
    IOptimizedNetworkPtr optNet(nullptr, nullptr);
    std::vector<std::string> errMessages;

    try
    {
        optNet = Optimize(*myNetwork, {"CpuAcc"}, run->GetDeviceSpec(), optOptions, errMessages);
        FAIL("Should have thrown an exception as GetAvailablePreferredBackends() should be empty in Optimize().");
    }
    catch (const armnn::InvalidArgumentException& e)
    {
        // Different exceptions are thrown on different backends
    }
    CHECK(errMessages.size() > 0);

    auto& backendRegistry = armnn::BackendRegistryInstance();
    backendRegistry.DeregisterAllocator(NeonBackend::GetIdStatic());
}

#endif

} // test suite ClCustomAllocatorTests<|endoftext|>


<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/lite/micro/examples/magic_wand/accelerometer_handler.h"
#include <stdio.h>
#include <zephyr.h>
#include <device.h>
#include <string.h>
#include <drivers/sensor.h>

#define BUFLEN 300
int begin_index = 0;
struct device *sensor = NULL;
int current_index = 0;

float bufx[BUFLEN] = {0.0f};
float bufy[BUFLEN] = {0.0f};
float bufz[BUFLEN] = {0.0f};

bool initial = true;

TfLiteStatus SetupAccelerometer(tflite::ErrorReporter* error_reporter) {
  sensor = device_get_binding(DT_INST_0_ADI_ADXL345_LABEL);
  if(sensor == NULL) {
    error_reporter->Report("Failed to get accelerometer, label: %s\n", DT_INST_0_ADI_ADXL345_LABEL);
  } else {
    error_reporter->Report("Got accelerometer, label: %s\n", DT_INST_0_ADI_ADXL345_LABEL);
  }
  return kTfLiteOk;
}

bool ReadAccelerometer(tflite::ErrorReporter* error_reporter, float* input,
                       int length) {
  int rc;
  struct sensor_value accel[3];
  int samples_count;

  rc = sensor_sample_fetch(sensor);
  if(rc < 0) {
    error_reporter -> Report("Fetch failed\n");
    return false;
  }
   //skip if there is no data
  if(!rc) {
    return false;
  }

  samples_count = rc;
  for(int i = 0; i < samples_count; i++) {
    rc = sensor_channel_get(sensor,
                            SENSOR_CHAN_ACCEL_XYZ,
                            accel);
    if (rc < 0) {
      error_reporter->Report("ERROR: Update failed: %d\n", rc);
      return false;
    }
    bufx[begin_index] = (float)sensor_value_to_double(&accel[0]);
    bufy[begin_index] = (float)sensor_value_to_double(&accel[1]);
    bufz[begin_index] = (float)sensor_value_to_double(&accel[2]);
    begin_index++;
    if (begin_index >= BUFLEN) begin_index = 0;

  }

  if(initial && begin_index >= 100) {
    initial = false;
  }

  if (initial) {
    return false;
  }

  int sample = 0;
  for (int i = 0; i < (length - 3); i+=3) {
    int ring_index = begin_index + sample - length/3;
    if(ring_index < 0) {
      ring_index += BUFLEN;
    }
    input[i] =   bufx[ring_index];
    input[i+1] = bufy[ring_index];
    input[i+2] = bufz[ring_index];
    sample++;
  }
  return true;
}
<commit_msg>lite: magic_wand: zephyr: report errors with macro<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/lite/micro/examples/magic_wand/accelerometer_handler.h"
#include <stdio.h>
#include <zephyr.h>
#include <device.h>
#include <string.h>
#include <drivers/sensor.h>

#define BUFLEN 300
int begin_index = 0;
struct device *sensor = NULL;
int current_index = 0;

float bufx[BUFLEN] = {0.0f};
float bufy[BUFLEN] = {0.0f};
float bufz[BUFLEN] = {0.0f};

bool initial = true;

TfLiteStatus SetupAccelerometer(tflite::ErrorReporter* error_reporter) {
  sensor = device_get_binding(DT_INST_0_ADI_ADXL345_LABEL);
  if(sensor == NULL) {
    TF_LITE_REPORT_ERROR(error_reporter, "Failed to get accelerometer, label: %s\n", DT_INST_0_ADI_ADXL345_LABEL);
  } else {
    TF_LITE_REPORT_ERROR(error_reporter, "Got accelerometer, label: %s\n", DT_INST_0_ADI_ADXL345_LABEL);
  }
  return kTfLiteOk;
}

bool ReadAccelerometer(tflite::ErrorReporter* error_reporter, float* input,
                       int length) {
  int rc;
  struct sensor_value accel[3];
  int samples_count;

  rc = sensor_sample_fetch(sensor);
  if(rc < 0) {
    TF_LITE_REPORT_ERROR(error_reporter, "Fetch failed\n");
    return false;
  }
   //skip if there is no data
  if(!rc) {
    return false;
  }

  samples_count = rc;
  for(int i = 0; i < samples_count; i++) {
    rc = sensor_channel_get(sensor,
                            SENSOR_CHAN_ACCEL_XYZ,
                            accel);
    if (rc < 0) {
      TF_LITE_REPORT_ERROR(error_reporter, "ERROR: Update failed: %d\n", rc);
      return false;
    }
    bufx[begin_index] = (float)sensor_value_to_double(&accel[0]);
    bufy[begin_index] = (float)sensor_value_to_double(&accel[1]);
    bufz[begin_index] = (float)sensor_value_to_double(&accel[2]);
    begin_index++;
    if (begin_index >= BUFLEN) begin_index = 0;

  }

  if(initial && begin_index >= 100) {
    initial = false;
  }

  if (initial) {
    return false;
  }

  int sample = 0;
  for (int i = 0; i < (length - 3); i+=3) {
    int ring_index = begin_index + sample - length/3;
    if(ring_index < 0) {
      ring_index += BUFLEN;
    }
    input[i] =   bufx[ring_index];
    input[i+1] = bufy[ring_index];
    input[i+2] = bufz[ring_index];
    sample++;
  }
  return true;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sbxcore.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2008-01-07 08:44: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
 *
 ************************************************************************/

#ifndef _SBXCORE_HXX
#define _SBXCORE_HXX

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

#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif

#include <basic/sbxdef.hxx>

class SvStream;
class String;
class UniString;

// Das nachfolgende Makro definiert die vier  (fuenf) notwendigen Methoden
// innerhalb eines SBX-Objekts. LoadPrivateData() und StorePrivateData()
// muessen selbst implementiert werden. Sie sind fuer das Laden/Speichern
// der Daten der abgeleiteten Klasse notwendig. Load() und Store() duerfen
// nicht ueberlagert werden.

// Diese Version des Makros definiert keine Load/StorePrivateData()-Methoden

#define SBX_DECL_PERSIST_NODATA( nCre, nSbxId, nVer )       \
    virtual UINT32 GetCreator() const { return nCre;   }    \
    virtual UINT16 GetVersion() const { return nVer;   }    \
    virtual UINT16 GetSbxId() const   { return nSbxId; }

#define SBX_DECL_PERSIST_NODATA_()                          \
    virtual UINT32 GetCreator() const;                      \
    virtual UINT16 GetVersion() const;                      \
    virtual UINT16 GetSbxId() const;

// Diese Version des Makros definiert Load/StorePrivateData()-Methoden

#define SBX_DECL_PERSIST( nCre, nSbxId, nVer )              \
    virtual BOOL LoadPrivateData( SvStream&, USHORT );      \
    virtual BOOL StorePrivateData( SvStream& ) const;       \
    SBX_DECL_PERSIST_NODATA( nCre, nSbxId, nVer )

#define SBX_DECL_PERSIST_()                                 \
    virtual BOOL LoadPrivateData( SvStream&, USHORT );      \
    virtual BOOL StorePrivateData( SvStream& ) const;       \
    SBX_DECL_PERSIST_NODATA_()

#define SBX_IMPL_PERSIST( C, nCre, nSbxId, nVer )           \
    UINT32 C::GetCreator() const { return nCre;   }         \
    UINT16 C::GetVersion() const { return nVer;   }         \
    UINT16 C::GetSbxId() const   { return nSbxId; }

class SbxBase;
class SbxFactory;
class SbxObject;

DBG_NAMEEX(SbxBase)

class SbxBaseImpl;

class SbxBase : virtual public SvRefBase
{
    SbxBaseImpl* mpSbxBaseImpl; // Impl data

    virtual BOOL LoadData( SvStream&, USHORT );
    virtual BOOL StoreData( SvStream& ) const;
protected:
    USHORT nFlags;          // Flag-Bits

    SbxBase();
    SbxBase( const SbxBase& );
    SbxBase& operator=( const SbxBase& );
    virtual ~SbxBase();
    SBX_DECL_PERSIST(0,0,0);
public:
    TYPEINFO();
    inline void     SetFlags( USHORT n );
    inline USHORT   GetFlags() const;
    inline void     SetFlag( USHORT n );
    inline void     ResetFlag( USHORT n );
    inline BOOL     IsSet( USHORT n ) const;
    inline BOOL     IsReset( USHORT n ) const;
    inline BOOL     CanRead() const;
    inline BOOL     CanWrite() const;
    inline BOOL     IsModified() const;
    inline BOOL     IsConst() const;
    inline BOOL     IsHidden() const;
    inline BOOL     IsVisible() const;

    virtual BOOL IsFixed() const;
    virtual void SetModified( BOOL );

    virtual SbxDataType  GetType()  const;
    virtual SbxClassType GetClass() const;

    virtual void Clear();

    static SbxBase* Load( SvStream& );
    static void Skip( SvStream& );
    BOOL Store( SvStream& );
    virtual BOOL LoadCompleted();
    virtual BOOL StoreCompleted();

    static SbxError GetError();
    static void SetError( SbxError );
    static BOOL IsError();
    static void ResetError();

    // Setzen der Factory fuer Load/Store/Create
    static void AddFactory( SbxFactory* );
    static void RemoveFactory( SbxFactory* );

    static SbxBase* Create( UINT16, UINT32=SBXCR_SBX );
    static SbxObject* CreateObject( const String& );
    // Sbx-Loesung als Ersatz fuer SfxBroadcaster::Enable()
    static void StaticEnableBroadcasting( BOOL bEnable );
    static BOOL StaticIsEnabledBroadcasting( void );
};

#ifndef SBX_BASE_DECL_DEFINED
#define SBX_BASE_DECL_DEFINED
SV_DECL_REF(SbxBase)
#endif

inline void SbxBase::SetFlags( USHORT n )
{ DBG_CHKTHIS( SbxBase, 0 ); nFlags = n; }

inline USHORT SbxBase::GetFlags() const
{ DBG_CHKTHIS( SbxBase, 0 ); return nFlags; }

inline void SbxBase::SetFlag( USHORT n )
{ DBG_CHKTHIS( SbxBase, 0 ); nFlags |= n; }

inline void SbxBase::ResetFlag( USHORT n )
{ DBG_CHKTHIS( SbxBase, 0 ); nFlags &= ~n; }

inline BOOL SbxBase::IsSet( USHORT n ) const
{ DBG_CHKTHIS( SbxBase, 0 ); return BOOL( ( nFlags & n ) != 0 ); }

inline BOOL SbxBase::IsReset( USHORT n ) const
{ DBG_CHKTHIS( SbxBase, 0 ); return BOOL( ( nFlags & n ) == 0 ); }

inline BOOL SbxBase::CanRead() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsSet( SBX_READ ); }

inline BOOL SbxBase::CanWrite() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsSet( SBX_WRITE ); }

inline BOOL SbxBase::IsModified() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsSet( SBX_MODIFIED ); }

inline BOOL SbxBase::IsConst() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsSet( SBX_CONST ); }

inline BOOL SbxBase::IsHidden() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsSet( SBX_HIDDEN ); }

inline BOOL SbxBase::IsVisible() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsReset( SBX_INVISIBLE ); }

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.28); FILE MERGED 2008/04/01 15:01:45 thb 1.3.28.2: #i85898# Stripping all external header guards 2008/03/28 16:06:57 rt 1.3.28.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: sbxcore.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SBXCORE_HXX
#define _SBXCORE_HXX

#include <tools/rtti.hxx>
#include <tools/ref.hxx>
#include <tools/debug.hxx>

#include <basic/sbxdef.hxx>

class SvStream;
class String;
class UniString;

// Das nachfolgende Makro definiert die vier  (fuenf) notwendigen Methoden
// innerhalb eines SBX-Objekts. LoadPrivateData() und StorePrivateData()
// muessen selbst implementiert werden. Sie sind fuer das Laden/Speichern
// der Daten der abgeleiteten Klasse notwendig. Load() und Store() duerfen
// nicht ueberlagert werden.

// Diese Version des Makros definiert keine Load/StorePrivateData()-Methoden

#define SBX_DECL_PERSIST_NODATA( nCre, nSbxId, nVer )       \
    virtual UINT32 GetCreator() const { return nCre;   }    \
    virtual UINT16 GetVersion() const { return nVer;   }    \
    virtual UINT16 GetSbxId() const   { return nSbxId; }

#define SBX_DECL_PERSIST_NODATA_()                          \
    virtual UINT32 GetCreator() const;                      \
    virtual UINT16 GetVersion() const;                      \
    virtual UINT16 GetSbxId() const;

// Diese Version des Makros definiert Load/StorePrivateData()-Methoden

#define SBX_DECL_PERSIST( nCre, nSbxId, nVer )              \
    virtual BOOL LoadPrivateData( SvStream&, USHORT );      \
    virtual BOOL StorePrivateData( SvStream& ) const;       \
    SBX_DECL_PERSIST_NODATA( nCre, nSbxId, nVer )

#define SBX_DECL_PERSIST_()                                 \
    virtual BOOL LoadPrivateData( SvStream&, USHORT );      \
    virtual BOOL StorePrivateData( SvStream& ) const;       \
    SBX_DECL_PERSIST_NODATA_()

#define SBX_IMPL_PERSIST( C, nCre, nSbxId, nVer )           \
    UINT32 C::GetCreator() const { return nCre;   }         \
    UINT16 C::GetVersion() const { return nVer;   }         \
    UINT16 C::GetSbxId() const   { return nSbxId; }

class SbxBase;
class SbxFactory;
class SbxObject;

DBG_NAMEEX(SbxBase)

class SbxBaseImpl;

class SbxBase : virtual public SvRefBase
{
    SbxBaseImpl* mpSbxBaseImpl; // Impl data

    virtual BOOL LoadData( SvStream&, USHORT );
    virtual BOOL StoreData( SvStream& ) const;
protected:
    USHORT nFlags;          // Flag-Bits

    SbxBase();
    SbxBase( const SbxBase& );
    SbxBase& operator=( const SbxBase& );
    virtual ~SbxBase();
    SBX_DECL_PERSIST(0,0,0);
public:
    TYPEINFO();
    inline void     SetFlags( USHORT n );
    inline USHORT   GetFlags() const;
    inline void     SetFlag( USHORT n );
    inline void     ResetFlag( USHORT n );
    inline BOOL     IsSet( USHORT n ) const;
    inline BOOL     IsReset( USHORT n ) const;
    inline BOOL     CanRead() const;
    inline BOOL     CanWrite() const;
    inline BOOL     IsModified() const;
    inline BOOL     IsConst() const;
    inline BOOL     IsHidden() const;
    inline BOOL     IsVisible() const;

    virtual BOOL IsFixed() const;
    virtual void SetModified( BOOL );

    virtual SbxDataType  GetType()  const;
    virtual SbxClassType GetClass() const;

    virtual void Clear();

    static SbxBase* Load( SvStream& );
    static void Skip( SvStream& );
    BOOL Store( SvStream& );
    virtual BOOL LoadCompleted();
    virtual BOOL StoreCompleted();

    static SbxError GetError();
    static void SetError( SbxError );
    static BOOL IsError();
    static void ResetError();

    // Setzen der Factory fuer Load/Store/Create
    static void AddFactory( SbxFactory* );
    static void RemoveFactory( SbxFactory* );

    static SbxBase* Create( UINT16, UINT32=SBXCR_SBX );
    static SbxObject* CreateObject( const String& );
    // Sbx-Loesung als Ersatz fuer SfxBroadcaster::Enable()
    static void StaticEnableBroadcasting( BOOL bEnable );
    static BOOL StaticIsEnabledBroadcasting( void );
};

#ifndef SBX_BASE_DECL_DEFINED
#define SBX_BASE_DECL_DEFINED
SV_DECL_REF(SbxBase)
#endif

inline void SbxBase::SetFlags( USHORT n )
{ DBG_CHKTHIS( SbxBase, 0 ); nFlags = n; }

inline USHORT SbxBase::GetFlags() const
{ DBG_CHKTHIS( SbxBase, 0 ); return nFlags; }

inline void SbxBase::SetFlag( USHORT n )
{ DBG_CHKTHIS( SbxBase, 0 ); nFlags |= n; }

inline void SbxBase::ResetFlag( USHORT n )
{ DBG_CHKTHIS( SbxBase, 0 ); nFlags &= ~n; }

inline BOOL SbxBase::IsSet( USHORT n ) const
{ DBG_CHKTHIS( SbxBase, 0 ); return BOOL( ( nFlags & n ) != 0 ); }

inline BOOL SbxBase::IsReset( USHORT n ) const
{ DBG_CHKTHIS( SbxBase, 0 ); return BOOL( ( nFlags & n ) == 0 ); }

inline BOOL SbxBase::CanRead() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsSet( SBX_READ ); }

inline BOOL SbxBase::CanWrite() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsSet( SBX_WRITE ); }

inline BOOL SbxBase::IsModified() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsSet( SBX_MODIFIED ); }

inline BOOL SbxBase::IsConst() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsSet( SBX_CONST ); }

inline BOOL SbxBase::IsHidden() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsSet( SBX_HIDDEN ); }

inline BOOL SbxBase::IsVisible() const
{ DBG_CHKTHIS( SbxBase, 0 ); return IsReset( SBX_INVISIBLE ); }

#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <unistd.h>
#include <getopt.h>
#include "gen.h"
#include "interface.h"
#include "parser.h"

int main(int argc, char *argv[])
{
	Generate Gen;
	Parser Prs;
	char *ybf;
	while (1) {
		static struct option long_options[] = {
			{ "new", optional_argument, 0, 'n' },
			{ "help", no_argument, 0, 'h' },
			{ "debug", no_argument, 0, 'd' },
			{ 0, 0, 0, 0 }
		};
		int option_index = 0;
		int c = getopt_long(argc, argv, "dhnm", long_options, &option_index);
		if (c == -1)
			break;
		switch (c) {
		case 'd':
			Gen.CheckMake();
			Gen.WriteMake();
			Gen.GenMakeFromTemplate();
			Gen.WalkDir(Gen.current_dir, ".\\.cpp$", FS_DEFAULT | FS_MATCHDIRS);
			Gen.WalkDir(Gen.current_dir, ".\\.h$", FS_DEFAULT | FS_MATCHDIRS);
			Prs.OpenConfig(argv[2]);
			break;
		case 'h':
			printHelp();
			break;
		case 'n':
			Gen.GenBlankConfig(0);
			break;
		}
	}
	return 0;
}
<commit_msg>yabs: fix debug optional argument<commit_after>#include <iostream>
#include <unistd.h>
#include <getopt.h>
#include "gen.h"
#include "interface.h"
#include "parser.h"

int main(int argc, char *argv[])
{
	Generate Gen;
	Parser Prs;
	char *ybf;
	while (1) {
		static struct option long_options[] = {
			{ "new", optional_argument, 0, 'n' },
			{ "help", no_argument, 0, 'h' },
			{ "debug", no_argument, 0, 'd' },
			{ 0, 0, 0, 0 }
		};
		int option_index = 0;
		int c = getopt_long(argc, argv, "dhnm", long_options, &option_index);
		if (c == -1)
			break;
		switch (c) {
		case 'd':
			Gen.CheckMake();
			Gen.WriteMake();
			Gen.GenMakeFromTemplate();
			Gen.WalkDir(Gen.current_dir, ".\\.cpp$", FS_DEFAULT | FS_MATCHDIRS);
			Gen.WalkDir(Gen.current_dir, ".\\.h$", FS_DEFAULT | FS_MATCHDIRS);
			if (argv[2] != NULL)
				Prs.OpenConfig(argv[2]);
			break;
		case 'h':
			printHelp();
			break;
		case 'n':
			Gen.GenBlankConfig(0);
			break;
		}
	}
	return 0;
}
<|endoftext|>


<commit_before>#include "update.hpp"

#include <cstdio>
#include "storage.hpp"

static std::map<uint16_t, LiveUpdate::resume_func> resume_funcs;

bool resume_begin(storage_header& storage, LiveUpdate::resume_func func)
{
  /// verify checksum

  /// restore each entry one by one, calling registered handlers
  printf("* Resuming %d stored entries\n", storage.entries);

  for (auto* ptr = storage.begin(); ptr->type != TYPE_END; ptr = storage.next(ptr))
  {
    // use registered functions when we can, otherwise, use normal
    auto it = resume_funcs.find(ptr->id);
    if (it != resume_funcs.end())
    {
      it->second(*ptr);
    } else {
      func(*ptr);
    }
  }
  return true;
}

void LiveUpdate::on_resume(uint16_t id, resume_func func)
{
  resume_funcs[id] = func;
}

/// struct Restore

std::string Restore::as_string() const
{
  if (ent.type == TYPE_STRING)
      return std::string(ent.vla, ent.len);
  throw std::runtime_error("Incorrect type: " + std::to_string(ent.type));
}
buffer_len  Restore::as_buffer() const
{
  if (ent.type == TYPE_BUFFER)
      return {ent.vla, ent.len};
  throw std::runtime_error("Incorrect type: " + std::to_string(ent.type));
}
#include "serialize_tcp.hpp"
Restore::Connection Restore::as_tcp_connection(net::TCP& tcp) const
{
  return deserialize_connection(ent.vla, tcp);
}

int16_t  Restore::get_type() const noexcept
{
  return ent.type;
}
uint16_t Restore::get_id() const noexcept
{
  return ent.id;
}
int32_t  Restore::length() const noexcept
{
  return ent.len;
}
void*    Restore::data() const noexcept
{
  return ent.vla;
}
<commit_msg>Zero storage after resuming for security<commit_after>#include "update.hpp"

#include <cstdio>
#include "storage.hpp"

static std::map<uint16_t, LiveUpdate::resume_func> resume_funcs;

bool resume_begin(storage_header& storage, LiveUpdate::resume_func func)
{
  /// verify checksum

  /// restore each entry one by one, calling registered handlers
  printf("* Resuming %d stored entries\n", storage.entries);

  for (auto* ptr = storage.begin(); ptr->type != TYPE_END; ptr = storage.next(ptr))
  {
    // use registered functions when we can, otherwise, use normal
    auto it = resume_funcs.find(ptr->id);
    if (it != resume_funcs.end())
    {
      it->second(*ptr);
    } else {
      func(*ptr);
    }
  }
  /// zero out all the values for security reasons
  memset(&storage, 0, sizeof(storage_header) + storage.length);

  return true;
}

void LiveUpdate::on_resume(uint16_t id, resume_func func)
{
  resume_funcs[id] = func;
}

/// struct Restore

std::string Restore::as_string() const
{
  if (ent.type == TYPE_STRING)
      return std::string(ent.vla, ent.len);
  throw std::runtime_error("Incorrect type: " + std::to_string(ent.type));
}
buffer_len  Restore::as_buffer() const
{
  if (ent.type == TYPE_BUFFER)
      return {ent.vla, ent.len};
  throw std::runtime_error("Incorrect type: " + std::to_string(ent.type));
}
#include "serialize_tcp.hpp"
Restore::Connection Restore::as_tcp_connection(net::TCP& tcp) const
{
  return deserialize_connection(ent.vla, tcp);
}

int16_t  Restore::get_type() const noexcept
{
  return ent.type;
}
uint16_t Restore::get_id() const noexcept
{
  return ent.id;
}
int32_t  Restore::length() const noexcept
{
  return ent.len;
}
void*    Restore::data() const noexcept
{
  return ent.vla;
}
<|endoftext|>


<commit_before>#include <hx/CFFI.h>
#include <ui/GamepadEvent.h>

namespace lime {

	AutoGCRoot* GamepadEvent::callback = 0;
	AutoGCRoot* GamepadEvent::eventObject = 0;

	static double id_axis;
	static int id_button;
	static int id_id;
	static int id_type;
	static int id_value;
	static bool init = false;

	GamepadEvent::GamepadEvent () {

		axis = 0;
		axisValue = 0;
		button = 0;
		id = 0;
		type = AXIS_MOVE;

	}

	void GamepadEvent::Dispatch (GamepadEvent* event) {

		if (GamepadEvent::callback) {

			if (!init) {

				id_axis = val_id ("axis");
				id_button = val_id ("button");
				id_id = val_id ("id");
				id_type = val_id ("type");
				id_value = val_id ("value");
				init = true;

			}

			value object = (GamepadEvent::eventObject ? GamepadEvent::eventObject->get () : alloc_empty_object ());

			alloc_field (object, id_axis, alloc_float (event->axis));
			alloc_field (object, id_button, alloc_int (event->button));
			alloc_field (object, id_id, alloc_int (event->id));
			alloc_field (object, id_type, alloc_int (event->type));
			alloc_field (object, id_value, alloc_float (event->axisValue));

			val_call0 (GamepadEvent::callback->get ());

		}

	}

}<commit_msg>Should be alloc_int<commit_after>#include <hx/CFFI.h>
#include <ui/GamepadEvent.h>

namespace lime {

	AutoGCRoot* GamepadEvent::callback = 0;
	AutoGCRoot* GamepadEvent::eventObject = 0;

	static double id_axis;
	static int id_button;
	static int id_id;
	static int id_type;
	static int id_value;
	static bool init = false;

	GamepadEvent::GamepadEvent () {

		axis = 0;
		axisValue = 0;
		button = 0;
		id = 0;
		type = AXIS_MOVE;

	}

	void GamepadEvent::Dispatch (GamepadEvent* event) {

		if (GamepadEvent::callback) {

			if (!init) {

				id_axis = val_id ("axis");
				id_button = val_id ("button");
				id_id = val_id ("id");
				id_type = val_id ("type");
				id_value = val_id ("value");
				init = true;

			}

			value object = (GamepadEvent::eventObject ? GamepadEvent::eventObject->get () : alloc_empty_object ());

			alloc_field (object, id_axis, alloc_int (event->axis));
			alloc_field (object, id_button, alloc_int (event->button));
			alloc_field (object, id_id, alloc_int (event->id));
			alloc_field (object, id_type, alloc_int (event->type));
			alloc_field (object, id_value, alloc_float (event->axisValue));

			val_call0 (GamepadEvent::callback->get ());

		}

	}

}<|endoftext|>


<commit_before>/**
Copyright (c) 2013, Philip Deegan.
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 Philip Deegan nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _KUL_TCP_BASE_HPP_
#define _KUL_TCP_BASE_HPP_

namespace kul{ namespace tcp {

class Exception : public kul::Exception{
    public:
        Exception(const char*f, const uint16_t& l, const std::string& s) : kul::Exception(f, l, s){}
};

template <class T = uint8_t>
class ASocket{
	protected:
		bool open = 0;
	public:
		virtual ~ASocket(){}
		virtual bool connect(const std::string& host, const int16_t& port)  = 0;
		virtual bool close()    = 0;
		virtual uint16_t read(T* data, const size_t& len) throw(kul::tcp::Exception) = 0;
		virtual bool write(const T* data, const size_t& len) = 0;

};

template <class T = uint8_t>
class ASocketServer{
	protected:
        uint16_t p;
        uint64_t s;

        ASocketServer(const uint16_t& p) : p(p){}
	public:
		virtual ~ASocketServer(){}
		virtual void start() throw (kul::tcp::Exception) = 0;
        virtual void onConnect(const char* ip, const uint16_t& port){}
        virtual void onDisconnect(const char* ip, const uint16_t& port){}
        const uint64_t  up()   const { return s - kul::Now::MILLIS(); }
        const uint16_t& port() const { return p; }
        bool started() const { return s; }
};

}// END NAMESPACE tcp
}// END NAMESPACE kul

#endif /* _KUL_HTTP_BASE_HPP_ */<commit_msg>Update tcp.base.hpp<commit_after>/**
Copyright (c) 2013, Philip Deegan.
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 Philip Deegan nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _KUL_TCP_BASE_HPP_
#define _KUL_TCP_BASE_HPP_

namespace kul{ namespace tcp {

class Exception : public kul::Exception{
    public:
        Exception(const char*f, const uint16_t& l, const std::string& s) : kul::Exception(f, l, s){}
};

template <class T = uint8_t>
class ASocket{
	protected:
		bool open = 0;
	public:
		virtual ~ASocket(){}
		virtual bool connect(const std::string& host, const int16_t& port)  = 0;
		virtual bool close()    = 0;
		virtual uint16_t read(T* data, const uint16_t& len) throw(kul::tcp::Exception) = 0;
		virtual bool write(const T* data, const uint16_t& len) = 0;

};

template <class T = uint8_t>
class ASocketServer{
	protected:
        uint16_t p;
        uint64_t s;

        ASocketServer(const uint16_t& p) : p(p){}
	public:
		virtual ~ASocketServer(){}
		virtual void start() throw (kul::tcp::Exception) = 0;
        virtual void onConnect(const char* ip, const uint16_t& port){}
        virtual void onDisconnect(const char* ip, const uint16_t& port){}
        const uint64_t  up()   const { return s - kul::Now::MILLIS(); }
        const uint16_t& port() const { return p; }
        bool started() const { return s; }
};

}// END NAMESPACE tcp
}// END NAMESPACE kul

#endif /* _KUL_HTTP_BASE_HPP_ */
<|endoftext|>


<commit_before>/**
@file Log.hpp
@brief Logging utilities.

@author Timothy Howard
@copyright 2013-2014 Timothy Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/

#ifndef HORD_LOG_HPP_
#define HORD_LOG_HPP_

#include <Hord/config.hpp>
#include <Hord/String.hpp>

#include <duct/StateStore.hpp>
#include <duct/IO/multistream.hpp>

#include <fstream>
#include <ostream>

namespace Hord {
namespace Log {

// TODO: Common output sentinels (e.g., current time in ISO-8601)
// TODO: Logging interface like exception throwing

// TODO: Datastores need to logify by roots.. somehow.
// Driver should probably manage that. Actually, Driver will
// probably be doing most of the Datastore logging anyways.

// TODO: Need to handle multi-threaded output to file stream properly
// FIXME: thread_local requires g++ 4.8!? (In Clang!)

// Forward declarations
class Controller;
class OutputStream;

/**
	@addtogroup etc
	@{
*/
/**
	@addtogroup log
	@{
*/

/**
	Stream type.
*/
enum StreamType : unsigned {
	general = 0u,
	debug,
	error,

/** @cond INTERNAL */
	LAST
/** @endcond */ // INTERNAL
};

/** Stream prefixes. */
enum class Pre : unsigned {
	general = 0u,
	debug,
	error,

	none,
	current,

/** @cond INTERNAL */
	LAST,
	LAST_TYPE = error
/** @endcond */ // INTERNAL
};

/** @cond INTERNAL */
enum : std::size_t {
	STREAMBUF_BUFFER_SIZE = 2048u
};

extern /*thread_local*/ Controller
s_controller;
/** @endcond */ // INTERNAL

/**
	Get the log controller.
*/
inline Controller&
get_controller() noexcept {
	return s_controller;
}

/**
	Log controller.
*/
class Controller final {
private:
	friend class OutputStream;

	/**
		State flags.
	*/
	enum class Flag : unsigned {
		write_stdout = 1 << 0,
		write_file = 1 << 1,
		write_datastore = 1 << 2
	};

	duct::StateStore<Flag> m_flags;
	String m_file_path;

	std::ofstream m_file_stream;
	char m_mc_buffer[STREAMBUF_BUFFER_SIZE];
	duct::IO::multicast_vector_type m_mc_vectors[
		static_cast<unsigned>(StreamType::LAST)
	];
	duct::IO::multistreambuf m_mc_streambufs[
		static_cast<unsigned>(StreamType::LAST)
	];

	/** Disable multicast to log file stream. */
	void
	disable_file_stream() noexcept;
	/** Enable multicast to log file stream. */
	void
	enable_file_stream() noexcept;

	/**
		Open the log file stream.

		@returns Whether the operation succeeded.
	*/
	bool
	open_file();

	/**
		Close the log file stream.

		@returns Whether the operation succeeded.
	*/
	bool
	close_file();

	Controller(Controller&&) = delete;
	Controller(Controller const&) = delete;
	Controller& operator=(Controller const&) = delete;
	Controller& operator=(Controller&&) = delete;

public:
/** @name Constructors and destructor */ /// @{
	/**
		Constructor with flags and log file path.

		@param enable_stdout Enable or disable standard output.
		@param enable_file Enable or disable log file output.
		@param enable_datastore Enable or disable datastore-local
		file output.
		@param path Log file path.
	*/
	Controller(
		bool const enable_stdout,
		bool const enable_file,
		bool const enable_datastore,
		String path
	) noexcept;

	/** Destructor. */
	~Controller() noexcept;
/// @}

/** @name Configuration */ /// @{
	/**
		Enable or disable standard output.

		@param enable Whether to enable or disable output.
	*/
	void
	stdout(
		bool const enable
	) noexcept;

	/**
		Check whether standard output is enabled.
	*/
	bool
	stdout_enabled() const noexcept {
		return m_flags.test(Flag::write_stdout);
	}

	/**
		Enable or disable file output.

		@returns
		- @c true if the operation succeeded (i.e., opening or closing
		  the log file stream);
		- @c false if the operation failed.
		@param enable Whether to enable or disable output.
	*/
	bool
	file(
		bool const enable
	) noexcept;

	/**
		Check whether file output is enabled.
	*/
	bool
	file_enabled() const noexcept {
		return m_flags.test(Flag::write_file);
	}

	/**
		Check whether the file stream is open.

		@remarks If this returns @c true, it implies
		file_enabled() == true.
	*/
	bool
	file_active() const noexcept {
		return m_file_stream.is_open();
	}

	/**
		Enable or disable datastore-local file output.

		@param enable Whether to enable or disable output.
	*/
	void
	datastore(
		bool const enable
	) noexcept;

	/**
		Check whether datastore-local file output is enabled.
	*/
	bool
	datastore_enabled() const noexcept {
		return m_flags.test(Flag::write_datastore);
	}

	/**
		Set the log file path.

		@remarks If the file stream is currently open, it is closed.
		If opening on @a path fails, @c false is returned, but file
		output is still enabled. If log file output is disabled,
		this only assigns the log file path.

		@returns
		- @c true if the file stream was successfully opened;
		- @c false if the file path could not be opened for writing.
		@param path Log file path.
	*/
	bool
	set_file_path(
		String path
	) noexcept;

	/**
		Get log file path.
	*/
	String const&
	get_file_path() const noexcept {
		return m_file_path;
	}
/// @}
};

/**
	Log output stream.
*/
class OutputStream final
	: public std::ostream
{
private:
	using base = std::ostream;

	StreamType const m_type;

	OutputStream() = delete;
	OutputStream(OutputStream const&) = delete;
	OutputStream& operator=(OutputStream const&) = delete;
	OutputStream& operator=(OutputStream&&) = delete;

public:
/** @name Constructors and destructor */ /// @{
	/**
		Constructor with type and streambuf.

		@param type Stream type.
		@param put_prefix Whether to write Pre::current.
	*/
	OutputStream(
		StreamType const type,
		bool const put_prefix
	) noexcept;

	// FIXME: Defect in libstdc++ 4.7.3: basic_ostream
	// move ctor is deleted and swap() is not defined
	/**
		Move constructor.

		@param other Stream to take ownership of.
	*/
	OutputStream(
		OutputStream&& other
	) noexcept
		//: base(std::move(other))
		: base(other.rdbuf())
		, m_type(other.m_type)
	{}

	/** Destructor. */
	~OutputStream() noexcept override {
		// Force-write streambuf to multicast streams
		static_cast<duct::IO::multistreambuf*>(
			this->rdbuf()
		)->multicast();
	}
/// @}

/** @name Properties */ /// @{
	/**
		Get stream type.
	*/
	StreamType
	get_type() const noexcept {
		return m_type;
	}
/// @}
};

/**
	Acquire log output stream for type.

	@param type Stream type.
*/
inline OutputStream
acquire(
	StreamType const type = Log::StreamType::general,
	bool const put_prefix = true
) noexcept {
	return OutputStream(type, put_prefix);
}

/** @cond INTERNAL */
OutputStream&
operator<<(
	OutputStream& stream,
	Pre prefix
);
/** @endcond */ // INTERNAL

/** @} */ // end of doc-group log
/** @} */ // end of doc-group etc

} // namespace Log
} // namespace Hord

#endif // HORD_LOG_HPP_
<commit_msg>doc: added missing description for put_prefix in Log::acquire().<commit_after>/**
@file Log.hpp
@brief Logging utilities.

@author Timothy Howard
@copyright 2013-2014 Timothy Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/

#ifndef HORD_LOG_HPP_
#define HORD_LOG_HPP_

#include <Hord/config.hpp>
#include <Hord/String.hpp>

#include <duct/StateStore.hpp>
#include <duct/IO/multistream.hpp>

#include <fstream>
#include <ostream>

namespace Hord {
namespace Log {

// TODO: Common output sentinels (e.g., current time in ISO-8601)
// TODO: Logging interface like exception throwing

// TODO: Datastores need to logify by roots.. somehow.
// Driver should probably manage that. Actually, Driver will
// probably be doing most of the Datastore logging anyways.

// TODO: Need to handle multi-threaded output to file stream properly
// FIXME: thread_local requires g++ 4.8!? (In Clang!)

// Forward declarations
class Controller;
class OutputStream;

/**
	@addtogroup etc
	@{
*/
/**
	@addtogroup log
	@{
*/

/**
	Stream type.
*/
enum StreamType : unsigned {
	general = 0u,
	debug,
	error,

/** @cond INTERNAL */
	LAST
/** @endcond */ // INTERNAL
};

/** Stream prefixes. */
enum class Pre : unsigned {
	general = 0u,
	debug,
	error,

	none,
	current,

/** @cond INTERNAL */
	LAST,
	LAST_TYPE = error
/** @endcond */ // INTERNAL
};

/** @cond INTERNAL */
enum : std::size_t {
	STREAMBUF_BUFFER_SIZE = 2048u
};

extern /*thread_local*/ Controller
s_controller;
/** @endcond */ // INTERNAL

/**
	Get the log controller.
*/
inline Controller&
get_controller() noexcept {
	return s_controller;
}

/**
	Log controller.
*/
class Controller final {
private:
	friend class OutputStream;

	/**
		State flags.
	*/
	enum class Flag : unsigned {
		write_stdout = 1 << 0,
		write_file = 1 << 1,
		write_datastore = 1 << 2
	};

	duct::StateStore<Flag> m_flags;
	String m_file_path;

	std::ofstream m_file_stream;
	char m_mc_buffer[STREAMBUF_BUFFER_SIZE];
	duct::IO::multicast_vector_type m_mc_vectors[
		static_cast<unsigned>(StreamType::LAST)
	];
	duct::IO::multistreambuf m_mc_streambufs[
		static_cast<unsigned>(StreamType::LAST)
	];

	/** Disable multicast to log file stream. */
	void
	disable_file_stream() noexcept;
	/** Enable multicast to log file stream. */
	void
	enable_file_stream() noexcept;

	/**
		Open the log file stream.

		@returns Whether the operation succeeded.
	*/
	bool
	open_file();

	/**
		Close the log file stream.

		@returns Whether the operation succeeded.
	*/
	bool
	close_file();

	Controller(Controller&&) = delete;
	Controller(Controller const&) = delete;
	Controller& operator=(Controller const&) = delete;
	Controller& operator=(Controller&&) = delete;

public:
/** @name Constructors and destructor */ /// @{
	/**
		Constructor with flags and log file path.

		@param enable_stdout Enable or disable standard output.
		@param enable_file Enable or disable log file output.
		@param enable_datastore Enable or disable datastore-local
		file output.
		@param path Log file path.
	*/
	Controller(
		bool const enable_stdout,
		bool const enable_file,
		bool const enable_datastore,
		String path
	) noexcept;

	/** Destructor. */
	~Controller() noexcept;
/// @}

/** @name Configuration */ /// @{
	/**
		Enable or disable standard output.

		@param enable Whether to enable or disable output.
	*/
	void
	stdout(
		bool const enable
	) noexcept;

	/**
		Check whether standard output is enabled.
	*/
	bool
	stdout_enabled() const noexcept {
		return m_flags.test(Flag::write_stdout);
	}

	/**
		Enable or disable file output.

		@returns
		- @c true if the operation succeeded (i.e., opening or closing
		  the log file stream);
		- @c false if the operation failed.
		@param enable Whether to enable or disable output.
	*/
	bool
	file(
		bool const enable
	) noexcept;

	/**
		Check whether file output is enabled.
	*/
	bool
	file_enabled() const noexcept {
		return m_flags.test(Flag::write_file);
	}

	/**
		Check whether the file stream is open.

		@remarks If this returns @c true, it implies
		file_enabled() == true.
	*/
	bool
	file_active() const noexcept {
		return m_file_stream.is_open();
	}

	/**
		Enable or disable datastore-local file output.

		@param enable Whether to enable or disable output.
	*/
	void
	datastore(
		bool const enable
	) noexcept;

	/**
		Check whether datastore-local file output is enabled.
	*/
	bool
	datastore_enabled() const noexcept {
		return m_flags.test(Flag::write_datastore);
	}

	/**
		Set the log file path.

		@remarks If the file stream is currently open, it is closed.
		If opening on @a path fails, @c false is returned, but file
		output is still enabled. If log file output is disabled,
		this only assigns the log file path.

		@returns
		- @c true if the file stream was successfully opened;
		- @c false if the file path could not be opened for writing.
		@param path Log file path.
	*/
	bool
	set_file_path(
		String path
	) noexcept;

	/**
		Get log file path.
	*/
	String const&
	get_file_path() const noexcept {
		return m_file_path;
	}
/// @}
};

/**
	Log output stream.
*/
class OutputStream final
	: public std::ostream
{
private:
	using base = std::ostream;

	StreamType const m_type;

	OutputStream() = delete;
	OutputStream(OutputStream const&) = delete;
	OutputStream& operator=(OutputStream const&) = delete;
	OutputStream& operator=(OutputStream&&) = delete;

public:
/** @name Constructors and destructor */ /// @{
	/**
		Constructor with type and streambuf.

		@param type Stream type.
		@param put_prefix Whether to write Pre::current.
	*/
	OutputStream(
		StreamType const type,
		bool const put_prefix
	) noexcept;

	// FIXME: Defect in libstdc++ 4.7.3: basic_ostream
	// move ctor is deleted and swap() is not defined
	/**
		Move constructor.

		@param other Stream to take ownership of.
	*/
	OutputStream(
		OutputStream&& other
	) noexcept
		//: base(std::move(other))
		: base(other.rdbuf())
		, m_type(other.m_type)
	{}

	/** Destructor. */
	~OutputStream() noexcept override {
		// Force-write streambuf to multicast streams
		static_cast<duct::IO::multistreambuf*>(
			this->rdbuf()
		)->multicast();
	}
/// @}

/** @name Properties */ /// @{
	/**
		Get stream type.
	*/
	StreamType
	get_type() const noexcept {
		return m_type;
	}
/// @}
};

/**
	Acquire log output stream for type.

	@param type Stream type.
	@param put_prefix Whether to put the current prefix before
	returning.
*/
inline OutputStream
acquire(
	StreamType const type = Log::StreamType::general,
	bool const put_prefix = true
) noexcept {
	return OutputStream(type, put_prefix);
}

/** @cond INTERNAL */
OutputStream&
operator<<(
	OutputStream& stream,
	Pre prefix
);
/** @endcond */ // INTERNAL

/** @} */ // end of doc-group log
/** @} */ // end of doc-group etc

} // namespace Log
} // namespace Hord

#endif // HORD_LOG_HPP_
<|endoftext|>


<commit_before><commit_msg>CWS-TOOLING: integrate CWS ab61 2009-01-29 09:39:19 +0100 jsk  r267096 : #i97038 2009-01-20 12:35:31 +0100 ab  r266568 : #i94994# Applied patch 2009-01-19 17:50:55 +0100 ab  r266514 : #i97038# Applied patch 2009-01-13 14:47:20 +0100 ab  r266226 : #i96087# Applied patch 2009-01-13 12:24:30 +0100 ab  r266207 : #i95200# Applied patch 2008-12-19 16:37:32 +0100 ab  r265735 : #i93214# Applied patch 2008-12-19 16:21:38 +0100 ab  r265730 : #i57749# Applied patch<commit_after><|endoftext|>