<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <algorithm>

#include "unogaltheme.hxx"
#include "unogalitem.hxx"
#include "galtheme.hxx"
#include "svx/gallery1.hxx"
#include "svx/galmisc.hxx"
#include <svx/fmmodel.hxx>
#include <rtl/uuid.h>
#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>
#include <unotools/pathoptions.hxx>

using namespace ::com::sun::star;

namespace unogallery {

// -----------------
// - GalleryTheme -
// -----------------

GalleryTheme::GalleryTheme( const ::rtl::OUString& rThemeName )
{
    mpGallery = ::Gallery::GetGalleryInstance();
    mpTheme = ( mpGallery ? mpGallery->AcquireTheme( rThemeName, *this ) : NULL );

    if( mpGallery )
        StartListening( *mpGallery );
}

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

GalleryTheme::~GalleryTheme()
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );

    DBG_ASSERT( !mpTheme || mpGallery, "Theme is living without Gallery" );

    implReleaseItems( NULL );

    if( mpGallery )
    {
        EndListening( *mpGallery );

        if( mpTheme )
            mpGallery->ReleaseTheme( mpTheme, *this );
    }
}

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

::rtl::OUString GalleryTheme::getImplementationName_Static()
    throw()
{
    return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.gallery.GalleryTheme" ) );
}

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

uno::Sequence< ::rtl::OUString > GalleryTheme::getSupportedServiceNames_Static()
    throw()
{
    uno::Sequence< ::rtl::OUString > aSeq( 1 );

    aSeq.getArray()[ 0 ] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.gallery.GalleryTheme" ) );

    return aSeq;
}

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

::rtl::OUString SAL_CALL GalleryTheme::getImplementationName()
    throw( uno::RuntimeException )
{
    return getImplementationName_Static();
}

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

sal_Bool SAL_CALL GalleryTheme::supportsService( const ::rtl::OUString& ServiceName )
    throw( uno::RuntimeException )
{
    uno::Sequence< ::rtl::OUString >    aSNL( getSupportedServiceNames() );
    const ::rtl::OUString*              pArray = aSNL.getConstArray();

    for( int i = 0; i < aSNL.getLength(); i++ )
        if( pArray[i] == ServiceName )
            return true;

    return false;
}

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

uno::Sequence< ::rtl::OUString > SAL_CALL GalleryTheme::getSupportedServiceNames()
    throw( uno::RuntimeException )
{
    return getSupportedServiceNames_Static();
}

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

uno::Sequence< uno::Type > SAL_CALL GalleryTheme::getTypes()
    throw(uno::RuntimeException)
{
    uno::Sequence< uno::Type >  aTypes( 5 );
    uno::Type*                  pTypes = aTypes.getArray();

    *pTypes++ = ::getCppuType((const uno::Reference< lang::XServiceInfo>*)0);
    *pTypes++ = ::getCppuType((const uno::Reference< lang::XTypeProvider>*)0);
    *pTypes++ = ::getCppuType((const uno::Reference< container::XElementAccess>*)0);
    *pTypes++ = ::getCppuType((const uno::Reference< container::XIndexAccess>*)0);
    *pTypes++ = ::getCppuType((const uno::Reference< gallery::XGalleryTheme>*)0);

    return aTypes;
}

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

uno::Sequence< sal_Int8 > SAL_CALL GalleryTheme::getImplementationId()
    throw(uno::RuntimeException)
{
    const vos::OGuard                   aGuard( Application::GetSolarMutex() );
    static uno::Sequence< sal_Int8 >    aId;

    if( aId.getLength() == 0 )
    {
        aId.realloc( 16 );
        rtl_createUuid( reinterpret_cast< sal_uInt8* >( aId.getArray() ), 0, sal_True );
    }

    return aId;
}

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

uno::Type SAL_CALL GalleryTheme::getElementType()
    throw (uno::RuntimeException)
{
    return ::getCppuType( (const uno::Reference< gallery::XGalleryItem >*) 0);
}

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

sal_Bool SAL_CALL GalleryTheme::hasElements()
    throw (uno::RuntimeException)
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );

    return( ( mpTheme != NULL ) && ( mpTheme->GetObjectCount() > 0 ) );
}

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

sal_Int32 SAL_CALL GalleryTheme::getCount()
    throw (uno::RuntimeException)
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );

    return( mpTheme ? mpTheme->GetObjectCount() : 0 );
}

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

uno::Any SAL_CALL GalleryTheme::getByIndex( ::sal_Int32 nIndex )
    throw (lang::IndexOutOfBoundsException, lang::WrappedTargetException, uno::RuntimeException)
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );
    uno::Any            aRet;

    if( mpTheme )
    {
        if( ( nIndex < 0 ) || ( nIndex >= getCount() ) )
        {
            throw lang::IndexOutOfBoundsException();
        }
        else
        {
            const GalleryObject* pObj = mpTheme->ImplGetGalleryObject( nIndex );

            if( pObj )
                aRet = uno::makeAny( uno::Reference< gallery::XGalleryItem >( new GalleryItem( *this, *pObj ) ) );
        }
    }

    return aRet;
}

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

::rtl::OUString SAL_CALL GalleryTheme::getName(  )
    throw (uno::RuntimeException)
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );
    ::rtl::OUString     aRet;

    if( mpTheme )
        aRet = mpTheme->GetName();

    return aRet;
}

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

void SAL_CALL GalleryTheme::update(  )
    throw (uno::RuntimeException)
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );

    if( mpTheme )
    {
        const Link aDummyLink;
        mpTheme->Actualize( aDummyLink );
    }
}

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

::sal_Int32 SAL_CALL GalleryTheme::insertURLByIndex(
    const ::rtl::OUString& rURL, ::sal_Int32 nIndex )
    throw (lang::WrappedTargetException, uno::RuntimeException)
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );
    sal_Int32           nRet = -1;

    if( mpTheme )
    {
        try
        {
            const INetURLObject aURL( rURL );

            nIndex = ::std::max( ::std::min( nIndex, getCount() ), sal_Int32( 0 ) );

            if( ( aURL.GetProtocol() != INET_PROT_NOT_VALID ) && mpTheme->InsertURL( aURL, nIndex ) )
            {
                const GalleryObject* pObj = mpTheme->ImplGetGalleryObject( aURL );

                if( pObj )
                    nRet = mpTheme->ImplGetGalleryObjectPos( pObj );
            }
        }
        catch( ... )
        {
        }
    }

    return nRet;
}

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

::sal_Int32 SAL_CALL GalleryTheme::insertGraphicByIndex(
    const uno::Reference< graphic::XGraphic >& rxGraphic, sal_Int32 nIndex )
    throw (lang::WrappedTargetException, uno::RuntimeException)
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );
    sal_Int32           nRet = -1;

    if( mpTheme )
    {
        try
        {
            const Graphic aGraphic( rxGraphic );

            nIndex = ::std::max( ::std::min( nIndex, getCount() ), sal_Int32( 0 ) );

            if( mpTheme->InsertGraphic( aGraphic, nIndex ) )
                nRet = nIndex;
        }
        catch( ... )
        {
        }
    }

    return nRet;
}

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

::sal_Int32 SAL_CALL GalleryTheme::insertDrawingByIndex(
    const uno::Reference< lang::XComponent >& Drawing, sal_Int32 nIndex )
    throw (lang::WrappedTargetException, uno::RuntimeException)
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );
    sal_Int32           nRet = -1;

    if( mpTheme )
    {
        GalleryDrawingModel* pModel = GalleryDrawingModel::getImplementation( Drawing );

        if( pModel && pModel->GetDoc() && pModel->GetDoc()->ISA( FmFormModel ) )
        {
            nIndex = ::std::max( ::std::min( nIndex, getCount() ), sal_Int32( 0 ) );

            if( mpTheme->InsertModel( *static_cast< FmFormModel* >( pModel->GetDoc() ), nIndex ) )
                nRet = nIndex;
        }
    }

    return nRet;
}

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

void SAL_CALL GalleryTheme::removeByIndex( sal_Int32 nIndex )
    throw (lang::IndexOutOfBoundsException, uno::RuntimeException)
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );

    if( mpTheme )
    {
        if( ( nIndex < 0 ) || ( nIndex >= getCount() ) )
            throw lang::IndexOutOfBoundsException();
        else
            mpTheme->RemoveObject( nIndex );
    }
}

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

void GalleryTheme::Notify( SfxBroadcaster&, const SfxHint& rHint )
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );
    const GalleryHint&  rGalleryHint = static_cast< const GalleryHint& >( rHint );

    switch( rGalleryHint.GetType() )
    {
        case( GALLERY_HINT_CLOSE_THEME ):
        {
            DBG_ASSERT( !mpTheme || mpGallery, "Theme is living without Gallery" );

            implReleaseItems( NULL );

            if( mpGallery && mpTheme )
            {
                mpGallery->ReleaseTheme( mpTheme, *this );
                mpTheme = NULL;
            }
        }
        break;

        case( GALLERY_HINT_CLOSE_OBJECT ):
        {
            GalleryObject* pObj = reinterpret_cast< GalleryObject* >( rGalleryHint.GetData1() );

            if( pObj )
                implReleaseItems( pObj );
        }
        break;

        default:
        break;
    }
}

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

void GalleryTheme::implReleaseItems( GalleryObject* pObj )
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );

    for( GalleryItemList::iterator aIter = maItemList.begin(); aIter != maItemList.end();  )
    {
        if( !pObj || ( (*aIter)->implGetObject() == pObj ) )
        {
            (*aIter)->implSetInvalid();
            aIter = maItemList.erase( aIter );
        }
        else
            ++aIter;
    }
}

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

::GalleryTheme* GalleryTheme::implGetTheme() const
{
    return mpTheme;
}

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

void GalleryTheme::implRegisterGalleryItem( ::unogallery::GalleryItem& rItem )
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );

//  DBG_ASSERT( maItemList.find( &rItem ) == maItemList.end(), "Item already registered" );
    maItemList.push_back( &rItem );
}

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

void GalleryTheme::implDeregisterGalleryItem( ::unogallery::GalleryItem& rItem )
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );

//  DBG_ASSERT( maItemList.find( &rItem ) != maItemList.end(), "Item is not registered" );
    maItemList.remove( &rItem );
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>#i80184# Allow adding drawing documents to gallery via API<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <algorithm>

#include "unogaltheme.hxx"
#include "unogalitem.hxx"
#include "galtheme.hxx"
#include "svx/gallery1.hxx"
#include "svx/galmisc.hxx"
#include <svx/fmmodel.hxx>
#include <svx/svdpage.hxx>
#include <svx/unopage.hxx>
#include <svl/itempool.hxx>
#include <rtl/uuid.h>
#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>
#include <unotools/pathoptions.hxx>

using namespace ::com::sun::star;

namespace unogallery {

// -----------------
// - GalleryTheme -
// -----------------

GalleryTheme::GalleryTheme( const ::rtl::OUString& rThemeName )
{
    mpGallery = ::Gallery::GetGalleryInstance();
    mpTheme = ( mpGallery ? mpGallery->AcquireTheme( rThemeName, *this ) : NULL );

    if( mpGallery )
        StartListening( *mpGallery );
}

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

GalleryTheme::~GalleryTheme()
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );

    DBG_ASSERT( !mpTheme || mpGallery, "Theme is living without Gallery" );

    implReleaseItems( NULL );

    if( mpGallery )
    {
        EndListening( *mpGallery );

        if( mpTheme )
            mpGallery->ReleaseTheme( mpTheme, *this );
    }
}

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

::rtl::OUString GalleryTheme::getImplementationName_Static()
    throw()
{
    return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.gallery.GalleryTheme" ) );
}

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

uno::Sequence< ::rtl::OUString > GalleryTheme::getSupportedServiceNames_Static()
    throw()
{
    uno::Sequence< ::rtl::OUString > aSeq( 1 );

    aSeq.getArray()[ 0 ] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.gallery.GalleryTheme" ) );

    return aSeq;
}

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

::rtl::OUString SAL_CALL GalleryTheme::getImplementationName()
    throw( uno::RuntimeException )
{
    return getImplementationName_Static();
}

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

sal_Bool SAL_CALL GalleryTheme::supportsService( const ::rtl::OUString& ServiceName )
    throw( uno::RuntimeException )
{
    uno::Sequence< ::rtl::OUString >    aSNL( getSupportedServiceNames() );
    const ::rtl::OUString*              pArray = aSNL.getConstArray();

    for( int i = 0; i < aSNL.getLength(); i++ )
        if( pArray[i] == ServiceName )
            return true;

    return false;
}

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

uno::Sequence< ::rtl::OUString > SAL_CALL GalleryTheme::getSupportedServiceNames()
    throw( uno::RuntimeException )
{
    return getSupportedServiceNames_Static();
}

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

uno::Sequence< uno::Type > SAL_CALL GalleryTheme::getTypes()
    throw(uno::RuntimeException)
{
    uno::Sequence< uno::Type >  aTypes( 5 );
    uno::Type*                  pTypes = aTypes.getArray();

    *pTypes++ = ::getCppuType((const uno::Reference< lang::XServiceInfo>*)0);
    *pTypes++ = ::getCppuType((const uno::Reference< lang::XTypeProvider>*)0);
    *pTypes++ = ::getCppuType((const uno::Reference< container::XElementAccess>*)0);
    *pTypes++ = ::getCppuType((const uno::Reference< container::XIndexAccess>*)0);
    *pTypes++ = ::getCppuType((const uno::Reference< gallery::XGalleryTheme>*)0);

    return aTypes;
}

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

uno::Sequence< sal_Int8 > SAL_CALL GalleryTheme::getImplementationId()
    throw(uno::RuntimeException)
{
    const vos::OGuard                   aGuard( Application::GetSolarMutex() );
    static uno::Sequence< sal_Int8 >    aId;

    if( aId.getLength() == 0 )
    {
        aId.realloc( 16 );
        rtl_createUuid( reinterpret_cast< sal_uInt8* >( aId.getArray() ), 0, sal_True );
    }

    return aId;
}

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

uno::Type SAL_CALL GalleryTheme::getElementType()
    throw (uno::RuntimeException)
{
    return ::getCppuType( (const uno::Reference< gallery::XGalleryItem >*) 0);
}

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

sal_Bool SAL_CALL GalleryTheme::hasElements()
    throw (uno::RuntimeException)
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );

    return( ( mpTheme != NULL ) && ( mpTheme->GetObjectCount() > 0 ) );
}

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

sal_Int32 SAL_CALL GalleryTheme::getCount()
    throw (uno::RuntimeException)
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );

    return( mpTheme ? mpTheme->GetObjectCount() : 0 );
}

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

uno::Any SAL_CALL GalleryTheme::getByIndex( ::sal_Int32 nIndex )
    throw (lang::IndexOutOfBoundsException, lang::WrappedTargetException, uno::RuntimeException)
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );
    uno::Any            aRet;

    if( mpTheme )
    {
        if( ( nIndex < 0 ) || ( nIndex >= getCount() ) )
        {
            throw lang::IndexOutOfBoundsException();
        }
        else
        {
            const GalleryObject* pObj = mpTheme->ImplGetGalleryObject( nIndex );

            if( pObj )
                aRet = uno::makeAny( uno::Reference< gallery::XGalleryItem >( new GalleryItem( *this, *pObj ) ) );
        }
    }

    return aRet;
}

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

::rtl::OUString SAL_CALL GalleryTheme::getName(  )
    throw (uno::RuntimeException)
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );
    ::rtl::OUString     aRet;

    if( mpTheme )
        aRet = mpTheme->GetName();

    return aRet;
}

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

void SAL_CALL GalleryTheme::update(  )
    throw (uno::RuntimeException)
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );

    if( mpTheme )
    {
        const Link aDummyLink;
        mpTheme->Actualize( aDummyLink );
    }
}

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

::sal_Int32 SAL_CALL GalleryTheme::insertURLByIndex(
    const ::rtl::OUString& rURL, ::sal_Int32 nIndex )
    throw (lang::WrappedTargetException, uno::RuntimeException)
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );
    sal_Int32           nRet = -1;

    if( mpTheme )
    {
        try
        {
            const INetURLObject aURL( rURL );

            nIndex = ::std::max( ::std::min( nIndex, getCount() ), sal_Int32( 0 ) );

            if( ( aURL.GetProtocol() != INET_PROT_NOT_VALID ) && mpTheme->InsertURL( aURL, nIndex ) )
            {
                const GalleryObject* pObj = mpTheme->ImplGetGalleryObject( aURL );

                if( pObj )
                    nRet = mpTheme->ImplGetGalleryObjectPos( pObj );
            }
        }
        catch( ... )
        {
        }
    }

    return nRet;
}

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

::sal_Int32 SAL_CALL GalleryTheme::insertGraphicByIndex(
    const uno::Reference< graphic::XGraphic >& rxGraphic, sal_Int32 nIndex )
    throw (lang::WrappedTargetException, uno::RuntimeException)
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );
    sal_Int32           nRet = -1;

    if( mpTheme )
    {
        try
        {
            const Graphic aGraphic( rxGraphic );

            nIndex = ::std::max( ::std::min( nIndex, getCount() ), sal_Int32( 0 ) );

            if( mpTheme->InsertGraphic( aGraphic, nIndex ) )
                nRet = nIndex;
        }
        catch( ... )
        {
        }
    }

    return nRet;
}

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

::sal_Int32 SAL_CALL GalleryTheme::insertDrawingByIndex(
    const uno::Reference< lang::XComponent >& Drawing, sal_Int32 nIndex )
    throw (lang::WrappedTargetException, uno::RuntimeException)
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );
    sal_Int32           nRet = -1;

    if( mpTheme )
    {
        GalleryDrawingModel* pModel = GalleryDrawingModel::getImplementation( Drawing );

        if( pModel && pModel->GetDoc() && pModel->GetDoc()->ISA( FmFormModel ) )
        {
            //Here we're inserting something that's already a gallery theme drawing

            nIndex = ::std::max( ::std::min( nIndex, getCount() ), sal_Int32( 0 ) );

            if( mpTheme->InsertModel( *static_cast< FmFormModel* >( pModel->GetDoc() ), nIndex ) )
                nRet = nIndex;
        }
        else if (!pModel)
        {
            //#i80184# Try to do the right thing and make a Gallery drawing out of an ordinary
            //Drawing if possible.
            try
            {
                uno::Reference< drawing::XDrawPagesSupplier > xDrawPagesSupplier( Drawing, uno::UNO_QUERY_THROW );
                uno::Reference< drawing::XDrawPages > xDrawPages( xDrawPagesSupplier->getDrawPages(), uno::UNO_QUERY_THROW );
                uno::Reference< drawing::XDrawPage > xPage( xDrawPages->getByIndex( 0 ), uno::UNO_QUERY_THROW );
                SvxDrawPage* pUnoPage = xPage.is() ? SvxDrawPage::getImplementation( xPage ) : NULL;
                SdrModel* pOrigModel = pUnoPage ? pUnoPage->GetSdrPage()->GetModel() : NULL;
                SdrPage* pOrigPage = pUnoPage ? pUnoPage->GetSdrPage() : NULL;

                if (pOrigPage && pOrigModel)
                {
                    FmFormModel* pTmpModel = new FmFormModel(&pOrigModel->GetItemPool());
                    SdrPage* pNewPage = pOrigPage->Clone();
                    pTmpModel->InsertPage(pNewPage, 0);

                    uno::Reference< lang::XComponent > xDrawing( new GalleryDrawingModel( pTmpModel ) );
                    pTmpModel->setUnoModel( uno::Reference< uno::XInterface >::query( xDrawing ) );

                    nRet = insertDrawingByIndex( xDrawing, nIndex );
                    return nRet;
                }
            }
            catch (...)
            {
            }
        }
    }

    return nRet;
}

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

void SAL_CALL GalleryTheme::removeByIndex( sal_Int32 nIndex )
    throw (lang::IndexOutOfBoundsException, uno::RuntimeException)
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );

    if( mpTheme )
    {
        if( ( nIndex < 0 ) || ( nIndex >= getCount() ) )
            throw lang::IndexOutOfBoundsException();
        else
            mpTheme->RemoveObject( nIndex );
    }
}

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

