<commit_before>/*************************************************************************
*
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ScriptNameResolverImpl.hxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:33:28 $
 *
 *  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 _FRAMEWORK_SCRIPT_SCRIPTNAMERESOLVERIMPL_HXX_
#define  _FRAMEWORK_SCRIPT_SCRIPTNAMERESOLVERIMPL_HXX_

#include <cppuhelper/implbase1.hxx> // helper for XInterface, XTypeProvider etc.

#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/script/CannotConvertException.hpp>
#include <com/sun/star/reflection/InvocationTargetException.hpp>

#include <drafts/com/sun/star/script/framework/runtime/XScriptNameResolver.hpp>
#include <drafts/com/sun/star/script/framework/storage/XScriptInfoAccess.hpp>
#include <drafts/com/sun/star/script/framework/storage/XScriptInfo.hpp>

namespace scripting_runtimemgr
{
// for simplification
#define css ::com::sun::star
#define dcsssf ::drafts::com::sun::star::script::framework

class ScriptNameResolverImpl : public
    ::cppu::WeakImplHelper1 < dcsssf::runtime::XScriptNameResolver >
{
public:
    /**********************************************
     ScriptNameResolverImpl Constructor
     @param  the current context
    */
    ScriptNameResolverImpl(
        const css::uno::Reference< css::uno::XComponentContext > & xContext );
    ~ScriptNameResolverImpl();

    // XServiceInfo implementation
    virtual ::rtl::OUString SAL_CALL getImplementationName()
        throw( css::uno::RuntimeException );
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
        throw( css::uno::RuntimeException );
    virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
        throw( css::uno::RuntimeException );

    /**********************************************
     resolve method
     @param  scriptURI this is the given ScriptURI
     @param invocationCtx  the invocation context contains the
      documentStorageID and document reference for use in script name
      resolving. On full name resolution it sets the resolvedScriptStorageID to
      the actual storage location of the fully resolved script. May or may not * be the
      same as the documentStorageID.
     @exception CannotResolveScriptNameException
     @exception IllegalArgumentException
     @exception NullPointerException
     @return  the resolved XScriptURI
    */
    css::uno::Reference < dcsssf::storage::XScriptInfo > SAL_CALL resolve(
        const ::rtl::OUString & scriptURI,
        css::uno::Any& invocationCtx )
        throw( css::script::CannotConvertException, css::lang::IllegalArgumentException,
           css::uno::RuntimeException );
private:
    css::uno::Reference < dcsssf::storage::XScriptInfo >
    resolveURIFromStorageID( sal_Int32 sid, const rtl::OUString & docURI,
        const ::rtl::OUString & nameToResolve )
        SAL_THROW ( ( css::lang::IllegalArgumentException, css::uno::RuntimeException ) );
    css::uno::Reference< dcsssf::storage::XScriptInfoAccess >
    getStorageInstance( sal_Int32 sid, const rtl::OUString & permissionURI)
        SAL_THROW ( ( css::uno::RuntimeException ) );
    ::rtl::OUString
    ScriptNameResolverImpl::getFilesysURL( const ::rtl::OUString & scriptURI )
        throw( css::lang::IllegalArgumentException );

    /**********************************************
     Reference< XComponentContext > m_xContext
        to obtain other services if needed
    */
    css::uno::Reference< css::uno::XComponentContext > m_xContext;
    css::uno::Reference< css::lang::XMultiComponentFactory > m_xMultiComFac;
    ::osl::Mutex m_mutex;

};
} // scripting_runtimemgr

#endif //_FRAMEWORK_SCRIPT_SCRIPTNAMERESOLVERIMPL_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.14.108); FILE MERGED 2008/03/31 13:36:02 rt 1.14.108.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: ScriptNameResolverImpl.hxx,v $
 * $Revision: 1.15 $
 *
 * 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 _FRAMEWORK_SCRIPT_SCRIPTNAMERESOLVERIMPL_HXX_
#define  _FRAMEWORK_SCRIPT_SCRIPTNAMERESOLVERIMPL_HXX_

#include <cppuhelper/implbase1.hxx> // helper for XInterface, XTypeProvider etc.

#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/script/CannotConvertException.hpp>
#include <com/sun/star/reflection/InvocationTargetException.hpp>

#include <drafts/com/sun/star/script/framework/runtime/XScriptNameResolver.hpp>
#include <drafts/com/sun/star/script/framework/storage/XScriptInfoAccess.hpp>
#include <drafts/com/sun/star/script/framework/storage/XScriptInfo.hpp>

namespace scripting_runtimemgr
{
// for simplification
#define css ::com::sun::star
#define dcsssf ::drafts::com::sun::star::script::framework

class ScriptNameResolverImpl : public
    ::cppu::WeakImplHelper1 < dcsssf::runtime::XScriptNameResolver >
{
public:
    /**********************************************
     ScriptNameResolverImpl Constructor
     @param  the current context
    */
    ScriptNameResolverImpl(
        const css::uno::Reference< css::uno::XComponentContext > & xContext );
    ~ScriptNameResolverImpl();

    // XServiceInfo implementation
    virtual ::rtl::OUString SAL_CALL getImplementationName()
        throw( css::uno::RuntimeException );
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
        throw( css::uno::RuntimeException );
    virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
        throw( css::uno::RuntimeException );

    /**********************************************
     resolve method
     @param  scriptURI this is the given ScriptURI
     @param invocationCtx  the invocation context contains the
      documentStorageID and document reference for use in script name
      resolving. On full name resolution it sets the resolvedScriptStorageID to
      the actual storage location of the fully resolved script. May or may not * be the
      same as the documentStorageID.
     @exception CannotResolveScriptNameException
     @exception IllegalArgumentException
     @exception NullPointerException
     @return  the resolved XScriptURI
    */
    css::uno::Reference < dcsssf::storage::XScriptInfo > SAL_CALL resolve(
        const ::rtl::OUString & scriptURI,
        css::uno::Any& invocationCtx )
        throw( css::script::CannotConvertException, css::lang::IllegalArgumentException,
           css::uno::RuntimeException );
private:
    css::uno::Reference < dcsssf::storage::XScriptInfo >
    resolveURIFromStorageID( sal_Int32 sid, const rtl::OUString & docURI,
        const ::rtl::OUString & nameToResolve )
        SAL_THROW ( ( css::lang::IllegalArgumentException, css::uno::RuntimeException ) );
    css::uno::Reference< dcsssf::storage::XScriptInfoAccess >
    getStorageInstance( sal_Int32 sid, const rtl::OUString & permissionURI)
        SAL_THROW ( ( css::uno::RuntimeException ) );
    ::rtl::OUString
    ScriptNameResolverImpl::getFilesysURL( const ::rtl::OUString & scriptURI )
        throw( css::lang::IllegalArgumentException );

    /**********************************************
     Reference< XComponentContext > m_xContext
        to obtain other services if needed
    */
    css::uno::Reference< css::uno::XComponentContext > m_xContext;
    css::uno::Reference< css::lang::XMultiComponentFactory > m_xMultiComFac;
    ::osl::Mutex m_mutex;

};
} // scripting_runtimemgr

#endif //_FRAMEWORK_SCRIPT_SCRIPTNAMERESOLVERIMPL_HXX_
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#ifndef INCLUDED_CANVAS_BASE_CANVASCUSTOMSPRITEBASE_HXX
#define INCLUDED_CANVAS_BASE_CANVASCUSTOMSPRITEBASE_HXX

#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/rendering/XCustomSprite.hpp>
#include <com/sun/star/rendering/XPolyPolygon2D.hpp>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/vector/b2dvector.hxx>
#include <basegfx/range/b2drange.hxx>
#include <canvas/base/integerbitmapbase.hxx>
#include <canvas/base/sprite.hxx>

#include <boost/utility.hpp>

namespace canvas
{
    /** Helper template to handle XCustomSprite method forwarding to
        CanvasCustomSpriteHelper

        Use this helper to handle the XCustomSprite part of your
        implementation.

        @tpl Base
        Base class to use, most probably one of the
        WeakComponentImplHelperN templates with the appropriate
        interfaces. At least XCustomSprite and Sprite should be among
        them (why else would you use this template, then?). Base class
        must have an Base( const Mutex& ) constructor (like the
        WeakComponentImplHelperN templates have).

        @tpl SpriteHelper
        Sprite helper implementation for the backend in question

        @tpl CanvasHelper
        Canvas helper implementation for the backend in question

        @tpl Mutex
        Lock strategy to use. Defaults to using the
        OBaseMutex-provided lock.  Every time one of the methods is
        entered, an object of type Mutex is created with m_aMutex as
        the sole parameter, and destroyed again when the method scope
        is left.

        @tpl UnambiguousBase
        Optional unambiguous base class for XInterface of Base. It's
        sometimes necessary to specify this parameter, e.g. if Base
        derives from multiple UNO interface (were each provides its
        own version of XInterface, making the conversion ambiguous)

        @see CanvasCustomSpriteHelper for further contractual
        requirements towards the SpriteHelper type, and some examples.
     */
    template< class Base,
              class SpriteHelper,
              class CanvasHelper,
              class Mutex=::osl::MutexGuard,
              class UnambiguousBase=::com::sun::star::uno::XInterface > class CanvasCustomSpriteBase :
        public IntegerBitmapBase< BitmapCanvasBase2<Base, CanvasHelper, Mutex, UnambiguousBase> >
    {
    public:
        typedef IntegerBitmapBase< BitmapCanvasBase2<Base, CanvasHelper, Mutex, UnambiguousBase> > BaseType;
        typedef SpriteHelper                                                    SpriteHelperType;

        CanvasCustomSpriteBase() :
            maSpriteHelper()
        {
        }

        /** Object is being disposed.

            Called from the cppu helper base, to notify disposal of
            this object. Already releases all internal references.

            @derive when overriding this method in derived classes,
            always call the base class' method!
         */
        virtual void disposeThis() SAL_OVERRIDE
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maSpriteHelper.disposing();

            // pass on to base class
            BaseType::disposeThis();
        }

        // XCanvas: selectively override base's methods here, for opacity tracking
        virtual void SAL_CALL clear() throw (::com::sun::star::uno::RuntimeException) SAL_OVERRIDE
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maSpriteHelper.clearingContent( this );

            // and forward to base class, which handles the actual rendering
            return BaseType::clear();
        }

        virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XCachedPrimitive > SAL_CALL
            drawBitmap( const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBitmap >& xBitmap,
                        const ::com::sun::star::rendering::ViewState&                                   viewState,
                        const ::com::sun::star::rendering::RenderState&                                 renderState ) throw (::com::sun::star::lang::IllegalArgumentException,
                                                                                ::com::sun::star::uno::RuntimeException) SAL_OVERRIDE
        {
            tools::verifyArgs(xBitmap, viewState, renderState,
                              BOOST_CURRENT_FUNCTION,
                              static_cast< typename BaseType::UnambiguousBaseType* >(this));

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maSpriteHelper.checkDrawBitmap( this, xBitmap, viewState, renderState );

            // and forward to base class, which handles the actual rendering
            return BaseType::drawBitmap( xBitmap,
                                         viewState,
                                         renderState );
        }

        // TODO(F3): If somebody uses the XIntegerBitmap methods to
        // clear pixel (setting alpha != 1.0 there), or a compositing
        // mode results in similar alpha, maSpriteHelper might
        // errorneously report fully opaque sprites. Effectively, all
        // render methods must be overridden here; or better,
        // functionality provided at the baseclass.

        // XSprite
        virtual void SAL_CALL setAlpha( double alpha ) throw (::com::sun::star::lang::IllegalArgumentException,
                                                              ::com::sun::star::uno::RuntimeException) SAL_OVERRIDE
        {
            tools::verifyRange( alpha, 0.0, 1.0 );

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maSpriteHelper.setAlpha( this, alpha );
        }

        virtual void SAL_CALL move( const ::com::sun::star::geometry::RealPoint2D&  aNewPos,
                                    const ::com::sun::star::rendering::ViewState&   viewState,
                                    const ::com::sun::star::rendering::RenderState& renderState ) throw (::com::sun::star::lang::IllegalArgumentException,
                                                                                ::com::sun::star::uno::RuntimeException) SAL_OVERRIDE
        {
            tools::verifyArgs(aNewPos, viewState, renderState,
                              BOOST_CURRENT_FUNCTION,
                              static_cast< typename BaseType::UnambiguousBaseType* >(this));

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maSpriteHelper.move( this, aNewPos, viewState, renderState );
        }

        virtual void SAL_CALL transform( const ::com::sun::star::geometry::AffineMatrix2D& aTransformation ) throw (::com::sun::star::lang::IllegalArgumentException,
                                                                                ::com::sun::star::uno::RuntimeException) SAL_OVERRIDE
        {
            tools::verifyArgs(aTransformation,
                              BOOST_CURRENT_FUNCTION,
                              static_cast< typename BaseType::UnambiguousBaseType* >(this));

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maSpriteHelper.transform( this, aTransformation );
        }

        virtual void SAL_CALL clip( const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D >& aClip ) throw (::com::sun::star::uno::RuntimeException) SAL_OVERRIDE
        {
            // NULL xClip explicitly allowed here (to clear clipping)

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maSpriteHelper.clip( this, aClip );
        }

        virtual void SAL_CALL setPriority( double nPriority ) throw (::com::sun::star::uno::RuntimeException) SAL_OVERRIDE
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maSpriteHelper.setPriority( this, nPriority );
        }

        virtual void SAL_CALL show() throw (::com::sun::star::uno::RuntimeException) SAL_OVERRIDE
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maSpriteHelper.show( this );
        }

        virtual void SAL_CALL hide() throw (::com::sun::star::uno::RuntimeException) SAL_OVERRIDE
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maSpriteHelper.hide( this );
        }

        // XCustomSprite
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XCanvas > SAL_CALL
            getContentCanvas() throw (::com::sun::star::uno::RuntimeException) SAL_OVERRIDE
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return this;
        }

        // Sprite
        virtual bool isAreaUpdateOpaque( const ::basegfx::B2DRange& rUpdateArea ) const
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return maSpriteHelper.isAreaUpdateOpaque( rUpdateArea );
        }

        virtual bool isContentChanged() const
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return BaseType::mbSurfaceDirty;
        }

        virtual ::basegfx::B2DPoint getPosPixel() const
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return maSpriteHelper.getPosPixel();
        }

        virtual ::basegfx::B2DVector getSizePixel() const
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return maSpriteHelper.getSizePixel();
        }

        virtual ::basegfx::B2DRange getUpdateArea() const
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return maSpriteHelper.getUpdateArea();
        }

        virtual double getPriority() const
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return maSpriteHelper.getPriority();
        }

    protected:
        SpriteHelperType maSpriteHelper;
    };
}

#endif // INCLUDED_CANVAS_BASE_CANVASCUSTOMSPRITEBASE_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#1213450 Uncaught exception<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#ifndef INCLUDED_CANVAS_BASE_CANVASCUSTOMSPRITEBASE_HXX
#define INCLUDED_CANVAS_BASE_CANVASCUSTOMSPRITEBASE_HXX

#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/rendering/XCustomSprite.hpp>
#include <com/sun/star/rendering/XPolyPolygon2D.hpp>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/vector/b2dvector.hxx>
#include <basegfx/range/b2drange.hxx>
#include <canvas/base/integerbitmapbase.hxx>
#include <canvas/base/sprite.hxx>

#include <boost/utility.hpp>

namespace canvas
{
    /** Helper template to handle XCustomSprite method forwarding to
        CanvasCustomSpriteHelper

        Use this helper to handle the XCustomSprite part of your
        implementation.

        @tpl Base
        Base class to use, most probably one of the
        WeakComponentImplHelperN templates with the appropriate
        interfaces. At least XCustomSprite and Sprite should be among
        them (why else would you use this template, then?). Base class
        must have an Base( const Mutex& ) constructor (like the
        WeakComponentImplHelperN templates have).

        @tpl SpriteHelper
        Sprite helper implementation for the backend in question

        @tpl CanvasHelper
        Canvas helper implementation for the backend in question

        @tpl Mutex
        Lock strategy to use. Defaults to using the
        OBaseMutex-provided lock.  Every time one of the methods is
        entered, an object of type Mutex is created with m_aMutex as
        the sole parameter, and destroyed again when the method scope
        is left.

        @tpl UnambiguousBase
        Optional unambiguous base class for XInterface of Base. It's
        sometimes necessary to specify this parameter, e.g. if Base
        derives from multiple UNO interface (were each provides its
        own version of XInterface, making the conversion ambiguous)

        @see CanvasCustomSpriteHelper for further contractual
        requirements towards the SpriteHelper type, and some examples.
     */
    template< class Base,
              class SpriteHelper,
              class CanvasHelper,
              class Mutex=::osl::MutexGuard,
              class UnambiguousBase=::com::sun::star::uno::XInterface > class CanvasCustomSpriteBase :
        public IntegerBitmapBase< BitmapCanvasBase2<Base, CanvasHelper, Mutex, UnambiguousBase> >
    {
    public:
        typedef IntegerBitmapBase< BitmapCanvasBase2<Base, CanvasHelper, Mutex, UnambiguousBase> > BaseType;
        typedef SpriteHelper                                                    SpriteHelperType;

        CanvasCustomSpriteBase() :
            maSpriteHelper()
        {
        }

        /** Object is being disposed.

            Called from the cppu helper base, to notify disposal of
            this object. Already releases all internal references.

            @derive when overriding this method in derived classes,
            always call the base class' method!
         */
        virtual void disposeThis() SAL_OVERRIDE
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maSpriteHelper.disposing();

            // pass on to base class
            BaseType::disposeThis();
        }

        // XCanvas: selectively override base's methods here, for opacity tracking
        virtual void SAL_CALL clear() throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maSpriteHelper.clearingContent( this );

            // and forward to base class, which handles the actual rendering
            return BaseType::clear();
        }

        virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XCachedPrimitive > SAL_CALL
            drawBitmap( const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBitmap >& xBitmap,
                        const ::com::sun::star::rendering::ViewState&                                   viewState,
                        const ::com::sun::star::rendering::RenderState&                                 renderState ) throw (::com::sun::star::lang::IllegalArgumentException,
                                                                                ::com::sun::star::uno::RuntimeException) SAL_OVERRIDE
        {
            tools::verifyArgs(xBitmap, viewState, renderState,
                              BOOST_CURRENT_FUNCTION,
                              static_cast< typename BaseType::UnambiguousBaseType* >(this));

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maSpriteHelper.checkDrawBitmap( this, xBitmap, viewState, renderState );

            // and forward to base class, which handles the actual rendering
            return BaseType::drawBitmap( xBitmap,
                                         viewState,
                                         renderState );
        }

        // TODO(F3): If somebody uses the XIntegerBitmap methods to
        // clear pixel (setting alpha != 1.0 there), or a compositing
        // mode results in similar alpha, maSpriteHelper might
        // errorneously report fully opaque sprites. Effectively, all
        // render methods must be overridden here; or better,
        // functionality provided at the baseclass.

        // XSprite
        virtual void SAL_CALL setAlpha( double alpha ) throw (::com::sun::star::lang::IllegalArgumentException,
                                                              ::com::sun::star::uno::RuntimeException) SAL_OVERRIDE
        {
            tools::verifyRange( alpha, 0.0, 1.0 );

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maSpriteHelper.setAlpha( this, alpha );
        }

        virtual void SAL_CALL move( const ::com::sun::star::geometry::RealPoint2D&  aNewPos,
                                    const ::com::sun::star::rendering::ViewState&   viewState,
                                    const ::com::sun::star::rendering::RenderState& renderState ) throw (::com::sun::star::lang::IllegalArgumentException,
                                                                                ::com::sun::star::uno::RuntimeException) SAL_OVERRIDE
        {
            tools::verifyArgs(aNewPos, viewState, renderState,
                              BOOST_CURRENT_FUNCTION,
                              static_cast< typename BaseType::UnambiguousBaseType* >(this));

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maSpriteHelper.move( this, aNewPos, viewState, renderState );
        }

        virtual void SAL_CALL transform( const ::com::sun::star::geometry::AffineMatrix2D& aTransformation ) throw (::com::sun::star::lang::IllegalArgumentException,
                                                                                ::com::sun::star::uno::RuntimeException) SAL_OVERRIDE
        {
            tools::verifyArgs(aTransformation,
                              BOOST_CURRENT_FUNCTION,
                              static_cast< typename BaseType::UnambiguousBaseType* >(this));

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maSpriteHelper.transform( this, aTransformation );
        }

        virtual void SAL_CALL clip( const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D >& aClip ) throw (::com::sun::star::uno::RuntimeException) SAL_OVERRIDE
        {
            // NULL xClip explicitly allowed here (to clear clipping)

            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maSpriteHelper.clip( this, aClip );
        }

        virtual void SAL_CALL setPriority( double nPriority ) throw (::com::sun::star::uno::RuntimeException) SAL_OVERRIDE
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maSpriteHelper.setPriority( this, nPriority );
        }

        virtual void SAL_CALL show() throw (::com::sun::star::uno::RuntimeException) SAL_OVERRIDE
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maSpriteHelper.show( this );
        }

        virtual void SAL_CALL hide() throw (::com::sun::star::uno::RuntimeException) SAL_OVERRIDE
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            maSpriteHelper.hide( this );
        }

        // XCustomSprite
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XCanvas > SAL_CALL
            getContentCanvas() throw (::com::sun::star::uno::RuntimeException) SAL_OVERRIDE
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return this;
        }

        // Sprite
        virtual bool isAreaUpdateOpaque( const ::basegfx::B2DRange& rUpdateArea ) const
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return maSpriteHelper.isAreaUpdateOpaque( rUpdateArea );
        }

        virtual bool isContentChanged() const
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return BaseType::mbSurfaceDirty;
        }

        virtual ::basegfx::B2DPoint getPosPixel() const
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return maSpriteHelper.getPosPixel();
        }

        virtual ::basegfx::B2DVector getSizePixel() const
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return maSpriteHelper.getSizePixel();
        }

        virtual ::basegfx::B2DRange getUpdateArea() const
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return maSpriteHelper.getUpdateArea();
        }

        virtual double getPriority() const
        {
            typename BaseType::MutexType aGuard( BaseType::m_aMutex );

            return maSpriteHelper.getPriority();
        }

    protected:
        SpriteHelperType maSpriteHelper;
    };
}