void GalleryTheme::Notify( SfxBroadcaster&, const SfxHint& rHint )
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );
    const GalleryHint&  rGalleryHint = static_cast< const GalleryHint& >( rHint );

    switch( rGalleryHint.GetType() )
    {
        case( GALLERY_HINT_CLOSE_THEME ):
        {
            DBG_ASSERT( !mpTheme || mpGallery, "Theme is living without Gallery" );

            implReleaseItems( NULL );

            if( mpGallery && mpTheme )
            {
                mpGallery->ReleaseTheme( mpTheme, *this );
                mpTheme = NULL;
            }
        }
        break;

        case( GALLERY_HINT_CLOSE_OBJECT ):
        {
            GalleryObject* pObj = reinterpret_cast< GalleryObject* >( rGalleryHint.GetData1() );

            if( pObj )
                implReleaseItems( pObj );
        }
        break;

        default:
        break;
    }
}

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

void GalleryTheme::implReleaseItems( GalleryObject* pObj )
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );

    for( GalleryItemList::iterator aIter = maItemList.begin(); aIter != maItemList.end();  )
    {
        if( !pObj || ( (*aIter)->implGetObject() == pObj ) )
        {
            (*aIter)->implSetInvalid();
            aIter = maItemList.erase( aIter );
        }
        else
            ++aIter;
    }
}

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

::GalleryTheme* GalleryTheme::implGetTheme() const
{
    return mpTheme;
}

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

void GalleryTheme::implRegisterGalleryItem( ::unogallery::GalleryItem& rItem )
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );

//  DBG_ASSERT( maItemList.find( &rItem ) == maItemList.end(), "Item already registered" );
    maItemList.push_back( &rItem );
}

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

void GalleryTheme::implDeregisterGalleryItem( ::unogallery::GalleryItem& rItem )
{
    const ::vos::OGuard aGuard( Application::GetSolarMutex() );

//  DBG_ASSERT( maItemList.find( &rItem ) != maItemList.end(), "Item is not registered" );
    maItemList.remove( &rItem );
}

}

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


<commit_before>// Copyright 2016 Yahoo Inc.
// Licensed under the terms of the Apache 2.0 license.
// Please see LICENSE file in the project root for terms.
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <glog/logging.h>

#include "common.hpp"
#include "jni/com_yahoo_ml_jcaffe_Mat.h"
/*
 * Class:     com_yahoo_ml_jcaffe_Mat
 * Method:    allocate
 * Signature: (III[)Z
 */
JNIEXPORT jlong JNICALL Java_com_yahoo_ml_jcaffe_Mat_allocate
  (JNIEnv *env, jobject object, jint channels, jint height, jint width,  jbyteArray array) {

  jboolean isCopy = false;
  jbyte *data = env->GetByteArrayElements(array, &isCopy);
  if (data==NULL || env->ExceptionCheck()) {
    LOG(ERROR) << "invalid data array";
    return 0;
  }

  if (!isCopy) {
    jsize len = env->GetArrayLength(array);
    if (env->ExceptionCheck()) {
      LOG(ERROR) << "GetArrayLength failed";
      return 0;
    }
    jbyte* new_data = new jbyte[len];
    if (new_data == NULL) {
      LOG(ERROR) << "fail to jbyte[] for new data";
      return 0;
    }

    memcpy(new_data, data, len * sizeof(jbyte));
    //set new data
    data = new_data;
  }

  cv::Mat* native_ptr = NULL;
  try {
    /* create a native Mat object */
    native_ptr = new cv::Mat(height, width, CV_8UC(channels), data);
  } catch (std::exception& ex) {
    ThrowJavaException(ex, env);
    return 0;
  }
  /* associate native object with JVM object */
  SetNativeAddress(env, object, native_ptr);

  return (long) data;
}

/*
 * Class:     com_yahoo_ml_jcaffe_Mat
 * Method:    deallocate
 * Signature: (JZ)V
 */
JNIEXPORT void JNICALL Java_com_yahoo_ml_jcaffe_Mat_deallocate
  (JNIEnv *env, jobject object, jlong native_ptr, jlong dataaddress) {

  //Mat object is only one responsible for cleaning itself and it's data
  if(dataaddress){
    delete (jbyte*)dataaddress;
  }
  delete (cv::Mat*) native_ptr;
}

/*
 * Class:     com_yahoo_ml_jcaffe_Mat
 * Method:    decode
 * Signature: (IJ)Lcom/yahoo/ml/jcaffe/Mat;
 */
JNIEXPORT void JNICALL Java_com_yahoo_ml_jcaffe_Mat_decode
  (JNIEnv *env, jobject object, jint flags, jlong dataaddress) {

  try{
    cv::Mat* native_ptr = (cv::Mat*) GetNativeAddress(env, object);
    cv::imdecode(cv::_InputArray(*native_ptr), flags, native_ptr);
  } catch (const std::exception& ex) {
    ThrowJavaException(ex, env);
    return;
  }

  jclass claz = env->GetObjectClass(object);
  if (claz == NULL || env->ExceptionCheck()) {
    LOG(ERROR) << "unable to get object's class";
    ThrowCosJavaException((char*)"unable to get the object's class", env);
    return;
  }

  if (dataaddress){
    delete (jbyte*)dataaddress;
  }
}

/* * Class:     com_yahoo_ml_jcaffe_Mat
 * Method:    resize
 * Signature: (II)Lcom/yahoo/ml/jcaffe/Mat;
 */
JNIEXPORT void JNICALL Java_com_yahoo_ml_jcaffe_Mat_resize
   (JNIEnv *env, jobject object, jint height, jint width, jlong dataaddress) {

  if (height < 0 || width < 0) {
    ThrowCosJavaException((char*)"invalid dimensions to resize", env);
    return;
  }
  try{
    cv::Mat* native_ptr = (cv::Mat*) GetNativeAddress(env, object);
    cv::Size size(width, height);
    cv::resize(cv::_InputArray(*native_ptr), cv::_OutputArray(*native_ptr), size, 0, 0, cv::INTER_LINEAR);
  } catch (const std::exception& ex) {
    ThrowJavaException(ex, env);
    return;
  }

  jclass claz = env->GetObjectClass(object);
  if (claz == NULL || env->ExceptionCheck()) {
    LOG(ERROR) << "unable to get object's class";
    ThrowCosJavaException((char*)"unable to get the object's class", env);
    return;
  }

  if (dataaddress){
    delete (jbyte*)dataaddress;
  }
}

/*
 * Class:     com_yahoo_ml_jcaffe_Mat
 * Method:    height
 * Signature: ()I
 */

JNIEXPORT jint JNICALL Java_com_yahoo_ml_jcaffe_Mat_height
  (JNIEnv *env, jobject object) {
  cv::Mat* native_ptr = NULL;
  try {
    native_ptr = (cv::Mat*) GetNativeAddress(env, object);
    return native_ptr->rows;
  } catch(const std::exception& ex) {
    ThrowJavaException(ex, env);
    return -1;
  }
}

/*
 * Class:     com_yahoo_ml_jcaffe_Mat
 * Method:    width
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_com_yahoo_ml_jcaffe_Mat_width
  (JNIEnv *env, jobject object) {
  cv::Mat* native_ptr = NULL;
  try {
    native_ptr = (cv::Mat*) GetNativeAddress(env, object);
    return native_ptr->cols;
  } catch(const std::exception& ex) {
    ThrowJavaException(ex, env);
    return -1;
  }
}

/*
 * Class:     com_yahoo_ml_jcaffe_Mat
 * Method:    data
 * Signature: ()[B
 */

JNIEXPORT jbyteArray JNICALL Java_com_yahoo_ml_jcaffe_Mat_data
   (JNIEnv *env, jobject object) {
  cv::Mat* native_ptr = NULL;
  int size = 0;
  try {
    native_ptr = (cv::Mat*) GetNativeAddress(env, object);
    size = native_ptr->total() * native_ptr->elemSize();
  } catch(const std::exception& ex) {
    ThrowJavaException(ex, env);
    return NULL;
  }

  jbyteArray dataarray = env->NewByteArray(size);
  if(dataarray == NULL || env->ExceptionCheck()){
    LOG(ERROR) << "Out of memory while allocating array for Mat data" ;
    return NULL;
  }
  env->SetByteArrayRegion(dataarray,0, size, (jbyte*)native_ptr->data);
  if (env->ExceptionCheck()) {
    LOG(ERROR) << "SetByteArrayRegion failed";
    return NULL;
  }
  return dataarray;
}

/*
 * Class:     com_yahoo_ml_jcaffe_Mat
 * Method:    channels
 * Signature: ()I
 */

JNIEXPORT jint JNICALL Java_com_yahoo_ml_jcaffe_Mat_channels
(JNIEnv *env, jobject object) {
  cv::Mat* native_ptr = NULL;
  try {
    native_ptr = (cv::Mat*) GetNativeAddress(env, object);
    return native_ptr->channels();
  } catch(const std::exception& ex) {
    ThrowJavaException(ex, env);
    return -1;
  }
}
<commit_msg>JNI addition<commit_after>// Copyright 2016 Yahoo Inc.
// Licensed under the terms of the Apache 2.0 license.
// Please see LICENSE file in the project root for terms.
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <glog/logging.h>

#include "common.hpp"
#include "jni/com_yahoo_ml_jcaffe_Mat.h"
/*
 * Class:     com_yahoo_ml_jcaffe_Mat
 * Method:    allocate
 * Signature: (III[)Z
 */
JNIEXPORT jlong JNICALL Java_com_yahoo_ml_jcaffe_Mat_allocate
  (JNIEnv *env, jobject object, jint channels, jint height, jint width,  jbyteArray array) {

  jboolean isCopy = false;
  jbyte *data = env->GetByteArrayElements(array, &isCopy);
  if (data==NULL || env->ExceptionCheck()) {
    LOG(ERROR) << "invalid data array";
    return 0;
  }

  if (!isCopy) {
    jsize len = env->GetArrayLength(array);
    if (env->ExceptionCheck()) {
      LOG(ERROR) << "GetArrayLength failed";
      return 0;
    }
    jbyte* new_data = new jbyte[len];
    if (new_data == NULL) {
      LOG(ERROR) << "fail to jbyte[] for new data";
      return 0;
    }

    memcpy(new_data, data, len * sizeof(jbyte));
    //set new data
    data = new_data;
  }

  cv::Mat* native_ptr = NULL;
  try {
    /* create a native Mat object */
    native_ptr = new cv::Mat(height, width, CV_8UC(channels), data);
  } catch (std::exception& ex) {
    ThrowJavaException(ex, env);
    return 0;
  }
  /* associate native object with JVM object */
  SetNativeAddress(env, object, native_ptr);

  return (long) data;
}