#endif // INCLUDED_CANVAS_BASE_CANVASCUSTOMSPRITEBASE_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: CRC32.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 16:11:18 $
 *
 *  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 _CRC32_HXX
#include <CRC32.hxx>
#endif
#ifndef _ZLIB_H
#ifdef SYSTEM_ZLIB
#include <zlib.h>
#else
#include <external/zlib/zlib.h>
#endif
#endif
#ifndef _PACKAGE_CONSTANTS_HXX_
#include <PackageConstants.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif

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

/** A class to compute the CRC32 value of a data stream
 */

CRC32::CRC32()
: nCRC(0)
{
}
CRC32::~CRC32()
{
}
void SAL_CALL CRC32::reset()
    throw(RuntimeException)
{
    nCRC=0;
}
sal_Int32 SAL_CALL CRC32::getValue()
    throw(RuntimeException)
{
    return nCRC & 0xFFFFFFFFL;
}
/** Update CRC32 with specified byte
 */
void SAL_CALL CRC32::updateByte (sal_Int8 nByte)
        throw(RuntimeException)
{
    sal_uInt8 pBuf[1];
    pBuf[0] = (sal_uInt8)nByte;
    nCRC  = crc32(nCRC, pBuf, 1);
}
/** Update CRC32 with specified sequence of bytes
 */
void SAL_CALL CRC32::updateSegment(const Sequence< sal_Int8 > &b,
                                    sal_Int32 off,
                                    sal_Int32 len)
        throw(RuntimeException)
{
    nCRC = crc32(nCRC, (const unsigned char*)b.getConstArray()+off, len );
}
/** Update CRC32 with specified sequence of bytes
 */
void SAL_CALL CRC32::update(const Sequence< sal_Int8 > &b)
        throw(RuntimeException)
{
    nCRC = crc32(nCRC, (const unsigned char*)b.getConstArray(),b.getLength());
}

sal_Int32 SAL_CALL CRC32::updateStream( Reference < XInputStream > & xStream )
    throw ( RuntimeException )
{
    sal_Int32 nLength, nTotal = 0;
    Sequence < sal_Int8 > aSeq ( n_ConstBufferSize );
    do
    {
        nLength = xStream->readBytes ( aSeq, n_ConstBufferSize );
        updateSegment ( aSeq, 0, nLength );
        nTotal += nLength;
    }
    while ( nLength == n_ConstBufferSize );

    return nTotal;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.11.44); FILE MERGED 2006/09/01 17:32:41 kaib 1.11.44.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: CRC32.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 17:26:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_package.hxx"
#ifndef _CRC32_HXX
#include <CRC32.hxx>
#endif
#ifndef _ZLIB_H
#ifdef SYSTEM_ZLIB
#include <zlib.h>
#else
#include <external/zlib/zlib.h>
#endif
#endif
#ifndef _PACKAGE_CONSTANTS_HXX_
#include <PackageConstants.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif

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

/** A class to compute the CRC32 value of a data stream
 */

CRC32::CRC32()
: nCRC(0)
{
}
CRC32::~CRC32()
{
}
void SAL_CALL CRC32::reset()
    throw(RuntimeException)
{
    nCRC=0;
}
sal_Int32 SAL_CALL CRC32::getValue()
    throw(RuntimeException)
{
    return nCRC & 0xFFFFFFFFL;
}
/** Update CRC32 with specified byte
 */
void SAL_CALL CRC32::updateByte (sal_Int8 nByte)
        throw(RuntimeException)
{
    sal_uInt8 pBuf[1];
    pBuf[0] = (sal_uInt8)nByte;
    nCRC  = crc32(nCRC, pBuf, 1);
}
/** Update CRC32 with specified sequence of bytes
 */
void SAL_CALL CRC32::updateSegment(const Sequence< sal_Int8 > &b,
                                    sal_Int32 off,
                                    sal_Int32 len)
        throw(RuntimeException)
{
    nCRC = crc32(nCRC, (const unsigned char*)b.getConstArray()+off, len );
}
/** Update CRC32 with specified sequence of bytes
 */
void SAL_CALL CRC32::update(const Sequence< sal_Int8 > &b)
        throw(RuntimeException)
{
    nCRC = crc32(nCRC, (const unsigned char*)b.getConstArray(),b.getLength());
}

sal_Int32 SAL_CALL CRC32::updateStream( Reference < XInputStream > & xStream )
    throw ( RuntimeException )
{
    sal_Int32 nLength, nTotal = 0;
    Sequence < sal_Int8 > aSeq ( n_ConstBufferSize );
    do
    {
        nLength = xStream->readBytes ( aSeq, n_ConstBufferSize );
        updateSegment ( aSeq, 0, nLength );
        nTotal += nLength;
    }
    while ( nLength == n_ConstBufferSize );

    return nTotal;
}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_PROB_NEG_BINOMIAL_2_LPMF_HPP
#define STAN_MATH_PRIM_PROB_NEG_BINOMIAL_2_LPMF_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/binomial_coefficient_log.hpp>
#include <stan/math/prim/fun/digamma.hpp>
#include <stan/math/prim/fun/lgamma.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/max_size.hpp>
#include <stan/math/prim/fun/multiply_log.hpp>
#include <stan/math/prim/fun/size.hpp>
#include <stan/math/prim/fun/size_zero.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <stan/math/prim/prob/poisson_lpmf.hpp>
#include <cmath>

namespace stan {
namespace math {

// NegBinomial(n|mu, phi)  [mu >= 0; phi > 0;  n >= 0]
template <bool propto, typename T_n, typename T_location, typename T_precision>
return_type_t<T_location, T_precision> neg_binomial_2_lpmf(
    const T_n& n, const T_location& mu, const T_precision& phi) {
  using T_partials_return = partials_return_t<T_n, T_location, T_precision>;
  using std::log;
  static const char* function = "neg_binomial_2_lpmf";
  check_nonnegative(function, "Failures variable", n);
  check_positive_finite(function, "Location parameter", mu);
  check_positive_finite(function, "Precision parameter", phi);
  check_consistent_sizes(function, "Failures variable", n, "Location parameter",
                         mu, "Precision parameter", phi);

  if (size_zero(n, mu, phi)) {
    return 0.0;
  }
  if (!include_summand<propto, T_location, T_precision>::value) {
    return 0.0;
  }

  T_partials_return logp(0.0);
  operands_and_partials<T_location, T_precision> ops_partials(mu, phi);

  scalar_seq_view<T_n> n_vec(n);
  scalar_seq_view<T_location> mu_vec(mu);
  scalar_seq_view<T_precision> phi_vec(phi);
  size_t size_mu = stan::math::size(mu);
  size_t size_phi = stan::math::size(phi);
  size_t size_mu_phi = max_size(mu, phi);
  size_t size_n_phi = max_size(n, phi);
  size_t size_all = max_size(n, mu, phi);

  VectorBuilder<true, T_partials_return, T_location> mu_val(size_mu);
  for (size_t i = 0; i < size_mu; ++i) {
    mu_val[i] = value_of(mu_vec[i]);
  }

  VectorBuilder<true, T_partials_return, T_precision> phi_val(size_phi);
  VectorBuilder<true, T_partials_return, T_precision> log_phi(size_phi);
  for (size_t i = 0; i < size_phi; ++i) {
    phi_val[i] = value_of(phi_vec[i]);
    log_phi[i] = log(phi_val[i]);
  }

  VectorBuilder<true, T_partials_return, T_location, T_precision> mu_plus_phi(
      size_mu_phi);
  VectorBuilder<true, T_partials_return, T_location, T_precision>
      log_mu_plus_phi(size_mu_phi);
  for (size_t i = 0; i < size_mu_phi; ++i) {
    mu_plus_phi[i] = mu_val[i] + phi_val[i];
    log_mu_plus_phi[i] = log(mu_plus_phi[i]);
  }

  VectorBuilder<true, T_partials_return, T_n, T_precision> n_plus_phi(
      size_n_phi);
  for (size_t i = 0; i < size_n_phi; ++i) {
    n_plus_phi[i] = n_vec[i] + phi_val[i];
  }

  for (size_t i = 0; i < size_all; i++) {
    if (include_summand<propto, T_precision>::value) {
      logp += binomial_coefficient_log(n_plus_phi[i] - 1, n_vec[i]);
    }
    if (include_summand<propto, T_location>::value) {
      logp += multiply_log(n_vec[i], mu_val[i]);
    }
    logp += -phi_val[i] * (log1p(mu_val[i] / phi_val[i]))
            - n_vec[i] * log_mu_plus_phi[i];

    if (!is_constant_all<T_location>::value) {
      ops_partials.edge1_.partials_[i]
          += n_vec[i] / mu_val[i] - (n_vec[i] + phi_val[i]) / (mu_plus_phi[i]);
    }
    if (!is_constant_all<T_precision>::value) {
      T_partials_return log_term;
      if (mu_val[i] < phi_val[i]) {
        log_term = log1p(-mu_val[i] / (mu_plus_phi[i]));
      } else {
        log_term = log_phi[i] - log_mu_plus_phi[i];
      }
      ops_partials.edge2_.partials_[i]
          += (mu_val[i] - n_vec[i]) / (mu_plus_phi[i]) + log_term
             - (digamma(phi_val[i]) - digamma(n_plus_phi[i]));
    }
  }
  return ops_partials.build(logp);
}

template <typename T_n, typename T_location, typename T_precision>
inline return_type_t<T_location, T_precision> neg_binomial_2_lpmf(
    const T_n& n, const T_location& mu, const T_precision& phi) {
  return neg_binomial_2_lpmf<false>(n, mu, phi);
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>Removed unused headers<commit_after>#ifndef STAN_MATH_PRIM_PROB_NEG_BINOMIAL_2_LPMF_HPP
#define STAN_MATH_PRIM_PROB_NEG_BINOMIAL_2_LPMF_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/binomial_coefficient_log.hpp>
#include <stan/math/prim/fun/digamma.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/max_size.hpp>
#include <stan/math/prim/fun/multiply_log.hpp>
#include <stan/math/prim/fun/size.hpp>
#include <stan/math/prim/fun/size_zero.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <cmath>

namespace stan {
namespace math {

// NegBinomial(n|mu, phi)  [mu >= 0; phi > 0;  n >= 0]
template <bool propto, typename T_n, typename T_location, typename T_precision>
return_type_t<T_location, T_precision> neg_binomial_2_lpmf(
    const T_n& n, const T_location& mu, const T_precision& phi) {
  using T_partials_return = partials_return_t<T_n, T_location, T_precision>;
  using std::log;
  static const char* function = "neg_binomial_2_lpmf";
  check_nonnegative(function, "Failures variable", n);
  check_positive_finite(function, "Location parameter", mu);
  check_positive_finite(function, "Precision parameter", phi);
  check_consistent_sizes(function, "Failures variable", n, "Location parameter",
                         mu, "Precision parameter", phi);

  if (size_zero(n, mu, phi)) {
    return 0.0;
  }
  if (!include_summand<propto, T_location, T_precision>::value) {
    return 0.0;
  }

  T_partials_return logp(0.0);
  operands_and_partials<T_location, T_precision> ops_partials(mu, phi);

  scalar_seq_view<T_n> n_vec(n);
  scalar_seq_view<T_location> mu_vec(mu);
  scalar_seq_view<T_precision> phi_vec(phi);
  size_t size_mu = stan::math::size(mu);
  size_t size_phi = stan::math::size(phi);
  size_t size_mu_phi = max_size(mu, phi);
  size_t size_n_phi = max_size(n, phi);
  size_t size_all = max_size(n, mu, phi);

  VectorBuilder<true, T_partials_return, T_location> mu_val(size_mu);
  for (size_t i = 0; i < size_mu; ++i) {
    mu_val[i] = value_of(mu_vec[i]);
  }

  VectorBuilder<true, T_partials_return, T_precision> phi_val(size_phi);
  VectorBuilder<true, T_partials_return, T_precision> log_phi(size_phi);
  for (size_t i = 0; i < size_phi; ++i) {
    phi_val[i] = value_of(phi_vec[i]);
    log_phi[i] = log(phi_val[i]);
  }

  VectorBuilder<true, T_partials_return, T_location, T_precision> mu_plus_phi(
      size_mu_phi);
  VectorBuilder<true, T_partials_return, T_location, T_precision>
      log_mu_plus_phi(size_mu_phi);
  for (size_t i = 0; i < size_mu_phi; ++i) {
    mu_plus_phi[i] = mu_val[i] + phi_val[i];
    log_mu_plus_phi[i] = log(mu_plus_phi[i]);
  }

  VectorBuilder<true, T_partials_return, T_n, T_precision> n_plus_phi(
      size_n_phi);
  for (size_t i = 0; i < size_n_phi; ++i) {
    n_plus_phi[i] = n_vec[i] + phi_val[i];
  }

  for (size_t i = 0; i < size_all; i++) {
    if (include_summand<propto, T_precision>::value) {
      logp += binomial_coefficient_log(n_plus_phi[i] - 1, n_vec[i]);
    }
    if (include_summand<propto, T_location>::value) {
      logp += multiply_log(n_vec[i], mu_val[i]);
    }
    logp += -phi_val[i] * (log1p(mu_val[i] / phi_val[i]))
            - n_vec[i] * log_mu_plus_phi[i];

    if (!is_constant_all<T_location>::value) {
      ops_partials.edge1_.partials_[i]
          += n_vec[i] / mu_val[i] - (n_vec[i] + phi_val[i]) / (mu_plus_phi[i]);
    }
    if (!is_constant_all<T_precision>::value) {
      T_partials_return log_term;
      if (mu_val[i] < phi_val[i]) {
        log_term = log1p(-mu_val[i] / (mu_plus_phi[i]));
      } else {
        log_term = log_phi[i] - log_mu_plus_phi[i];
      }
      ops_partials.edge2_.partials_[i]
          += (mu_val[i] - n_vec[i]) / (mu_plus_phi[i]) + log_term
             - (digamma(phi_val[i]) - digamma(n_plus_phi[i]));
    }
  }
  return ops_partials.build(logp);
}

template <typename T_n, typename T_location, typename T_precision>
inline return_type_t<T_location, T_precision> neg_binomial_2_lpmf(
    const T_n& n, const T_location& mu, const T_precision& phi) {
  return neg_binomial_2_lpmf<false>(n, mu, phi);
}

}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#ifndef INCLUDED_COMPHELPER_IMPLEMENTATIONREFERENCE_HXX
#define INCLUDED_COMPHELPER_IMPLEMENTATIONREFERENCE_HXX

#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/uno/XInterface.hpp>

namespace comphelper
{

    /** Holds a uno::Reference alongside a C++ implementation pointer

        This template is useful to accomplish the following task: the
        client needs an implementation pointer to an object providing
        UNO interfaces. It is unsafe to simply store a C++ pointer,
        because of the automatic UNO lifetime control. It is
        inconvenient to always cast the UNO interface to the C++
        implementation, and what's more, it's mostly unclear to the
        casual code reader.

        Thus, this template nicely encapsulate the stated intention,
        by holding a uno::Reference internally, and providing simple
        C++ pointer semantics to the outside. As a differentiator to
        ::rtl::Reference, this template features a getRef() method,
        giving you friction-less access to the internal UNO interface,
        without extra querying.

        By the way, the pointer semantic of this template include
        transitive constness. That means, if this template's instance
        is const (e.g. because it is a member of a class which is
        accessed in a const method), the pointer returned is also
        const.

        As this template is geared towards fast, internal pointer
        access, validity of the UNO reference is _not_ checked for
        every pointer access. The client of this template is
        responsible to check that, wherever necessary, via the is()
        method.

        @tpl CppType
        The C++ type this class should mimick a pointer to (not the
        pointer type itself!).

        @tpl UnoType
        The UNO interface type of the object (a uno::Reference to this
        type is held internally).

        @tpl XIfType
        An unambiguous derivative of UnoType. This is defaulted to
        the second template parameter (UnoType), which should normally
        just work, since one typically has only single inheritance in
        UNO.<p>
        Alternatively, when using the
        ImplementationReference::createFromQuery() method to create an
        instance, this type can serve a different need: if the
        provided CppType only derives from XInterface (generally
        speaking, derives from a UNO interface above UnoType in the
        class hierarchy), then the default XIfType constitutes a
        possibly invalid downcast to UnoType. Setting XIfType equal to
        CppTypes's most derived UNO interface type then solves this
        problem (which is not as arcane as it seems to be. Just
        imagine you're providing a C++ abstract interface, which must
        provide UNO reference semantics. Naturally, you will derive
        this C++ interface only from XInterface, to reduce the number
        of ambiguous classes. Even more naturally, it is reasonable to
        have UnoType be something different from XInterface, governed
        by the usage of the C++ interface)

        @sample ImplementationReference< MyCppType, XMyInterface >

        @sample ImplementationReference< MyAbstractCppType, XMyInterface, XInterface >
        for an abstract C++ class

        @see ::rtl::Reference

     */
    template < class CppType,
               class UnoType,
               class XIfType=UnoType > class ImplementationReference
    {
    public:

        typedef UnoType UnoInterfaceType;
        typedef CppType ImplementationType;
        typedef XIfType UnambiguousXInterfaceType;

        /** Default-construct an ImplementationReference

            Uno reference will be invalid, implementation pointer will
            be NULL.
         */
        ImplementationReference() :
            mxRef(),
            mpImpl( NULL )
        {
        }

        /** Create an ImplementationReference from C++ pointer.

            This constructor does not perform an explicit
            QueryInterface on the provided implementation object, but
            constructs the UNO reference directly from the given
            pointer. This is the fastest, and most often the best way
            to create an ImplementationReference. If the conversion
            between the implementation object and the required UNO
            interface is ambiguous, provide the third template
            parameter with a type that can be unambiguously upcasted
            to the UNO interface (the second template parameter).

            There are cases, however, where performing a
            QueryInterface is the better, albeit slower choice. In
            these cases, createFromQuery() should be used.

            @param pImpl
            Pointer to the C++ implementation type

            @see createFromQuery()
        */
        explicit ImplementationReference( ImplementationType* pImpl ) :
            mxRef( static_cast<UnambiguousXInterfaceType*>(pImpl) ),
            mpImpl( pImpl )
        {
        }

        struct CreateFromQuery { };
        /** Create an ImplementationReference from C++ pointer

            @param pImpl
            The pointer to the C++ implementation type, which is
            queried for the template-parameterized UNO type.

            @param dummy
            Dummy parameter, to distinguish this contructor from the
            default unary one (which does not perform a
            QueryInterface)
         */
        ImplementationReference( ImplementationType* pImpl, CreateFromQuery ) :
            mxRef( static_cast<UnambiguousXInterfaceType*>(pImpl),
                   ::com::sun::star::uno::UNO_QUERY ),
            mpImpl( pImpl )
        {
        }

        /** Factory method to create an ImplementationReference from
            C++ pointer.

            This is a static version of the constructor which creates
            an instance of an implementation type which is explicitly
            queried for the ImplementationReference's
            template-parameterized UNO type.

            @sample
                mpRef = mpRef.createFromQuery( new ImplementationType );
        */
        static ImplementationReference createFromQuery( ImplementationType* pImpl )
        {
            return ImplementationReference( pImpl, CreateFromQuery() );
        }

        /** Query whether the pointer is still valid.

            Hands off also from the implementation pointer if this
            returns false!
         */
        bool is() const { return mxRef.is(); }

        /** Get a pointer to the implementation object

            Compatibility method to get an auto_ptr-compatible
            interface
         */
        ImplementationType*         get() { return mpImpl; }
        const ImplementationType*   get() const { return mpImpl; }

        /** Release all references

            Compatibility method to get an auto_ptr-compatible
            interface
         */
        void                        reset() { dispose(); }

        /** Release all references

            This method releases the UNO interface reference, and
            clears the C++ pointer to NULL.
         */
        void                        dispose() { mxRef = NULL; mpImpl=NULL; }

        ImplementationType*         operator->() { return mpImpl; }
        const ImplementationType*   operator->() const { return mpImpl; }

        ImplementationType&         operator*() { return *mpImpl; }
        const ImplementationType&   operator*() const { return *mpImpl; }

        /// Access to the underlying UNO reference, without extra querying
        ::com::sun::star::uno::Reference< UnoInterfaceType > getRef() { return mxRef; }

        /// Access to the underlying UNO reference, without extra querying
        const ::com::sun::star::uno::Reference< UnoInterfaceType >& getRef() const { return mxRef; }

        // default destructor, copy constructor and assignment will do
        // ~ImplementationReference();
        // ImplementationReference( const ImplementationReference& );
        // ImplementationReference& operator= ( const ImplementationReference& );

        /** Comparison operator

            Object identity is defined to be identity of the
            implementation pointers. This is in general invalid when
            comparing pointers to UNO objects (ambiguous class
            hierarchies, optimizations in the bridges, etc.), but okay
            for raw C++ pointers (which is what's compared herein).
        */
        bool operator==( const ImplementationReference& rhs ) const
        {
            return mpImpl == rhs.mpImpl;
        }

        /** less-than operator

            Object order is defined to be the ordering of the
            implementation pointers. This is in general invalid when
            comparing pointers to UNO objects (ambiguous class
            hierarchies, optimizations in the bridges, etc.), but okay
            for raw C++ pointers (which is what's used herein).

            This ordering complies with STL's strict weak ordering
            concept.
        */
        bool operator<( const ImplementationReference& rhs ) const
        {
            return mpImpl < rhs.mpImpl;
        }

    private:

        // the interface, hard reference to prevent object from vanishing
        ::com::sun::star::uno::Reference< UnoInterfaceType >    mxRef;

        // the c++ object, for our internal stuff
        ImplementationType*                                     mpImpl;

    };

}

#endif // INCLUDED_COMPHELPER_IMPLEMENTATIONREFERENCE_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Remove newly unused comphelper::ImplementationReference<commit_after><|endoftext|>


<commit_before>#ifndef __MULTIDIMENSIONAL_ARRAY__ARRAY_IMPL_HPP__
#define __MULTIDIMENSIONAL_ARRAY__ARRAY_IMPL_HPP__

#include "array.hpp"

namespace MultidimensionalArray {
  template <class T>
  Array<T>::Array():
    values_(nullptr),
    deallocate_on_destruction_(true) { }

  template <class T>
  Array<T>::Array(T const& other):
    values_(new T[1]),
    size_({1}),
    deallocate_on_destruction_(true) {
      values_[0] = other;
    }

  template <class T>
  Array<T>::Array(T&& other):
    values_(new T[1]),
    size_({1}),
    deallocate_on_destruction_(true) {
      values_[0] = std::move(other);
    }

  template <class T>
  Array<T>::Array(Array const& other):
    size_(other.size_),
    values_(nullptr),
    deallocate_on_destruction_(other.deallocate_on_destruction_) {
      if (other.deallocate_on_destruction_) {
        if (get_total_size() > 0) {
          values_ = new T[get_total_size()];
          copy(other.values_);
        }
      }
      else {
        values_ = other.values_;
        deallocate_on_destruction_ = false;
      }
    }

  template <class T>
  Array<T>::Array(Array&& other):
    size_(std::move(other.size_)),
    values_(std::move(other.values_)),
    deallocate_on_destruction_(std::move(other.deallocate_on_destruction_)) {
      other.values_ = nullptr;
    }

  template <class T>
  template <class T2>
  Array<T>::Array(Array<T2> const& other):
    Array() {
      size_ = other.get_size();
      deallocate_on_destruction_ = true;
      if (get_total_size() > 0)
        values_ = new T[get_total_size()];

      copy(other.get_pointer());
    }

  template <class T>
  Array<T>::Array(ConstArray<T> const& other):
    size_(other.size_),
    values_(nullptr),
    deallocate_on_destruction_(true) {
      if (get_total_size() > 0) {
        values_ = new T[get_total_size()];
        copy(other.values_);
      }
    }

  template <class T>
  template <class T2>
  Array<T>::Array(ConstArray<T2> const& other):
    size_(other.size_),
    values_(nullptr),
    deallocate_on_destruction_(true) {
      if (get_total_size() > 0) {
        values_ = new T[get_total_size()];
        copy(other.values_);
      }
    }

  template <class T>
  Array<T>::Array(View<T> const& other):
    Array(other.get_size()) {
      *this = other;
    }

  template <class T>
  template <class T2>
  Array<T>::Array(View<T2> const& other):
    Array(other.get_size()) {
      *this = other;
    }

  template <class T>
  Array<T>::Array(ConstView<T> const& other):
    Array(other.get_size()) {
      *this = other;
    }

  template <class T>
  template <class T2>
  Array<T>::Array(ConstView<T2> const& other):
    Array(other.get_size()) {
      *this = other;
    }

  template <class T>
  Array<T>::Array(Size const& size):
    Array() {
      size_ = size;
      deallocate_on_destruction_ = true;

      if (get_total_size() > 0)
        values_ = new T[get_total_size()];
    }

  template <class T>
  Array<T>::Array(Size const& size, T const* other):
    Array(size) {
      copy(other);
    }

  template <class T>
  template <class T2>
  Array<T>::Array(Size const& size, T2 const* other):
    Array(size) {
      copy(other);
    }

  template <class T>
  Array<T>::Array(Size::SizeType const& size):
    Array(Size(size)) { }

  template <class T>
  Array<T>::Array(Size::SizeType const& size, T const* other):
    Array(Size(size), other) { }

  template <class T>
  template <class T2>
  Array<T>::Array(Size::SizeType const& size, T2 const* other):
    Array(Size(size), other) { }

  template <class T>
  Array<T>::~Array() {
    cleanup();
  }

  template <class T>
  Array<T> const& Array<T>::operator=(Array const& other) {
    assert(size_.same(other.get_size()));
    copy(other.values_);
    return *this;
  }

  template <class T>
  Array<T> const& Array<T>::operator=(Array&& other) {
    assert(size_.same(other.get_size()));

    if (values_ != nullptr)
      delete[] values_;

    values_ = other.values_;
    other.values_ = nullptr;
    return *this;
  }

  template <class T>
  template <class T2>
  Array<T> const& Array<T>::operator=(Array<T2> const& other) {
    assert(size_.same(other.get_size()));
    copy(other.get_pointer());
    return *this;
  }

  template <class T>
  Array<T> const& Array<T>::operator=(ConstArray<T> const& other) {
    assert(size_.same(other.get_size()));
    copy(other.get_pointer());
    return *this;
  }

  template <class T>
  template <class T2>
  Array<T> const& Array<T>::operator=(ConstArray<T2> const& other) {
    assert(size_.same(other.get_size()));
    copy(other.get_pointer());
    return *this;
  }

  template <class T>
  Array<T> const& Array<T>::operator=(View<T> const& other) {
    assert(size_.same(other.get_size()));
    copy(other);
    return *this;
  }

  template <class T>
  template <class T2>
  Array<T> const& Array<T>::operator=(View<T2> const& other) {
    assert(size_.same(other.get_size()));
    copy(other);
    return *this;
  }

  template <class T>
  Array<T> const& Array<T>::operator=(ConstView<T> const& other) {
    assert(size_.same(other.get_size()));
    copy(other);
    return *this;
  }

  template <class T>
  template <class T2>
  Array<T> const& Array<T>::operator=(ConstView<T2> const& other) {
    assert(size_.same(other.get_size()));
    copy(other);
    return *this;
  }

  template <class T>
  View<T> Array<T>::view() {
    return View<T>(*this);
  }

  template <class T>
  ConstView<T> Array<T>::view() const {
    return ConstView<T>(*this);
  }

  template <class T>
  bool Array<T>::resize(Size const& size, bool allow_allocation) {
    if (size.get_total_size() != get_total_size()) {
      if (!deallocate_on_destruction_)
        return false;

      if (values_) {
        delete[] values_;
        values_ = nullptr;
      }
      if (size.get_total_size() > 0 && allow_allocation)
        values_ = new T[size.get_total_size()];
    }

    size_ = size;

    return true;
  }

  template <class T>
  bool Array<T>::resize(Size::SizeType const& size, bool allow_allocation) {
    return resize(Size(size), allow_allocation);
  }

  template <class T>
  void Array<T>::set_pointer(T* p, bool responsible_for_deleting) {
    if (values_ != nullptr && deallocate_on_destruction_) {
      delete[] values_;
      values_ = nullptr;
    }

    values_ = p;
    deallocate_on_destruction_ = responsible_for_deleting;
  }

  template <class T>
  template <class... Args>
  T& Array<T>::operator()(Args const&... args) {
    assert(values_ != nullptr);
    return values_[size_.get_position_variadic(args...)];
  }

  template <class T>
  template <class... Args>
  T const& Array<T>::operator()(Args const&... args) const {
    assert(values_ != nullptr);
    return values_[size_.get_position_variadic(args...)];
  }

  template <class T>
  T& Array<T>::get(Size::SizeType const& index) {
    assert(values_ != nullptr);
    return values_[size_.get_position(index)];
  }

  template <class T>
  T const& Array<T>::get(Size::SizeType const& index) const {
    assert(values_ != nullptr);
    return values_[size_.get_position(index)];
  }

  template <class T>
  template <class T2>
  void Array<T>::copy(T2 const* other) {
    assert(values_ != nullptr);
    assert(other != nullptr);
    for (size_t i = 0; i < get_total_size(); i++)
      values_[i] = other[i];
  }

  template <class T>
  template <class T2>
  void Array<T>::copy(View<T2> const& other) {
    assert(values_ != nullptr);
    auto it1 = other.get_size().cbegin();
    auto it2 = other.get_size().cend();
    for (size_t i = 0; i < get_total_size() && it1 != it2; i++, ++it1)
      values_[i] = other.get(*it1);
  }

  template <class T>
  template <class T2>
  void Array<T>::copy(ConstView<T2> const& other) {
    assert(values_ != nullptr);
    auto it1 = other.get_size().cbegin();
    auto it2 = other.get_size().cend();
    for (size_t i = 0; i < get_total_size() && it1 != it2; i++, ++it1)
      values_[i] = other.get(*it1);
  }

  template <class T>
  void Array<T>::cleanup() {
    if (values_ != nullptr && deallocate_on_destruction_) {
      delete[] values_;
      values_ = nullptr;
    }

    size_ = Size();
  }
};

#endif
<commit_msg>Fixed constructor order.<commit_after>#ifndef __MULTIDIMENSIONAL_ARRAY__ARRAY_IMPL_HPP__
#define __MULTIDIMENSIONAL_ARRAY__ARRAY_IMPL_HPP__

#include "array.hpp"

namespace MultidimensionalArray {
  template <class T>
  Array<T>::Array():
    values_(nullptr),
    deallocate_on_destruction_(true) { }

  template <class T>
  Array<T>::Array(T const& other):
    size_({1}),
    values_(new T[1]),
    deallocate_on_destruction_(true) {
      values_[0] = other;
    }

  template <class T>
  Array<T>::Array(T&& other):
    size_({1}),
    values_(new T[1]),
    deallocate_on_destruction_(true) {
      values_[0] = std::move(other);
    }

  template <class T>
  Array<T>::Array(Array const& other):
    size_(other.size_),
    values_(nullptr),
    deallocate_on_destruction_(other.deallocate_on_destruction_) {
      if (other.deallocate_on_destruction_) {
        if (get_total_size() > 0) {
          values_ = new T[get_total_size()];
          copy(other.values_);
        }
      }
      else {
        values_ = other.values_;
        deallocate_on_destruction_ = false;
      }
    }

  template <class T>
  Array<T>::Array(Array&& other):
    size_(std::move(other.size_)),
    values_(std::move(other.values_)),
    deallocate_on_destruction_(std::move(other.deallocate_on_destruction_)) {
      other.values_ = nullptr;
    }

  template <class T>
  template <class T2>
  Array<T>::Array(Array<T2> const& other):
    Array() {
      size_ = other.get_size();
      deallocate_on_destruction_ = true;
      if (get_total_size() > 0)
        values_ = new T[get_total_size()];

      copy(other.get_pointer());
    }

  template <class T>
  Array<T>::Array(ConstArray<T> const& other):
    size_(other.size_),
    values_(nullptr),
    deallocate_on_destruction_(true) {
      if (get_total_size() > 0) {
        values_ = new T[get_total_size()];
        copy(other.values_);
      }
    }

  template <class T>
  template <class T2>
  Array<T>::Array(ConstArray<T2> const& other):
    size_(other.size_),
    values_(nullptr),
    deallocate_on_destruction_(true) {
      if (get_total_size() > 0) {
        values_ = new T[get_total_size()];
        copy(other.values_);
      }
    }

  template <class T>
  Array<T>::Array(View<T> const& other):
    Array(other.get_size()) {
      *this = other;
    }

  template <class T>
  template <class T2>
  Array<T>::Array(View<T2> const& other):
    Array(other.get_size()) {
      *this = other;
    }

  template <class T>
  Array<T>::Array(ConstView<T> const& other):
    Array(other.get_size()) {
      *this = other;
    }

  template <class T>
  template <class T2>
  Array<T>::Array(ConstView<T2> const& other):
    Array(other.get_size()) {
      *this = other;
    }

  template <class T>
  Array<T>::Array(Size const& size):
    Array() {
      size_ = size;
      deallocate_on_destruction_ = true;

      if (get_total_size() > 0)
        values_ = new T[get_total_size()];
    }

  template <class T>
  Array<T>::Array(Size const& size, T const* other):
    Array(size) {
      copy(other);
    }

  template <class T>
  template <class T2>
  Array<T>::Array(Size const& size, T2 const* other):
    Array(size) {
      copy(other);
    }

  template <class T>
  Array<T>::Array(Size::SizeType const& size):
    Array(Size(size)) { }

  template <class T>
  Array<T>::Array(Size::SizeType const& size, T const* other):
    Array(Size(size), other) { }

  template <class T>
  template <class T2>
  Array<T>::Array(Size::SizeType const& size, T2 const* other):
    Array(Size(size), other) { }

  template <class T>
  Array<T>::~Array() {
    cleanup();
  }

  template <class T>
  Array<T> const& Array<T>::operator=(Array const& other) {
    assert(size_.same(other.get_size()));
    copy(other.values_);
    return *this;
  }

  template <class T>
  Array<T> const& Array<T>::operator=(Array&& other) {
    assert(size_.same(other.get_size()));

    if (values_ != nullptr)
      delete[] values_;

    values_ = other.values_;
    other.values_ = nullptr;
    return *this;
  }

  template <class T>
  template <class T2>
  Array<T> const& Array<T>::operator=(Array<T2> const& other) {
    assert(size_.same(other.get_size()));
    copy(other.get_pointer());
    return *this;
  }

  template <class T>
  Array<T> const& Array<T>::operator=(ConstArray<T> const& other) {
    assert(size_.same(other.get_size()));
    copy(other.get_pointer());
    return *this;
  }

  template <class T>
  template <class T2>
  Array<T> const& Array<T>::operator=(ConstArray<T2> const& other) {
    assert(size_.same(other.get_size()));
    copy(other.get_pointer());
    return *this;
  }

  template <class T>
  Array<T> const& Array<T>::operator=(View<T> const& other) {
    assert(size_.same(other.get_size()));
    copy(other);
    return *this;
  }

  template <class T>
  template <class T2>
  Array<T> const& Array<T>::operator=(View<T2> const& other) {
    assert(size_.same(other.get_size()));
    copy(other);
    return *this;
  }

  template <class T>
  Array<T> const& Array<T>::operator=(ConstView<T> const& other) {
    assert(size_.same(other.get_size()));
    copy(other);
    return *this;
  }

  template <class T>
  template <class T2>
  Array<T> const& Array<T>::operator=(ConstView<T2> const& other) {
    assert(size_.same(other.get_size()));
    copy(other);
    return *this;
  }

  template <class T>
  View<T> Array<T>::view() {
    return View<T>(*this);
  }

  template <class T>
  ConstView<T> Array<T>::view() const {
    return ConstView<T>(*this);
  }

  template <class T>
  bool Array<T>::resize(Size const& size, bool allow_allocation) {
    if (size.get_total_size() != get_total_size()) {
      if (!deallocate_on_destruction_)
        return false;

      if (values_) {
        delete[] values_;
        values_ = nullptr;
      }
      if (size.get_total_size() > 0 && allow_allocation)
        values_ = new T[size.get_total_size()];
    }

    size_ = size;

    return true;
  }

  template <class T>
  bool Array<T>::resize(Size::SizeType const& size, bool allow_allocation) {
    return resize(Size(size), allow_allocation);
  }

  template <class T>
  void Array<T>::set_pointer(T* p, bool responsible_for_deleting) {
    if (values_ != nullptr && deallocate_on_destruction_) {
      delete[] values_;
      values_ = nullptr;
    }

    values_ = p;
    deallocate_on_destruction_ = responsible_for_deleting;
  }

  template <class T>
  template <class... Args>
  T& Array<T>::operator()(Args const&... args) {
    assert(values_ != nullptr);
    return values_[size_.get_position_variadic(args...)];
  }

  template <class T>
  template <class... Args>
  T const& Array<T>::operator()(Args const&... args) const {
    assert(values_ != nullptr);
    return values_[size_.get_position_variadic(args...)];
  }

  template <class T>
  T& Array<T>::get(Size::SizeType const& index) {
    assert(values_ != nullptr);
    return values_[size_.get_position(index)];
  }

  template <class T>
  T const& Array<T>::get(Size::SizeType const& index) const {
    assert(values_ != nullptr);
    return values_[size_.get_position(index)];
  }

  template <class T>
  template <class T2>
  void Array<T>::copy(T2 const* other) {
    assert(values_ != nullptr);
    assert(other != nullptr);
    for (size_t i = 0; i < get_total_size(); i++)
      values_[i] = other[i];
  }

  template <class T>
  template <class T2>
  void Array<T>::copy(View<T2> const& other) {
    assert(values_ != nullptr);
    auto it1 = other.get_size().cbegin();
    auto it2 = other.get_size().cend();
    for (size_t i = 0; i < get_total_size() && it1 != it2; i++, ++it1)
      values_[i] = other.get(*it1);
  }

  template <class T>
  template <class T2>
  void Array<T>::copy(ConstView<T2> const& other) {
    assert(values_ != nullptr);
    auto it1 = other.get_size().cbegin();
    auto it2 = other.get_size().cend();
    for (size_t i = 0; i < get_total_size() && it1 != it2; i++, ++it1)
      values_[i] = other.get(*it1);
  }

  template <class T>
  void Array<T>::cleanup() {
    if (values_ != nullptr && deallocate_on_destruction_) {
      delete[] values_;
      values_ = nullptr;
    }

    size_ = Size();
  }
};

#endif
<|endoftext|>


<commit_before>#ifndef CPPMATH_MATH_HPP
#define CPPMATH_MATH_HPP

#define _USE_MATH_DEFINES
#include <math.h>
#include <algorithm>
#include "compat.hpp"

namespace math
{
    constexpr const double pi = M_PI;

    double pointDistance(double x1, double y1, double x2, double y2);
    double pointDirection(double x1, double y1, double x2, double y2);

    double lengthdirX(double len, double dir);
    double lengthdirY(double len, double dir);

    double adaptDirection(double dir);

    template <typename T, typename T2>
    constexpr T snap(T x, T2 gridsize)
    {
        return (int)(x / gridsize) * gridsize - (x < 0 ? gridsize : 0);
    }

    template <typename T, typename T2>
    constexpr T smartSnap(T x, T2 gridsize)
    {
        return round(x / gridsize) * gridsize - (x < 0 ? gridsize : 0);
    }

    constexpr double radtodeg(double rad)
    {
        return rad * 180 / pi;
    }

    constexpr double degtorad(double deg)
    {
        return deg * pi / 180;
    }

    template <typename T>
    constexpr int sign(T val)
    {
        return (T(0) < val) - (val < T(0));
    }

    template <typename T>
    T clamp(const T& val, const T& min, const T& max)
    {
        return std::max(min, std::min(val, max));
    }
}

#endif

<commit_msg>Add functions to check if a var is within a range<commit_after>#ifndef CPPMATH_MATH_HPP
#define CPPMATH_MATH_HPP

#define _USE_MATH_DEFINES
#include <math.h>
#include <algorithm>
#include "compat.hpp"

namespace math
{
    constexpr const double pi = M_PI;

    double pointDistance(double x1, double y1, double x2, double y2);
    double pointDirection(double x1, double y1, double x2, double y2);

    double lengthdirX(double len, double dir);
    double lengthdirY(double len, double dir);

    double adaptDirection(double dir);

    template <typename T, typename T2>
    constexpr T snap(T x, T2 gridsize)
    {
        return (int)(x / gridsize) * gridsize - (x < 0 ? gridsize : 0);
    }

    template <typename T, typename T2>
    constexpr T smartSnap(T x, T2 gridsize)
    {
        return round(x / gridsize) * gridsize - (x < 0 ? gridsize : 0);
    }

    constexpr double radtodeg(double rad)
    {
        return rad * 180 / pi;
    }

    constexpr double degtorad(double deg)
    {
        return deg * pi / 180;
    }

    template <typename T>
    constexpr int sign(T val)
    {
        return (T(0) < val) - (val < T(0));
    }

    template <typename T>
    T clamp(const T& val, const T& min, const T& max)
    {
        return std::max(min, std::min(val, max));
    }

    template <typename T>
    constexpr bool around(const T& val, const T& base, const T& rad)
    {
        return inrange(val, base - rad, base + rad);
    }

    template <typename T>
    constexpr bool inrange(const T& val, const T& a, const T& b, bool incl = false)
    {
        return incl ? val >= std::min(a, b) && val <= std::max(a, b)
                    : val > std::min(a, b) && val < std::max(a, b);
    }
}

#endif

<|endoftext|>


<commit_before>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Utility/PixelFormat.hpp>
#include <Nazara/Core/Error.hpp>
#include <algorithm>
#include <array>
#include <cstring>
#include <Nazara/Utility/Debug.hpp>

namespace Nz
{
	inline PixelFormatInfo::PixelFormatInfo() :
	content(PixelFormatContent_Undefined),
	bitsPerPixel(0)
	{
	}

	inline PixelFormatInfo::PixelFormatInfo(PixelFormatContent formatContent, UInt8 bpp, PixelFormatSubType subType) :
	content(formatContent),
	redType(subType),
	greenType(subType),
	blueType(subType),
	alphaType(subType),
	bitsPerPixel(bpp)
	{
	}

	inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, UInt8 bpp, PixelFormatSubType subType) :
	content(formatContent),
	redType(subType),
	greenType(subType),
	blueType(subType),
	alphaType(subType),
	name(formatName),
	bitsPerPixel(bpp)
	{
	}

	inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, Bitset<> rMask, Bitset<> gMask, Bitset<> bMask, Bitset<> aMask, PixelFormatSubType subType) :
	redMask(rMask),
	greenMask(gMask),
	blueMask(bMask),
	alphaMask(aMask),
	content(formatContent),
	redType(subType),
	greenType(subType),
	blueType(subType),
	alphaType(subType),
	name(formatName)
	{
		RecomputeBitsPerPixel();
	}

	inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, PixelFormatSubType rType, Bitset<> rMask, PixelFormatSubType gType, Bitset<> gMask, PixelFormatSubType bType, Bitset<> bMask, PixelFormatSubType aType, Bitset<> aMask, UInt8 bpp) :
	redMask(rMask),
	greenMask(gMask),
	blueMask(bMask),
	alphaMask(aMask),
	content(formatContent),
	redType(rType),
	greenType(gType),
	blueType(bType),
	alphaType(aType),
	name(formatName)
	{
		if (bpp == 0)
			RecomputeBitsPerPixel();
	}