/*
 * Class:     com_yahoo_ml_jcaffe_Mat
 * Method:    deallocate
 * Signature: (JZ)V
 */
JNIEXPORT void JNICALL Java_com_yahoo_ml_jcaffe_Mat_deallocate
  (JNIEnv *env, jobject object, jlong native_ptr, jlong dataaddress) {

  //Mat object is only one responsible for cleaning itself and it's data
  if(dataaddress){
    delete[] (jbyte*)dataaddress;
  }
  delete (cv::Mat*) native_ptr;
}

/*
 * Class:     com_yahoo_ml_jcaffe_Mat
 * Method:    decode
 * Signature: (IJ)Lcom/yahoo/ml/jcaffe/Mat;
 */
JNIEXPORT void JNICALL Java_com_yahoo_ml_jcaffe_Mat_decode
  (JNIEnv *env, jobject object, jint flags, jlong dataaddress) {

  try{
    cv::Mat* native_ptr = (cv::Mat*) GetNativeAddress(env, object);
    cv::imdecode(cv::_InputArray(*native_ptr), flags, native_ptr);
  } catch (const std::exception& ex) {
    ThrowJavaException(ex, env);
    return;
  }

  jclass claz = env->GetObjectClass(object);
  if (claz == NULL || env->ExceptionCheck()) {
    LOG(ERROR) << "unable to get object's class";
    ThrowCosJavaException((char*)"unable to get the object's class", env);
    return;
  }

  if (dataaddress){
    delete (jbyte*)dataaddress;
  }
}

/* * Class:     com_yahoo_ml_jcaffe_Mat
 * Method:    resize
 * Signature: (II)Lcom/yahoo/ml/jcaffe/Mat;
 */
JNIEXPORT void JNICALL Java_com_yahoo_ml_jcaffe_Mat_resize
   (JNIEnv *env, jobject object, jint height, jint width, jlong dataaddress) {

  if (height < 0 || width < 0) {
    ThrowCosJavaException((char*)"invalid dimensions to resize", env);
    return;
  }
  try{
    cv::Mat* native_ptr = (cv::Mat*) GetNativeAddress(env, object);
    cv::Size size(width, height);
    cv::resize(cv::_InputArray(*native_ptr), cv::_OutputArray(*native_ptr), size, 0, 0, cv::INTER_LINEAR);
  } catch (const std::exception& ex) {
    ThrowJavaException(ex, env);
    return;
  }

  jclass claz = env->GetObjectClass(object);
  if (claz == NULL || env->ExceptionCheck()) {
    LOG(ERROR) << "unable to get object's class";
    ThrowCosJavaException((char*)"unable to get the object's class", env);
    return;
  }

  if (dataaddress){
    delete (jbyte*)dataaddress;
  }
}

/*
 * Class:     com_yahoo_ml_jcaffe_Mat
 * Method:    height
 * Signature: ()I
 */

JNIEXPORT jint JNICALL Java_com_yahoo_ml_jcaffe_Mat_height
  (JNIEnv *env, jobject object) {
  cv::Mat* native_ptr = NULL;
  try {
    native_ptr = (cv::Mat*) GetNativeAddress(env, object);
    return native_ptr->rows;
  } catch(const std::exception& ex) {
    ThrowJavaException(ex, env);
    return -1;
  }
}

/*
 * Class:     com_yahoo_ml_jcaffe_Mat
 * Method:    width
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_com_yahoo_ml_jcaffe_Mat_width
  (JNIEnv *env, jobject object) {
  cv::Mat* native_ptr = NULL;
  try {
    native_ptr = (cv::Mat*) GetNativeAddress(env, object);
    return native_ptr->cols;
  } catch(const std::exception& ex) {
    ThrowJavaException(ex, env);
    return -1;
  }
}

/*
 * Class:     com_yahoo_ml_jcaffe_Mat
 * Method:    data
 * Signature: ()[B
 */

JNIEXPORT jbyteArray JNICALL Java_com_yahoo_ml_jcaffe_Mat_data
   (JNIEnv *env, jobject object) {
  cv::Mat* native_ptr = NULL;
  int size = 0;
  try {
    native_ptr = (cv::Mat*) GetNativeAddress(env, object);
    size = native_ptr->total() * native_ptr->elemSize();
  } catch(const std::exception& ex) {
    ThrowJavaException(ex, env);
    return NULL;
  }

  jbyteArray dataarray = env->NewByteArray(size);
  if(dataarray == NULL || env->ExceptionCheck()){
    LOG(ERROR) << "Out of memory while allocating array for Mat data" ;
    return NULL;
  }
  env->SetByteArrayRegion(dataarray,0, size, (jbyte*)native_ptr->data);
  if (env->ExceptionCheck()) {
    LOG(ERROR) << "SetByteArrayRegion failed";
    return NULL;
  }
  return dataarray;
}

/*
 * Class:     com_yahoo_ml_jcaffe_Mat
 * Method:    channels
 * Signature: ()I
 */

JNIEXPORT jint JNICALL Java_com_yahoo_ml_jcaffe_Mat_channels
(JNIEnv *env, jobject object) {
  cv::Mat* native_ptr = NULL;
  try {
    native_ptr = (cv::Mat*) GetNativeAddress(env, object);
    return native_ptr->channels();
  } catch(const std::exception& ex) {
    ThrowJavaException(ex, env);
    return -1;
  }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: textcontrolcombo.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: vg $ $Date: 2007-10-22 15:24:43 $
 *
 *  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 _TEXTCONTROLCOMBO_HXX
#define _TEXTCONTROLCOMBO_HXX

#ifndef _FIXED_HXX
#include <vcl/fixed.hxx>
#endif

#include <vcl/field.hxx>

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif

class SW_DLLPUBLIC TextControlCombo : public Window
{
protected:

    Control&    mrCtrl;
    FixedText&  mrFTbefore;
    FixedText&  mrFTafter;

public:

    using Window::Enable;
    using Window::Disable;

                TextControlCombo( Window* _pParent, const ResId& _rResId,
                            Control& _rCtrl, FixedText& _rFTbefore, FixedText& _rFTafter );
    virtual     ~TextControlCombo();

    void        Arrange( FixedText& _rOrg, BOOL bShow = true );

    // identical to window functionality
    void        Show( BOOL bVisible = TRUE, USHORT nFlags = 0 );
    void        Hide( USHORT nFlags = 0 ) { Show( FALSE, nFlags ); }

    void        Enable( BOOL bEnable = TRUE, BOOL bChild = TRUE );
    void        Disable( BOOL bChild = TRUE ) { Enable( FALSE, bChild ); }
};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.6.216); FILE MERGED 2008/04/01 12:55:32 thb 1.6.216.2: #i85898# Stripping all external header guards 2008/03/31 16:58:42 rt 1.6.216.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: textcontrolcombo.hxx,v $
 * $Revision: 1.7 $
 *
 * 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 _TEXTCONTROLCOMBO_HXX
#define _TEXTCONTROLCOMBO_HXX

#ifndef _FIXED_HXX
#include <vcl/fixed.hxx>
#endif

#include <vcl/field.hxx>
#include "swdllapi.h"

class SW_DLLPUBLIC TextControlCombo : public Window
{
protected:

    Control&    mrCtrl;
    FixedText&  mrFTbefore;
    FixedText&  mrFTafter;

public:

    using Window::Enable;
    using Window::Disable;

                TextControlCombo( Window* _pParent, const ResId& _rResId,
                            Control& _rCtrl, FixedText& _rFTbefore, FixedText& _rFTafter );
    virtual     ~TextControlCombo();

    void        Arrange( FixedText& _rOrg, BOOL bShow = true );

    // identical to window functionality
    void        Show( BOOL bVisible = TRUE, USHORT nFlags = 0 );
    void        Hide( USHORT nFlags = 0 ) { Show( FALSE, nFlags ); }

    void        Enable( BOOL bEnable = TRUE, BOOL bChild = TRUE );
    void        Disable( BOOL bChild = TRUE ) { Enable( FALSE, bChild ); }
};

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * 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: null_spritecanvas.cxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <canvas/debug.hxx>
#include <canvas/verbosetrace.hxx>
#include <canvas/canvastools.hxx>

#include <osl/mutex.hxx>

#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>

#include <cppuhelper/factory.hxx>
#include <cppuhelper/implementationentry.hxx>
#include <comphelper/servicedecl.hxx>

#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/tools/canvastools.hxx>
#include <basegfx/numeric/ftools.hxx>

#include "null_spritecanvas.hxx"

using namespace ::com::sun::star;

#define SERVICE_NAME "com.sun.star.rendering.NullCanvas"

namespace nullcanvas
{
    SpriteCanvas::SpriteCanvas( const uno::Sequence< uno::Any >&                aArguments,
                                const uno::Reference< uno::XComponentContext >& rxContext ) :
        mxComponentContext( rxContext )
    {
        // #i64742# Only call initialize when not in probe mode
        if( aArguments.getLength() != 0 )
            initialize( aArguments );
    }

    void SpriteCanvas::initialize( const uno::Sequence< uno::Any >& aArguments )
    {
        VERBOSE_TRACE( "SpriteCanvas::initialize called" );

        // At index 1, we expect a system window handle here,
        // containing a pointer to a valid window, on which to output
        // At index 2, we expect the current window bound rect
        CHECK_AND_THROW( aArguments.getLength() >= 4 &&
                         aArguments[1].getValueTypeClass() == uno::TypeClass_LONG,
                         "SpriteCanvas::initialize: wrong number of arguments, or wrong types" );

        awt::Rectangle aRect;
        aArguments[2] >>= aRect;
        const ::basegfx::B2ISize aSize(aRect.Width,
                                       aRect.Height);

        sal_Bool bIsFullscreen( sal_False );
        aArguments[3] >>= bIsFullscreen;

        // setup helper
        maDeviceHelper.init( *this,
                             aSize,
                             bIsFullscreen );
        maCanvasHelper.init( maRedrawManager,
                             *this,
                             aSize,
                             false );
    }