	inline void PixelFormatInfo::Clear()
	{
		bitsPerPixel = 0;
		alphaMask.Clear();
		blueMask.Clear();
		greenMask.Clear();
		redMask.Clear();
		name.Clear();
	}

	inline bool PixelFormatInfo::IsCompressed() const
	{
		return redType   == PixelFormatSubType_Compressed ||
		       greenType == PixelFormatSubType_Compressed ||
		       blueType  == PixelFormatSubType_Compressed ||
		       alphaType == PixelFormatSubType_Compressed;
	}

	inline bool PixelFormatInfo::IsValid() const
	{
		return bitsPerPixel != 0;
	}

	inline void PixelFormatInfo::RecomputeBitsPerPixel()
	{
		Bitset<> counter;
		counter |= redMask;
		counter |= greenMask;
		counter |= blueMask;
		counter |= alphaMask;

		bitsPerPixel = counter.Count();
	}

	inline bool PixelFormatInfo::Validate() const
	{
		if (!IsValid())
			return false;

		if (content <= PixelFormatContent_Undefined || content > PixelFormatContent_Max)
			return false;

		std::array<const Nz::Bitset<>*, 4> masks = {&redMask, &greenMask, &blueMask, &alphaMask};
		std::array<PixelFormatSubType, 4> types = {redType, greenType, blueType, alphaType};

		for (unsigned int i = 0; i < 4; ++i)
		{
			unsigned int usedBits = masks[i]->Count();
			if (usedBits == 0)
				continue;

			if (usedBits > bitsPerPixel)
				return false;

			switch (types[i])
			{
				case PixelFormatSubType_Half:
					if (usedBits != 16)
						return false;

					break;

				case PixelFormatSubType_Float:
					if (usedBits != 32)
						return false;

					break;

				default:
					break;
			}
		}

		return true;
	}

	inline std::size_t PixelFormat::ComputeSize(PixelFormatType format, unsigned int width, unsigned int height, unsigned int depth)
	{
		if (IsCompressed(format))
		{
			switch (format)
			{
				case PixelFormatType_DXT1:
				case PixelFormatType_DXT3:
				case PixelFormatType_DXT5:
					return (((width + 3) / 4) * ((height + 3) / 4) * (format == PixelFormatType_DXT1) ? 8 : 16) * depth;

				default:
					NazaraError("Unsupported format");
					return 0;
			}
		}
		else
			return width * height * depth * GetBytesPerPixel(format);
	}

	inline bool PixelFormat::Convert(PixelFormatType srcFormat, PixelFormatType dstFormat, const void* src, void* dst)
	{
		if (srcFormat == dstFormat)
		{
			std::memcpy(dst, src, GetBytesPerPixel(srcFormat));
			return true;
		}

		#if NAZARA_UTILITY_SAFE
		if (IsCompressed(srcFormat))
		{
			NazaraError("Cannot convert single pixel from compressed format");
			return false;
		}

		if (IsCompressed(dstFormat))
		{
			NazaraError("Cannot convert single pixel to compressed format");
			return false;
		}
		#endif

		ConvertFunction func = s_convertFunctions[srcFormat][dstFormat];
		if (!func)
		{
			NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " is not supported");
			return false;
		}