    void SAL_CALL SpriteCanvas::disposing()
    {
        ::osl::MutexGuard aGuard( m_aMutex );

        mxComponentContext.clear();

        // forward to parent
        SpriteCanvasBaseT::disposing();
    }

    ::sal_Bool SAL_CALL SpriteCanvas::showBuffer( ::sal_Bool bUpdateAll ) throw (uno::RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex );

        // avoid repaints on hidden window (hidden: not mapped to
        // screen). Return failure, since the screen really has _not_
        // been updated (caller should try again later)
        return !mbIsVisible ? false : SpriteCanvasBaseT::showBuffer( bUpdateAll );
    }

    ::sal_Bool SAL_CALL SpriteCanvas::switchBuffer( ::sal_Bool bUpdateAll ) throw (uno::RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex );

        // avoid repaints on hidden window (hidden: not mapped to
        // screen). Return failure, since the screen really has _not_
        // been updated (caller should try again later)
        return !mbIsVisible ? false : SpriteCanvasBaseT::switchBuffer( bUpdateAll );
    }

    sal_Bool SAL_CALL SpriteCanvas::updateScreen( sal_Bool bUpdateAll ) throw (uno::RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex );

        // avoid repaints on hidden window (hidden: not mapped to
        // screen). Return failure, since the screen really has _not_
        // been updated (caller should try again later)
        return !mbIsVisible ? false : maCanvasHelper.updateScreen(
            ::basegfx::unotools::b2IRectangleFromAwtRectangle(maBounds),
            bUpdateAll,
            mbSurfaceDirty );
    }

    ::rtl::OUString SAL_CALL SpriteCanvas::getServiceName(  ) throw (uno::RuntimeException)
    {
        return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICE_NAME ) );
    }

    namespace sdecl = comphelper::service_decl;
#if defined (__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ <= 3)
    sdecl::class_<SpriteCanvas, sdecl::with_args<true> > serviceImpl;
    const sdecl::ServiceDecl nullCanvasDecl(
        serviceImpl,
#else
    const sdecl::ServiceDecl nullCanvasDecl(
        sdecl::class_<SpriteCanvas, sdecl::with_args<true> >(),
#endif
        "com.sun.star.comp.rendering.NullCanvas",
        SERVICE_NAME );
}

// The C shared lib entry points
COMPHELPER_SERVICEDECL_EXPORTS1(nullcanvas::nullCanvasDecl)
<commit_msg>INTEGRATION: CWS canvas05 (1.5.56); FILE MERGED 2008/06/09 12:51:48 thb 1.5.56.3: #i88081# Join from CWS impress144 (fixing the dxcanvas crash), extended for the other canvas impls 2008/04/21 07:27:25 thb 1.5.56.2: RESYNC: (1.5-1.6); FILE MERGED 2007/10/01 13:02:02 thb 1.5.56.1: #i78888# #i78925# #i79258# #i79437# Merge from CWS picom<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: null_spritecanvas.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <canvas/debug.hxx>
#include <tools/diagnose_ex.h>
#include <canvas/verbosetrace.hxx>
#include <canvas/canvastools.hxx>

#include <osl/mutex.hxx>

#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>

#include <cppuhelper/factory.hxx>
#include <cppuhelper/implementationentry.hxx>
#include <comphelper/servicedecl.hxx>

#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/tools/canvastools.hxx>
#include <basegfx/numeric/ftools.hxx>

#include "null_spritecanvas.hxx"

using namespace ::com::sun::star;

#define SERVICE_NAME "com.sun.star.rendering.NullCanvas"

namespace nullcanvas
{
    SpriteCanvas::SpriteCanvas( const uno::Sequence< uno::Any >&                aArguments,
                                const uno::Reference< uno::XComponentContext >& rxContext ) :
        maArguments(aArguments),
        mxComponentContext( rxContext )
    {
    }

    void SpriteCanvas::initialize()
    {
        // #i64742# Only call initialize when not in probe mode
        if( maArguments.getLength() == 0 )
            return;

        VERBOSE_TRACE( "SpriteCanvas::initialize called" );

        // At index 1, we expect a system window handle here,
        // containing a pointer to a valid window, on which to output
        // At index 2, we expect the current window bound rect
        ENSURE_ARG_OR_THROW( maArguments.getLength() >= 4 &&
                             maArguments[1].getValueTypeClass() == uno::TypeClass_LONG,
                             "SpriteCanvas::initialize: wrong number of arguments, or wrong types" );

        awt::Rectangle aRect;
        maArguments[2] >>= aRect;
        const ::basegfx::B2ISize aSize(aRect.Width,
                                       aRect.Height);

        sal_Bool bIsFullscreen( sal_False );
        maArguments[3] >>= bIsFullscreen;

        // setup helper
        maDeviceHelper.init( *this,
                             aSize,
                             bIsFullscreen );
        maCanvasHelper.init( maRedrawManager,
                             *this,
                             aSize,
                             false );

        maArguments.realloc(0);
    }

    void SAL_CALL SpriteCanvas::disposing()
    {
        ::osl::MutexGuard aGuard( m_aMutex );

        mxComponentContext.clear();

        // forward to parent
        SpriteCanvasBaseT::disposing();
    }

    ::sal_Bool SAL_CALL SpriteCanvas::showBuffer( ::sal_Bool bUpdateAll ) throw (uno::RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex );

        // avoid repaints on hidden window (hidden: not mapped to
        // screen). Return failure, since the screen really has _not_
        // been updated (caller should try again later)
        return !mbIsVisible ? false : SpriteCanvasBaseT::showBuffer( bUpdateAll );
    }

    ::sal_Bool SAL_CALL SpriteCanvas::switchBuffer( ::sal_Bool bUpdateAll ) throw (uno::RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex );

        // avoid repaints on hidden window (hidden: not mapped to
        // screen). Return failure, since the screen really has _not_
        // been updated (caller should try again later)
        return !mbIsVisible ? false : SpriteCanvasBaseT::switchBuffer( bUpdateAll );
    }

    sal_Bool SAL_CALL SpriteCanvas::updateScreen( sal_Bool bUpdateAll ) throw (uno::RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex );

        // avoid repaints on hidden window (hidden: not mapped to
        // screen). Return failure, since the screen really has _not_
        // been updated (caller should try again later)
        return !mbIsVisible ? false : maCanvasHelper.updateScreen(
            ::basegfx::unotools::b2IRectangleFromAwtRectangle(maBounds),
            bUpdateAll,
            mbSurfaceDirty );
    }

    ::rtl::OUString SAL_CALL SpriteCanvas::getServiceName(  ) throw (uno::RuntimeException)
    {
        return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICE_NAME ) );
    }

    static uno::Reference<uno::XInterface> initCanvas( SpriteCanvas* pCanvas )
    {
        uno::Reference<uno::XInterface> xRet(static_cast<cppu::OWeakObject*>(pCanvas));
        pCanvas->initialize();
        return xRet;
    }

    namespace sdecl = comphelper::service_decl;
    sdecl::class_<SpriteCanvas, sdecl::with_args<true> > serviceImpl(&initCanvas);
    const sdecl::ServiceDecl nullCanvasDecl(
        serviceImpl,
        "com.sun.star.comp.rendering.NullCanvas",
        SERVICE_NAME );
}

// The C shared lib entry points
COMPHELPER_SERVICEDECL_EXPORTS1(nullcanvas::nullCanvasDecl)
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: null_spritehelper.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2007-07-17 14:23:20 $
 *
 *  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_canvas.hxx"

#include <canvas/debug.hxx>
#include <canvas/verbosetrace.hxx>

#include <rtl/logfile.hxx>
#include <rtl/math.hxx>

#include <canvas/canvastools.hxx>

#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/tools/canvastools.hxx>
#include <basegfx/numeric/ftools.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygonrasterconverter.hxx>
#include <basegfx/polygon/b2dpolygontriangulator.hxx>
#include <basegfx/polygon/b2dpolygoncutandtouch.hxx>

#include "null_canvascustomsprite.hxx"
#include "null_spritehelper.hxx"

#include <memory>

using namespace ::com::sun::star;

namespace nullcanvas
{
    SpriteHelper::SpriteHelper() :
        mpSpriteCanvas(),
        mbTextureDirty( true )
    {
    }

    void SpriteHelper::init( const geometry::RealSize2D&    rSpriteSize,
                             const SpriteCanvasRef&         rSpriteCanvas )
    {
        ENSURE_AND_THROW( rSpriteCanvas.get(),
                          "SpriteHelper::init(): Invalid device, sprite canvas or surface" );

        mpSpriteCanvas     = rSpriteCanvas;
        mbTextureDirty     = true;

        // also init base class
        CanvasCustomSpriteHelper::init( rSpriteSize,
                                        rSpriteCanvas.get() );
    }

    void SpriteHelper::disposing()
    {
        mpSpriteCanvas.clear();

        // forward to parent
        CanvasCustomSpriteHelper::disposing();
    }

    void SpriteHelper::redraw( bool& /*io_bSurfaceDirty*/ ) const
    {
        // TODO
    }

    ::basegfx::B2DPolyPolygon SpriteHelper::polyPolygonFromXPolyPolygon2D( uno::Reference< rendering::XPolyPolygon2D >& xPoly ) const
    {
        return ::canvas::tools::polyPolygonFromXPolyPolygon2D( xPoly );
    }
}
<commit_msg>INTEGRATION: CWS changefileheader (1.5.50); FILE MERGED 2008/03/28 16:35:09 rt 1.5.50.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: null_spritehelper.cxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <canvas/debug.hxx>
#include <canvas/verbosetrace.hxx>

#include <rtl/logfile.hxx>
#include <rtl/math.hxx>

#include <canvas/canvastools.hxx>

#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/tools/canvastools.hxx>
#include <basegfx/numeric/ftools.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygonrasterconverter.hxx>
#include <basegfx/polygon/b2dpolygontriangulator.hxx>
#include <basegfx/polygon/b2dpolygoncutandtouch.hxx>