		if (!func(reinterpret_cast<const UInt8*>(src), reinterpret_cast<const UInt8*>(src) + GetBytesPerPixel(srcFormat), reinterpret_cast<UInt8*>(dst)))
		{
			NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " failed");
			return false;
		}

		return true;
	}

	inline bool PixelFormat::Convert(PixelFormatType srcFormat, PixelFormatType dstFormat, const void* start, const void* end, void* dst)
	{
		if (srcFormat == dstFormat)
		{
			std::memcpy(dst, start, reinterpret_cast<const UInt8*>(end)-reinterpret_cast<const UInt8*>(start));
			return true;
		}

		ConvertFunction func = s_convertFunctions[srcFormat][dstFormat];
		if (!func)
		{
			NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " is not supported");
			return false;
		}

		if (!func(reinterpret_cast<const UInt8*>(start), reinterpret_cast<const UInt8*>(end), reinterpret_cast<UInt8*>(dst)))
		{
			NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " failed");
			return false;
		}

		return true;
	}

	inline bool PixelFormat::Flip(PixelFlipping flipping, PixelFormatType format, unsigned int width, unsigned int height, unsigned int depth, const void* src, void* dst)
	{
		#if NAZARA_UTILITY_SAFE
		if (!IsValid(format))
		{
			NazaraError("Invalid pixel format");
			return false;
		}
		#endif

		auto it = s_flipFunctions[flipping].find(format);
		if (it != s_flipFunctions[flipping].end())
			it->second(width, height, depth, reinterpret_cast<const UInt8*>(src), reinterpret_cast<UInt8*>(dst));
		else
		{
			// Flipping générique

			#if NAZARA_UTILITY_SAFE
			if (IsCompressed(format))
			{
				NazaraError("No function to flip compressed format");
				return false;
			}
			#endif

			UInt8 bpp = GetBytesPerPixel(format);
			unsigned int lineStride = width*bpp;
			switch (flipping)
			{
				case PixelFlipping_Horizontally:
				{
					if (src == dst)
					{
						for (unsigned int z = 0; z < depth; ++z)
						{
							UInt8* ptr = reinterpret_cast<UInt8*>(dst) + width*height*z;
							for (unsigned int y = 0; y < height/2; ++y)
								std::swap_ranges(&ptr[y*lineStride], &ptr[(y+1)*lineStride-1], &ptr[(height-y-1)*lineStride]);
						}
					}
					else
					{
						for (unsigned int z = 0; z < depth; ++z)
						{
							const UInt8* srcPtr = reinterpret_cast<const UInt8*>(src);
							UInt8* dstPtr = reinterpret_cast<UInt8*>(dst) + (width-1)*height*depth*bpp;
							for (unsigned int y = 0; y < height; ++y)
							{
								std::memcpy(dstPtr, srcPtr, lineStride);

								srcPtr += lineStride;
								dstPtr -= lineStride;
							}
						}
					}
					break;
				}

				case PixelFlipping_Vertically:
				{
					if (src == dst)
					{
						for (unsigned int z = 0; z < depth; ++z)
						{
							UInt8* ptr = reinterpret_cast<UInt8*>(dst) + width*height*z;
							for (unsigned int y = 0; y < height; ++y)
							{
								for (unsigned int x = 0; x < width/2; ++x)
									std::swap_ranges(&ptr[x*bpp], &ptr[(x+1)*bpp], &ptr[(width-x)*bpp]);

								ptr += lineStride;
							}
						}
					}
					else
					{
						for (unsigned int z = 0; z < depth; ++z)
						{
							UInt8* ptr = reinterpret_cast<UInt8*>(dst) + width*height*z;
							for (unsigned int y = 0; y < height; ++y)
							{
								for (unsigned int x = 0; x < width; ++x)
									std::memcpy(&ptr[x*bpp], &ptr[(width-x)*bpp], bpp);

								ptr += lineStride;
							}
						}
					}
					break;
				}
			}
		}

		return true;
	}

	inline UInt8 PixelFormat::GetBitsPerPixel(PixelFormatType format)
	{
		return s_pixelFormatInfos[format].bitsPerPixel;
	}

	inline UInt8 PixelFormat::GetBytesPerPixel(PixelFormatType format)
	{
		return GetBitsPerPixel(format)/8;
	}

	inline PixelFormatContent PixelFormat::GetContent(PixelFormatType format)
	{
		return s_pixelFormatInfos[format].content;
	}

	inline const PixelFormatInfo& PixelFormat::GetInfo(PixelFormatType format)
	{
		return s_pixelFormatInfos[format];
	}

	inline const String& PixelFormat::GetName(PixelFormatType format)
	{
		return s_pixelFormatInfos[format].name;
	}

	inline bool PixelFormat::HasAlpha(PixelFormatType format)
	{
		return s_pixelFormatInfos[format].alphaMask.TestAny();
	}

	inline bool PixelFormat::IsCompressed(PixelFormatType format)
	{
		return s_pixelFormatInfos[format].IsCompressed();
	}

	inline bool PixelFormat::IsConversionSupported(PixelFormatType srcFormat, PixelFormatType dstFormat)
	{
		if (srcFormat == dstFormat)
			return true;

		return s_convertFunctions[srcFormat][dstFormat] != nullptr;
	}

	inline bool PixelFormat::IsValid(PixelFormatType format)
	{
		return format != PixelFormatType_Undefined;
	}

	inline void PixelFormat::SetConvertFunction(PixelFormatType srcFormat, PixelFormatType dstFormat, ConvertFunction func)
	{
		s_convertFunctions[srcFormat][dstFormat] = func;
	}

	inline void PixelFormat::SetFlipFunction(PixelFlipping flipping, PixelFormatType format, FlipFunction func)
	{
		s_flipFunctions[flipping][format] = func;
	}
}

#include <Nazara/Utility/DebugOff.hpp>
<commit_msg>Utility/PixelFormat: Fix ComputeSize for DXT formats<commit_after>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Utility/PixelFormat.hpp>
#include <Nazara/Core/Error.hpp>
#include <algorithm>
#include <array>
#include <cstring>
#include <Nazara/Utility/Debug.hpp>