#include "null_canvascustomsprite.hxx"
#include "null_spritehelper.hxx"

#include <memory>

using namespace ::com::sun::star;

namespace nullcanvas
{
    SpriteHelper::SpriteHelper() :
        mpSpriteCanvas(),
        mbTextureDirty( true )
    {
    }

    void SpriteHelper::init( const geometry::RealSize2D&    rSpriteSize,
                             const SpriteCanvasRef&         rSpriteCanvas )
    {
        ENSURE_AND_THROW( rSpriteCanvas.get(),
                          "SpriteHelper::init(): Invalid device, sprite canvas or surface" );

        mpSpriteCanvas     = rSpriteCanvas;
        mbTextureDirty     = true;

        // also init base class
        CanvasCustomSpriteHelper::init( rSpriteSize,
                                        rSpriteCanvas.get() );
    }

    void SpriteHelper::disposing()
    {
        mpSpriteCanvas.clear();

        // forward to parent
        CanvasCustomSpriteHelper::disposing();
    }

    void SpriteHelper::redraw( bool& /*io_bSurfaceDirty*/ ) const
    {
        // TODO
    }

    ::basegfx::B2DPolyPolygon SpriteHelper::polyPolygonFromXPolyPolygon2D( uno::Reference< rendering::XPolyPolygon2D >& xPoly ) const
    {
        return ::canvas::tools::polyPolygonFromXPolyPolygon2D( xPoly );
    }
}
<|endoftext|>


<commit_before>#include "chainerx/routines/pooling.h"

#include <cstdint>
#include <memory>
#include <utility>
#include <vector>

#include "chainerx/array.h"
#include "chainerx/backprop_mode.h"
#include "chainerx/backward_builder.h"
#include "chainerx/backward_context.h"
#include "chainerx/constant.h"
#include "chainerx/device.h"
#include "chainerx/error.h"
#include "chainerx/graph.h"
#include "chainerx/routines/math.h"
#include "chainerx/routines/routines_util.h"
#include "chainerx/stack_vector.h"

namespace chainerx {
namespace {

void CheckPoolInputs(
        const Array& x,
        const StackVector<int64_t, kMaxNdim>& kernel_size,
        const StackVector<int64_t, kMaxNdim>& stride,
        const StackVector<int64_t, kMaxNdim>& pad) {
    int8_t ndim = x.ndim() - 2;  // Number of spatial dimensions.
    if (static_cast<int8_t>(kernel_size.size()) != ndim) {
        throw DimensionError{"Wrong numbers of kernel size dimensions ", kernel_size.size(), " for input with ", x.ndim(), " dimensions."};
    }
    if (static_cast<int8_t>(stride.size()) != ndim) {
        throw DimensionError{"Wrong numbers of strides ", stride.size(), " for input with ", x.ndim(), " dimensions."};
    }
    if (static_cast<int8_t>(pad.size()) != ndim) {
        throw DimensionError{"Wrong numbers of paddings ", pad.size(), " for input with ", x.ndim(), " dimensions."};
    }
    if (ndim == 0) {
        throw DimensionError{"Pooling operation requires at least one spatial dimension."};
    }
}

}  // namespace

Array MaxPool(
        const Array& x,
        const StackVector<int64_t, kMaxNdim>& kernel_size,
        const StackVector<int64_t, kMaxNdim>& stride,
        const StackVector<int64_t, kMaxNdim>& pad,
        bool cover_all) {
    CheckPoolInputs(x, kernel_size, stride, pad);
    std::unique_ptr<MaxPoolForwardBackward> fb = x.device().GetMaxPoolForwardBackward(kernel_size, stride, pad, cover_all);

    Array out = fb->Forward(x.AsGradStopped());
    internal::MakeViewForForwardBackwardOutput(out);

    // Supporting arbitrary number of backwards using a recursive definition.
    // TODO(hvy): Test backward of double backward.
    struct MaxPoolBwd {
        void operator()(BackwardContext& bctx1) {
            const Array& gout = bctx1.output_grad();
            Array gx = fb->Backward(gout.AsGradStopped());
            internal::MakeViewForForwardBackwardOutput(gx);
            {
                BackwardBuilder bb2{"max_pooling_backward", gout, gx};
                if (BackwardBuilder::Target bt2 = bb2.CreateTarget(0)) {
                    bt2.Define([st = std::move(*this)](BackwardContext& bctx2) {
                        const Array& ggx = bctx2.output_grad();
                        Array ggout = st.fb->DoubleBackward(ggx.AsGradStopped());
                        internal::MakeViewForForwardBackwardOutput(ggout);
                        // Make ggout further backpropable.
                        {
                            BackwardBuilder bb3{"max_pooling_double_backward", ggx, ggout};
                            if (BackwardBuilder::Target bt3 = bb3.CreateTarget(0)) {
                                bt3.Define(std::move(st));
                            }
                            bb3.Finalize();
                        }
                        bctx2.input_grad() = ggout;
                    });
                }
                bb2.Finalize();
            }
            bctx1.input_grad() = gx;
        }

        StackVector<int64_t, kMaxNdim> kernel_size;
        StackVector<int64_t, kMaxNdim> stride;
        StackVector<int64_t, kMaxNdim> pad;
        bool cover_all;
        std::shared_ptr<MaxPoolForwardBackward> fb;
    };

    {
        BackwardBuilder bb1{"max_pooling", x, out};
        if (BackwardBuilder::Target bt1 = bb1.CreateTarget(0)) {
            bt1.Define(MaxPoolBwd{kernel_size, stride, pad, cover_all, std::move(fb)});
        }
        bb1.Finalize();
    }
    return out;
}

Array AveragePool(
        const Array& x,
        const StackVector<int64_t, kMaxNdim>& kernel_size,
        const StackVector<int64_t, kMaxNdim>& stride,
        const StackVector<int64_t, kMaxNdim>& pad,
        AveragePoolPadMode pad_mode) {
    if (GetKind(x.dtype()) != DtypeKind::kFloat) {
        throw DtypeError("cannot apply average pooling to ", x.dtype(), " array (floatXX array is expected)");
    }

    CheckPoolInputs(x, kernel_size, stride, pad);
    std::shared_ptr<AveragePoolForwardBackward> fb = x.device().GetAveragePoolForwardBackward(kernel_size, stride, pad, pad_mode);
    Array out = fb->Forward(x.AsGradStopped());
    internal::MakeViewForForwardBackwardOutput(out);
    {
        BackwardBuilder bb1{"average_pool", x, out};
        if (BackwardBuilder::Target bt1 = bb1.CreateTarget(0)) {
            bt1.Define([fb = std::move(fb), kernel_size, stride, pad, pad_mode](BackwardContext& bctx) {
                const Array& gout = bctx.output_grad();
                Array gx = fb->Backward(gout.AsGradStopped());
                internal::MakeViewForForwardBackwardOutput(gx);
                {
                    BackwardBuilder bb2{"average_pool_backward", gout, gx};
                    if (BackwardBuilder::Target bt2 = bb2.CreateTarget(0)) {
                        bt2.Define([kernel_size, stride, pad, pad_mode](BackwardContext& bctx2) {
                            const Array& ggx = bctx2.output_grad();
                            bctx2.input_grad() = AveragePool(ggx, kernel_size, stride, pad, pad_mode);
                        });
                    }
                    bb2.Finalize();
                }
                bctx.input_grad() = gx;
            });
        }
        bb1.Finalize();
    }
    return out;
}

}  // namespace chainerx
<commit_msg>fixed segv<commit_after>#include "chainerx/routines/pooling.h"

#include <cstdint>
#include <memory>
#include <utility>
#include <vector>

#include "chainerx/array.h"
#include "chainerx/backprop_mode.h"
#include "chainerx/backward_builder.h"
#include "chainerx/backward_context.h"
#include "chainerx/constant.h"
#include "chainerx/device.h"
#include "chainerx/error.h"
#include "chainerx/graph.h"
#include "chainerx/routines/math.h"
#include "chainerx/routines/routines_util.h"
#include "chainerx/stack_vector.h"

namespace chainerx {
namespace {

void CheckPoolInputs(
        const Array& x,
        const StackVector<int64_t, kMaxNdim>& kernel_size,
        const StackVector<int64_t, kMaxNdim>& stride,
        const StackVector<int64_t, kMaxNdim>& pad) {
    int8_t ndim = x.ndim() - 2;  // Number of spatial dimensions.
    if (static_cast<int8_t>(kernel_size.size()) != ndim) {
        throw DimensionError{"Wrong numbers of kernel size dimensions ", kernel_size.size(), " for input with ", x.ndim(), " dimensions."};
    }
    if (static_cast<int8_t>(stride.size()) != ndim) {
        throw DimensionError{"Wrong numbers of strides ", stride.size(), " for input with ", x.ndim(), " dimensions."};
    }
    if (static_cast<int8_t>(pad.size()) != ndim) {
        throw DimensionError{"Wrong numbers of paddings ", pad.size(), " for input with ", x.ndim(), " dimensions."};
    }
    if (ndim == 0) {
        throw DimensionError{"Pooling operation requires at least one spatial dimension."};
    }
}

}  // namespace

Array MaxPool(
        const Array& x,
        const StackVector<int64_t, kMaxNdim>& kernel_size,
        const StackVector<int64_t, kMaxNdim>& stride,
        const StackVector<int64_t, kMaxNdim>& pad,
        bool cover_all) {
    CheckPoolInputs(x, kernel_size, stride, pad);
    std::unique_ptr<MaxPoolForwardBackward> fb = x.device().GetMaxPoolForwardBackward(kernel_size, stride, pad, cover_all);

    Array out = fb->Forward(x.AsGradStopped());
    internal::MakeViewForForwardBackwardOutput(out);

    // Supporting arbitrary number of backwards using a recursive definition.
    // TODO(hvy): Test backward of double backward.
    struct MaxPoolBwd {
        void operator()(BackwardContext& bctx1) {
            const Array& gout = bctx1.output_grad();
            Array gx = fb->Backward(gout.AsGradStopped());
            internal::MakeViewForForwardBackwardOutput(gx);
            {
                BackwardBuilder bb2{"max_pooling_backward", gout, gx};
                if (BackwardBuilder::Target bt2 = bb2.CreateTarget(0)) {
                    bt2.Define([st = *this](BackwardContext& bctx2) {
                        const Array& ggx = bctx2.output_grad();
                        Array ggout = st.fb->DoubleBackward(ggx.AsGradStopped());
                        internal::MakeViewForForwardBackwardOutput(ggout);
                        // Make ggout further backpropable.
                        {
                            BackwardBuilder bb3{"max_pooling_double_backward", ggx, ggout};
                            if (BackwardBuilder::Target bt3 = bb3.CreateTarget(0)) {
                                bt3.Define(std::move(st));
                            }
                            bb3.Finalize();
                        }
                        bctx2.input_grad() = ggout;
                    });
                }
                bb2.Finalize();
            }
            bctx1.input_grad() = gx;
        }

        StackVector<int64_t, kMaxNdim> kernel_size;
        StackVector<int64_t, kMaxNdim> stride;
        StackVector<int64_t, kMaxNdim> pad;
        bool cover_all;
        std::shared_ptr<MaxPoolForwardBackward> fb;
    };

    {
        BackwardBuilder bb1{"max_pooling", x, out};
        if (BackwardBuilder::Target bt1 = bb1.CreateTarget(0)) {
            bt1.Define(MaxPoolBwd{kernel_size, stride, pad, cover_all, std::move(fb)});
        }
        bb1.Finalize();
    }
    return out;
}

Array AveragePool(
        const Array& x,
        const StackVector<int64_t, kMaxNdim>& kernel_size,
        const StackVector<int64_t, kMaxNdim>& stride,
        const StackVector<int64_t, kMaxNdim>& pad,
        AveragePoolPadMode pad_mode) {
    if (GetKind(x.dtype()) != DtypeKind::kFloat) {
        throw DtypeError("cannot apply average pooling to ", x.dtype(), " array (floatXX array is expected)");
    }

    CheckPoolInputs(x, kernel_size, stride, pad);
    std::shared_ptr<AveragePoolForwardBackward> fb = x.device().GetAveragePoolForwardBackward(kernel_size, stride, pad, pad_mode);
    Array out = fb->Forward(x.AsGradStopped());
    internal::MakeViewForForwardBackwardOutput(out);
    {
        BackwardBuilder bb1{"average_pool", x, out};
        if (BackwardBuilder::Target bt1 = bb1.CreateTarget(0)) {
            bt1.Define([fb = std::move(fb), kernel_size, stride, pad, pad_mode](BackwardContext& bctx) {
                const Array& gout = bctx.output_grad();
                Array gx = fb->Backward(gout.AsGradStopped());
                internal::MakeViewForForwardBackwardOutput(gx);
                {
                    BackwardBuilder bb2{"average_pool_backward", gout, gx};
                    if (BackwardBuilder::Target bt2 = bb2.CreateTarget(0)) {
                        bt2.Define([kernel_size, stride, pad, pad_mode](BackwardContext& bctx2) {
                            const Array& ggx = bctx2.output_grad();
                            bctx2.input_grad() = AveragePool(ggx, kernel_size, stride, pad, pad_mode);
                        });
                    }
                    bb2.Finalize();
                }
                bctx.input_grad() = gx;
            });
        }
        bb1.Finalize();
    }
    return out;
}

}  // namespace chainerx
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ImplOPropertySet.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 01:29:30 $
 *
 *  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 CHART_IMPLOPROPERTYSET_HXX
#define CHART_IMPLOPROPERTYSET_HXX

#ifndef _COM_SUN_STAR_BEANS_PROPERTYSTATE_HPP_
#include <com/sun/star/beans/PropertyState.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_STYLE_XSTYLE_HPP_
#include <com/sun/star/style/XStyle.hpp>
#endif

#include <map>
#include <vector>

namespace property
{
namespace impl
{

class ImplOPropertySet
{
public:
    ImplOPropertySet();

    /** supports states DIRECT_VALUE and DEFAULT_VALUE
     */
    ::com::sun::star::beans::PropertyState
        GetPropertyStateByHandle( sal_Int32 nHandle ) const;

    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState >
        GetPropertyStatesByHandle( const ::std::vector< sal_Int32 > & aHandles ) const;

    void SetPropertyToDefault( sal_Int32 nHandle );
    void SetPropertiesToDefault( const ::std::vector< sal_Int32 > & aHandles );
    void SetAllPropertiesToDefault();

    /** @param rValue is set to the value for the property given in nHandle.  If
               the property is not set, the style chain is searched for any
               instance set there.  If there was no value found either in the
               property set itself or any of its styles, rValue remains
               unchanged and false is returned.

        @return false if the property is default, true otherwise.
     */
    bool GetPropertyValueByHandle(
        ::com::sun::star::uno::Any & rValue,
        sal_Int32 nHandle ) const;

    void SetPropertyValueByHandle( sal_Int32 nHandle,
                                   const ::com::sun::star::uno::Any & rValue,
                                   ::com::sun::star::uno::Any * pOldValue = NULL );

    bool SetStyle( const ::com::sun::star::uno::Reference< ::com::sun::star::style::XStyle > & xStyle );
    ::com::sun::star::uno::Reference< ::com::sun::star::style::XStyle >
        GetStyle() const;

    typedef
        ::std::map< sal_Int32, ::com::sun::star::uno::Any >
        tPropertyMap;

private:
    tPropertyMap    m_aProperties;
    ::com::sun::star::uno::Reference< ::com::sun::star::style::XStyle >
        m_xStyle;
};

} //  namespace impl
} //  namespace chart

// CHART_IMPLOPROPERTYSET_HXX
#endif
<commit_msg>INTEGRATION: CWS chart2mst3 (1.1.1.1.4); FILE MERGED 2005/11/04 15:48:28 bm 1.1.1.1.4.3: clone properties that have interface type 2005/10/07 12:08:52 bm 1.1.1.1.4.2: RESYNC: (1.1.1.1-1.2); FILE MERGED 2005/03/30 16:31:14 bm 1.1.1.1.4.1: make model cloneable (+first undo implementation)<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ImplOPropertySet.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 18:59:20 $
 *
 *  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 CHART_IMPLOPROPERTYSET_HXX
#define CHART_IMPLOPROPERTYSET_HXX

#ifndef _COM_SUN_STAR_BEANS_PROPERTYSTATE_HPP_
#include <com/sun/star/beans/PropertyState.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_STYLE_XSTYLE_HPP_
#include <com/sun/star/style/XStyle.hpp>
#endif

#include <map>
#include <vector>

namespace property
{
namespace impl
{

class ImplOPropertySet
{
public:
    ImplOPropertySet();
    explicit ImplOPropertySet( const ImplOPropertySet & rOther );

    /** supports states DIRECT_VALUE and DEFAULT_VALUE
     */
    ::com::sun::star::beans::PropertyState
        GetPropertyStateByHandle( sal_Int32 nHandle ) const;

    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState >
        GetPropertyStatesByHandle( const ::std::vector< sal_Int32 > & aHandles ) const;

    void SetPropertyToDefault( sal_Int32 nHandle );
    void SetPropertiesToDefault( const ::std::vector< sal_Int32 > & aHandles );
    void SetAllPropertiesToDefault();

    /** @param rValue is set to the value for the property given in nHandle.  If
               the property is not set, the style chain is searched for any
               instance set there.  If there was no value found either in the
               property set itself or any of its styles, rValue remains
               unchanged and false is returned.

        @return false if the property is default, true otherwise.
     */
    bool GetPropertyValueByHandle(
        ::com::sun::star::uno::Any & rValue,
        sal_Int32 nHandle ) const;

    void SetPropertyValueByHandle( sal_Int32 nHandle,
                                   const ::com::sun::star::uno::Any & rValue,
                                   ::com::sun::star::uno::Any * pOldValue = NULL );

    bool SetStyle( const ::com::sun::star::uno::Reference< ::com::sun::star::style::XStyle > & xStyle );
    ::com::sun::star::uno::Reference< ::com::sun::star::style::XStyle >
        GetStyle() const;

    typedef
        ::std::map< sal_Int32, ::com::sun::star::uno::Any >
        tPropertyMap;

private:
    void cloneInterfaceProperties();

    tPropertyMap    m_aProperties;
    ::com::sun::star::uno::Reference< ::com::sun::star::style::XStyle >
        m_xStyle;
};

} //  namespace impl
} //  namespace chart

// CHART_IMPLOPROPERTYSET_HXX
#endif
<|endoftext|>


<commit_before><commit_msg>Revert 39779 - Part of http://codereview.chromium.org/650206<commit_after><|endoftext|>


<commit_before><commit_msg>Fix Linux build<commit_after><|endoftext|>


<commit_before><commit_msg>DevTools: increase web inspector height<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/debugger/devtools_view.h"

#include <string>

#include "base/command_line.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/views/tab_contents_container_view.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/property_bag.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"

DevToolsView::DevToolsView(Profile* profile)
    : tab_contents_(NULL),
      profile_(profile) {
  web_container_ = new TabContentsContainerView();
  AddChildView(web_container_);
}

DevToolsView::~DevToolsView() {
}

std::string DevToolsView::GetClassName() const {
  return "DevToolsView";
}

gfx::Size DevToolsView::GetPreferredSize() {
  return gfx::Size(700, 400);
}

void DevToolsView::Layout() {
  web_container_->SetBounds(0, 0, width(), height());
}

void DevToolsView::ViewHierarchyChanged(bool is_add,
                                     views::View* parent,
                                     views::View* child) {
  if (is_add && child == this) {
    DCHECK(GetWidget());
    Init();
  }
}

void DevToolsView::Init() {
  // We can't create the TabContents until we've actually been put into a real
  // view hierarchy somewhere.
  tab_contents_ = new TabContents(profile_, NULL, MSG_ROUTING_NONE, NULL);
  tab_contents_->set_delegate(this);
  web_container_->SetTabContents(tab_contents_);
  tab_contents_->render_view_host()->AllowDOMUIBindings();

  // chrome://devtools/devtools.html
  GURL contents(std::string(chrome::kChromeUIDevToolsURL) + "devtools.html");

  // this will call CreateRenderView to create renderer process
  tab_contents_->controller().LoadURL(contents, GURL(),
                                      PageTransition::START_PAGE);

  // If each DevTools front end has its own renderer process allow to inspect
  // DevTools windows.
  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessPerTab)) {
    views::Accelerator accelerator('J', true /* shift_down */,
                                   true /* ctrl_down */, false /* alt_down */);
    views::FocusManager* focus_manager = GetFocusManager();
    DCHECK(focus_manager);
    focus_manager->RegisterAccelerator(accelerator, this);
  }
}