namespace Nz
{
	inline PixelFormatInfo::PixelFormatInfo() :
	content(PixelFormatContent_Undefined),
	bitsPerPixel(0)
	{
	}

	inline PixelFormatInfo::PixelFormatInfo(PixelFormatContent formatContent, UInt8 bpp, PixelFormatSubType subType) :
	content(formatContent),
	redType(subType),
	greenType(subType),
	blueType(subType),
	alphaType(subType),
	bitsPerPixel(bpp)
	{
	}

	inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, UInt8 bpp, PixelFormatSubType subType) :
	content(formatContent),
	redType(subType),
	greenType(subType),
	blueType(subType),
	alphaType(subType),
	name(formatName),
	bitsPerPixel(bpp)
	{
	}

	inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, Bitset<> rMask, Bitset<> gMask, Bitset<> bMask, Bitset<> aMask, PixelFormatSubType subType) :
	redMask(rMask),
	greenMask(gMask),
	blueMask(bMask),
	alphaMask(aMask),
	content(formatContent),
	redType(subType),
	greenType(subType),
	blueType(subType),
	alphaType(subType),
	name(formatName)
	{
		RecomputeBitsPerPixel();
	}

	inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, PixelFormatSubType rType, Bitset<> rMask, PixelFormatSubType gType, Bitset<> gMask, PixelFormatSubType bType, Bitset<> bMask, PixelFormatSubType aType, Bitset<> aMask, UInt8 bpp) :
	redMask(rMask),
	greenMask(gMask),
	blueMask(bMask),
	alphaMask(aMask),
	content(formatContent),
	redType(rType),
	greenType(gType),
	blueType(bType),
	alphaType(aType),
	name(formatName)
	{
		if (bpp == 0)
			RecomputeBitsPerPixel();
	}

	inline void PixelFormatInfo::Clear()
	{
		bitsPerPixel = 0;
		alphaMask.Clear();
		blueMask.Clear();
		greenMask.Clear();
		redMask.Clear();
		name.Clear();
	}

	inline bool PixelFormatInfo::IsCompressed() const
	{
		return redType   == PixelFormatSubType_Compressed ||
		       greenType == PixelFormatSubType_Compressed ||
		       blueType  == PixelFormatSubType_Compressed ||
		       alphaType == PixelFormatSubType_Compressed;
	}

	inline bool PixelFormatInfo::IsValid() const
	{
		return bitsPerPixel != 0;
	}

	inline void PixelFormatInfo::RecomputeBitsPerPixel()
	{
		Bitset<> counter;
		counter |= redMask;
		counter |= greenMask;
		counter |= blueMask;
		counter |= alphaMask;

		bitsPerPixel = counter.Count();
	}

	inline bool PixelFormatInfo::Validate() const
	{
		if (!IsValid())
			return false;

		if (content <= PixelFormatContent_Undefined || content > PixelFormatContent_Max)
			return false;

		std::array<const Nz::Bitset<>*, 4> masks = {&redMask, &greenMask, &blueMask, &alphaMask};
		std::array<PixelFormatSubType, 4> types = {redType, greenType, blueType, alphaType};

		for (unsigned int i = 0; i < 4; ++i)
		{
			unsigned int usedBits = masks[i]->Count();
			if (usedBits == 0)
				continue;

			if (usedBits > bitsPerPixel)
				return false;

			switch (types[i])
			{
				case PixelFormatSubType_Half:
					if (usedBits != 16)
						return false;

					break;

				case PixelFormatSubType_Float:
					if (usedBits != 32)
						return false;

					break;

				default:
					break;
			}
		}

		return true;
	}

	inline std::size_t PixelFormat::ComputeSize(PixelFormatType format, unsigned int width, unsigned int height, unsigned int depth)
	{
		if (IsCompressed(format))
		{
			switch (format)
			{
				case PixelFormatType_DXT1:
				case PixelFormatType_DXT3:
				case PixelFormatType_DXT5:
					return (((width + 3) / 4) * ((height + 3) / 4) * ((format == PixelFormatType_DXT1) ? 8 : 16)) * depth;

				default:
					NazaraError("Unsupported format");
					return 0;
			}
		}
		else
			return width * height * depth * GetBytesPerPixel(format);
	}

	inline bool PixelFormat::Convert(PixelFormatType srcFormat, PixelFormatType dstFormat, const void* src, void* dst)
	{
		if (srcFormat == dstFormat)
		{
			std::memcpy(dst, src, GetBytesPerPixel(srcFormat));
			return true;
		}

		#if NAZARA_UTILITY_SAFE
		if (IsCompressed(srcFormat))
		{
			NazaraError("Cannot convert single pixel from compressed format");
			return false;
		}

		if (IsCompressed(dstFormat))
		{
			NazaraError("Cannot convert single pixel to compressed format");
			return false;
		}
		#endif

		ConvertFunction func = s_convertFunctions[srcFormat][dstFormat];
		if (!func)
		{
			NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " is not supported");
			return false;
		}

		if (!func(reinterpret_cast<const UInt8*>(src), reinterpret_cast<const UInt8*>(src) + GetBytesPerPixel(srcFormat), reinterpret_cast<UInt8*>(dst)))
		{
			NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " failed");
			return false;
		}

		return true;
	}

	inline bool PixelFormat::Convert(PixelFormatType srcFormat, PixelFormatType dstFormat, const void* start, const void* end, void* dst)
	{
		if (srcFormat == dstFormat)
		{
			std::memcpy(dst, start, reinterpret_cast<const UInt8*>(end)-reinterpret_cast<const UInt8*>(start));
			return true;
		}

		ConvertFunction func = s_convertFunctions[srcFormat][dstFormat];
		if (!func)
		{
			NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " is not supported");
			return false;
		}

		if (!func(reinterpret_cast<const UInt8*>(start), reinterpret_cast<const UInt8*>(end), reinterpret_cast<UInt8*>(dst)))
		{
			NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " failed");
			return false;
		}

		return true;
	}

	inline bool PixelFormat::Flip(PixelFlipping flipping, PixelFormatType format, unsigned int width, unsigned int height, unsigned int depth, const void* src, void* dst)
	{
		#if NAZARA_UTILITY_SAFE
		if (!IsValid(format))
		{
			NazaraError("Invalid pixel format");
			return false;
		}
		#endif

		auto it = s_flipFunctions[flipping].find(format);
		if (it != s_flipFunctions[flipping].end())
			it->second(width, height, depth, reinterpret_cast<const UInt8*>(src), reinterpret_cast<UInt8*>(dst));
		else
		{
			// Flipping générique

			#if NAZARA_UTILITY_SAFE
			if (IsCompressed(format))
			{
				NazaraError("No function to flip compressed format");
				return false;
			}
			#endif

			UInt8 bpp = GetBytesPerPixel(format);
			unsigned int lineStride = width*bpp;
			switch (flipping)
			{
				case PixelFlipping_Horizontally:
				{
					if (src == dst)
					{
						for (unsigned int z = 0; z < depth; ++z)
						{
							UInt8* ptr = reinterpret_cast<UInt8*>(dst) + width*height*z;
							for (unsigned int y = 0; y < height/2; ++y)
								std::swap_ranges(&ptr[y*lineStride], &ptr[(y+1)*lineStride-1], &ptr[(height-y-1)*lineStride]);
						}
					}
					else
					{
						for (unsigned int z = 0; z < depth; ++z)
						{
							const UInt8* srcPtr = reinterpret_cast<const UInt8*>(src);
							UInt8* dstPtr = reinterpret_cast<UInt8*>(dst) + (width-1)*height*depth*bpp;
							for (unsigned int y = 0; y < height; ++y)
							{
								std::memcpy(dstPtr, srcPtr, lineStride);

								srcPtr += lineStride;
								dstPtr -= lineStride;
							}
						}
					}
					break;
				}

				case PixelFlipping_Vertically:
				{
					if (src == dst)
					{
						for (unsigned int z = 0; z < depth; ++z)
						{
							UInt8* ptr = reinterpret_cast<UInt8*>(dst) + width*height*z;
							for (unsigned int y = 0; y < height; ++y)
							{
								for (unsigned int x = 0; x < width/2; ++x)
									std::swap_ranges(&ptr[x*bpp], &ptr[(x+1)*bpp], &ptr[(width-x)*bpp]);

								ptr += lineStride;
							}
						}
					}
					else
					{
						for (unsigned int z = 0; z < depth; ++z)
						{
							UInt8* ptr = reinterpret_cast<UInt8*>(dst) + width*height*z;
							for (unsigned int y = 0; y < height; ++y)
							{
								for (unsigned int x = 0; x < width; ++x)
									std::memcpy(&ptr[x*bpp], &ptr[(width-x)*bpp], bpp);

								ptr += lineStride;
							}
						}
					}
					break;
				}
			}
		}

		return true;
	}

	inline UInt8 PixelFormat::GetBitsPerPixel(PixelFormatType format)
	{
		return s_pixelFormatInfos[format].bitsPerPixel;
	}

	inline UInt8 PixelFormat::GetBytesPerPixel(PixelFormatType format)
	{
		return GetBitsPerPixel(format)/8;
	}

	inline PixelFormatContent PixelFormat::GetContent(PixelFormatType format)
	{
		return s_pixelFormatInfos[format].content;
	}

	inline const PixelFormatInfo& PixelFormat::GetInfo(PixelFormatType format)
	{
		return s_pixelFormatInfos[format];
	}

	inline const String& PixelFormat::GetName(PixelFormatType format)
	{
		return s_pixelFormatInfos[format].name;
	}

	inline bool PixelFormat::HasAlpha(PixelFormatType format)
	{
		return s_pixelFormatInfos[format].alphaMask.TestAny();
	}

	inline bool PixelFormat::IsCompressed(PixelFormatType format)
	{
		return s_pixelFormatInfos[format].IsCompressed();
	}

	inline bool PixelFormat::IsConversionSupported(PixelFormatType srcFormat, PixelFormatType dstFormat)
	{
		if (srcFormat == dstFormat)
			return true;

		return s_convertFunctions[srcFormat][dstFormat] != nullptr;
	}

	inline bool PixelFormat::IsValid(PixelFormatType format)
	{
		return format != PixelFormatType_Undefined;
	}

	inline void PixelFormat::SetConvertFunction(PixelFormatType srcFormat, PixelFormatType dstFormat, ConvertFunction func)
	{
		s_convertFunctions[srcFormat][dstFormat] = func;
	}

	inline void PixelFormat::SetFlipFunction(PixelFlipping flipping, PixelFormatType format, FlipFunction func)
	{
		s_flipFunctions[flipping][format] = func;
	}
}

#include <Nazara/Utility/DebugOff.hpp>
<|endoftext|>