bool DevToolsView::AcceleratorPressed(const views::Accelerator& accelerator) {
  // TODO(yurys): get rid of this hack and pull the accelerator from the
  // resources
  views::Accelerator la('J', true /* shift_down */, true /* ctrl_down */,
                        false /* alt_down */);
  if (!tab_contents_) {
    return false;
  }
  if (!(la == accelerator)) {
    return false;
  }
  DevToolsManager* manager = g_browser_process->devtools_manager();
  manager->OpenDevToolsWindow(tab_contents_->render_view_host());
  return true;
}

void DevToolsView::OnWindowClosing() {
  DCHECK(tab_contents_) << "OnWindowClosing is called twice";
  if (tab_contents_) {
    // Detach last (and only) tab.
    web_container_->SetTabContents(NULL);

    // Destroy the tab and navigation controller.
    delete tab_contents_;
    tab_contents_ = NULL;
  }
}

void DevToolsView::SendMessageToClient(const IPC::Message& message) {
  if (tab_contents_) {
    RenderViewHost* target_host = tab_contents_->render_view_host();
    IPC::Message* m =  new IPC::Message(message);
    m->set_routing_id(target_host->routing_id());
    target_host->Send(m);
  }
}

RenderViewHost* DevToolsView::GetRenderViewHost() const {
  if (tab_contents_) {
    return tab_contents_->render_view_host();
  }
  return NULL;
}

void DevToolsView::OpenURLFromTab(TabContents* source,
                               const GURL& url, const GURL& referrer,
                               WindowOpenDisposition disposition,
                               PageTransition::Type transition) {
  NOTREACHED();
}
<commit_msg>DevTools: increase web inspector height<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/debugger/devtools_view.h"

#include <string>

#include "base/command_line.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/views/tab_contents_container_view.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/property_bag.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"

DevToolsView::DevToolsView(Profile* profile)
    : tab_contents_(NULL),
      profile_(profile) {
  web_container_ = new TabContentsContainerView();
  AddChildView(web_container_);
}

DevToolsView::~DevToolsView() {
}

std::string DevToolsView::GetClassName() const {
  return "DevToolsView";
}

gfx::Size DevToolsView::GetPreferredSize() {
  return gfx::Size(640, 640);
}

void DevToolsView::Layout() {
  web_container_->SetBounds(0, 0, width(), height());
}

void DevToolsView::ViewHierarchyChanged(bool is_add,
                                     views::View* parent,
                                     views::View* child) {
  if (is_add && child == this) {
    DCHECK(GetWidget());
    Init();
  }
}

void DevToolsView::Init() {
  // We can't create the TabContents until we've actually been put into a real
  // view hierarchy somewhere.
  tab_contents_ = new TabContents(profile_, NULL, MSG_ROUTING_NONE, NULL);
  tab_contents_->set_delegate(this);
  web_container_->SetTabContents(tab_contents_);
  tab_contents_->render_view_host()->AllowDOMUIBindings();

  // chrome://devtools/devtools.html
  GURL contents(std::string(chrome::kChromeUIDevToolsURL) + "devtools.html");

  // this will call CreateRenderView to create renderer process
  tab_contents_->controller().LoadURL(contents, GURL(),
                                      PageTransition::START_PAGE);

  // If each DevTools front end has its own renderer process allow to inspect
  // DevTools windows.
  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessPerTab)) {
    views::Accelerator accelerator('J', true /* shift_down */,
                                   true /* ctrl_down */, false /* alt_down */);
    views::FocusManager* focus_manager = GetFocusManager();
    DCHECK(focus_manager);
    focus_manager->RegisterAccelerator(accelerator, this);
  }
}

bool DevToolsView::AcceleratorPressed(const views::Accelerator& accelerator) {
  // TODO(yurys): get rid of this hack and pull the accelerator from the
  // resources
  views::Accelerator la('J', true /* shift_down */, true /* ctrl_down */,
                        false /* alt_down */);
  if (!tab_contents_) {
    return false;
  }
  if (!(la == accelerator)) {
    return false;
  }
  DevToolsManager* manager = g_browser_process->devtools_manager();
  manager->OpenDevToolsWindow(tab_contents_->render_view_host());
  return true;
}

void DevToolsView::OnWindowClosing() {
  DCHECK(tab_contents_) << "OnWindowClosing is called twice";
  if (tab_contents_) {
    // Detach last (and only) tab.
    web_container_->SetTabContents(NULL);

    // Destroy the tab and navigation controller.
    delete tab_contents_;
    tab_contents_ = NULL;
  }
}

void DevToolsView::SendMessageToClient(const IPC::Message& message) {
  if (tab_contents_) {
    RenderViewHost* target_host = tab_contents_->render_view_host();
    IPC::Message* m =  new IPC::Message(message);
    m->set_routing_id(target_host->routing_id());
    target_host->Send(m);
  }
}

RenderViewHost* DevToolsView::GetRenderViewHost() const {
  if (tab_contents_) {
    return tab_contents_->render_view_host();
  }
  return NULL;
}

void DevToolsView::OpenURLFromTab(TabContents* source,
                               const GURL& url, const GURL& referrer,
                               WindowOpenDisposition disposition,
                               PageTransition::Type transition) {
  NOTREACHED();
}
<|endoftext|>


<commit_before><commit_msg>Hook up alt-d on linux.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/platform_util.h"

#include <gtk/gtk.h>

#include "app/gtk_util.h"
#include "base/file_util.h"
#include "base/process_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/process_watcher.h"
#include "googleurl/src/gurl.h"

#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/dom_ui/filebrowse_ui.h"
#include "chrome/browser/dom_ui/mediaplayer_ui.h"

class Profile;

namespace platform_util {

// TODO(estade): It would be nice to be able to select the file in the file
// manager, but that probably requires extending xdg-open. For now just
// show the folder.
void ShowItemInFolder(const FilePath& full_path) {
  FilePath dir = full_path.DirName();
  if (!file_util::DirectoryExists(dir))
    return;

  Profile* profile;
  profile = BrowserList::GetLastActive()->profile();

  FileBrowseUI::OpenPopup(profile,
                          dir.value(),
                          FileBrowseUI::kPopupWidth,
                          FileBrowseUI::kPopupHeight);
}

void OpenItem(const FilePath& full_path) {
  std::string ext = full_path.Extension();
  // For things supported natively by the browser, we should open it
  // in a tab.
  if (ext == ".jpg" ||
      ext == ".jpeg" ||
      ext == ".png" ||
      ext == ".gif" ||
      ext == ".html" ||
      ext == ".htm") {
    std::string path;
    path = "file://";
    path += full_path.value();
    if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {
      bool result = ChromeThread::PostTask(
          ChromeThread::UI, FROM_HERE,
          NewRunnableFunction(&OpenItem, full_path));
      DCHECK(result);
      return;
    }
    Browser* browser = BrowserList::GetLastActive();
    browser->AddTabWithURL(
        GURL(path), GURL(), PageTransition::LINK,
        true, -1, false, NULL);
    return;
  }
  if (ext == ".avi" ||
      ext == ".mp4" ||
      ext == ".mp3" ||
      ext == ".mkv" ||
      ext == ".ogg") {
    MediaPlayer* mediaplayer = MediaPlayer::Get();
    std::string url = "file://";
    url += full_path.value();
    GURL gurl(url);
    mediaplayer->EnqueueMediaURL(gurl);
    return;
  }
}

void OpenExternal(const GURL& url) {

}

}  // namespace platform_util
<commit_msg>Fixing opening files on chromeos.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/platform_util.h"

#include <gtk/gtk.h>

#include "app/gtk_util.h"
#include "base/file_util.h"
#include "base/process_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/process_watcher.h"
#include "googleurl/src/gurl.h"

#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/dom_ui/filebrowse_ui.h"
#include "chrome/browser/dom_ui/mediaplayer_ui.h"

class Profile;

namespace platform_util {

// TODO(estade): It would be nice to be able to select the file in the file
// manager, but that probably requires extending xdg-open. For now just
// show the folder.
void ShowItemInFolder(const FilePath& full_path) {
  FilePath dir = full_path.DirName();
  if (!file_util::DirectoryExists(dir))
    return;

  Profile* profile;
  profile = BrowserList::GetLastActive()->profile();

  FileBrowseUI::OpenPopup(profile,
                          dir.value(),
                          FileBrowseUI::kPopupWidth,
                          FileBrowseUI::kPopupHeight);
}

void OpenItem(const FilePath& full_path) {
  std::string ext = full_path.Extension();
  // For things supported natively by the browser, we should open it
  // in a tab.
  if (ext == ".jpg" ||
      ext == ".jpeg" ||
      ext == ".png" ||
      ext == ".gif" ||
      ext == ".html" ||
      ext == ".htm") {
    std::string path;
    path = "file://";
    path.append(full_path.value());
    if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {
      bool result = ChromeThread::PostTask(
          ChromeThread::UI, FROM_HERE,
          NewRunnableFunction(&OpenItem, full_path));
      DCHECK(result);
      return;
    }
    Browser* browser = BrowserList::GetLastActive();
    browser->AddTabWithURL(
        GURL(path), GURL(), PageTransition::LINK, -1, Browser::ADD_SELECTED,
        NULL, std::string());
    return;
  }
  if (ext == ".avi" ||
      ext == ".mp4" ||
      ext == ".mp3" ||
      ext == ".mkv" ||
      ext == ".ogg") {
    MediaPlayer* mediaplayer = MediaPlayer::Get();
    std::string url = "file://";
    url += full_path.value();
    GURL gurl(url);
    mediaplayer->EnqueueMediaURL(gurl);
    return;
  }
}

void OpenExternal(const GURL& url) {

}

}  // namespace platform_util
<|endoftext|>