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

#include <svtools/pathoptions.hxx>
#include <sfx2/viewfrm.hxx>
#include "gallery1.hxx"
#include "galtheme.hxx"
#include "galbrws.hxx"
#include "gallery.hxx"

// -----------
// - Statics -
// -----------

static SfxListener aDummyListener;

// -------------------
// - GalleryExplorer -
// -------------------

Gallery* GalleryExplorer::ImplGetGallery()
{
    static Gallery* pGallery = NULL;

    if( !pGallery )
        pGallery = Gallery::AcquireGallery( SvtPathOptions().GetGalleryPath() );

    return pGallery;
}

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

GalleryExplorer* GalleryExplorer::GetGallery()
{
    static GalleryExplorer* pThis = NULL;

    // only create a dummy object which can be accessed
    if( !pThis )
        pThis = new GalleryExplorer;

    return pThis;
}

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

INetURLObject GalleryExplorer::GetURL() const
{
    return GALLERYBROWSER()->GetURL();
}

String GalleryExplorer::GetFilterName() const
{
    return GALLERYBROWSER()->GetFilterName();
}

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

Graphic GalleryExplorer::GetGraphic() const
{
    return GALLERYBROWSER()->GetGraphic();
}

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

BOOL GalleryExplorer::GetVCDrawModel( FmFormModel& rModel ) const
{
    return GALLERYBROWSER()->GetVCDrawModel( rModel );
}

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

BOOL GalleryExplorer::IsLinkage() const
{
    return GALLERYBROWSER()->IsLinkage();
}

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

BOOL GalleryExplorer::FillThemeList( List& rThemeList )
{
    Gallery* pGal = ImplGetGallery();

    if( pGal )
    {
        for( ULONG i = 0, nCount = pGal->GetThemeCount(); i < nCount; i++ )
        {
            const GalleryThemeEntry* pEntry = pGal->GetThemeInfo( i );

            if( pEntry && !pEntry->IsReadOnly() && !pEntry->IsHidden() )
                rThemeList.Insert( new String( pEntry->GetThemeName() ), LIST_APPEND );
        }
    }

    return( rThemeList.Count() > 0 );
}

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

BOOL GalleryExplorer::FillObjList( const String& rThemeName, List& rObjList )
{
    Gallery* pGal = ImplGetGallery();

    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( rThemeName, aDummyListener );

        if( pTheme )
        {
            for( ULONG i = 0, nCount = pTheme->GetObjectCount(); i < nCount; i++ )
                rObjList.Insert( new String( pTheme->GetObjectURL( i ).GetMainURL( INetURLObject::NO_DECODE ) ), LIST_APPEND );

            pGal->ReleaseTheme( pTheme, aDummyListener );
        }
    }

    return( rObjList.Count() > 0 );
}

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

BOOL GalleryExplorer::FillObjList( ULONG nThemeId, List& rObjList )
{
    Gallery* pGal = ImplGetGallery();
    return( pGal ? FillObjList( pGal->GetThemeName( nThemeId ), rObjList ) : FALSE );
}

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

sal_Bool GalleryExplorer::FillObjListTitle( const sal_uInt32 nThemeId, std::vector< rtl::OUString >& rList )
{
    Gallery* pGal = ImplGetGallery();
    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( pGal->GetThemeName( nThemeId ), aDummyListener );
        if( pTheme )
        {
            for( ULONG i = 0, nCount = pTheme->GetObjectCount(); i < nCount; i++ )
            {
                SgaObject*  pObj = pTheme->AcquireObject( i );
                if ( pObj )
                {
                    rtl::OUString aTitle( pObj->GetTitle() );
                    rList.push_back( aTitle );
                    pTheme->ReleaseObject( pObj );
                }
            }
            pGal->ReleaseTheme( pTheme, aDummyListener );
        }
    }
    return( rList.size() > 0 );
}

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

BOOL GalleryExplorer::InsertURL( const String& rThemeName, const String& rURL )
{
    return InsertURL( rThemeName, rURL, SGA_FORMAT_ALL );
}

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

BOOL GalleryExplorer::InsertURL( ULONG nThemeId, const String& rURL )
{
    return InsertURL( nThemeId, rURL, SGA_FORMAT_ALL );
}

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

BOOL GalleryExplorer::InsertURL( const String& rThemeName, const String& rURL, const ULONG nSgaFormat )
{
    Gallery*    pGal = ImplGetGallery();
    BOOL        bRet = FALSE;

    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( rThemeName, aDummyListener );

        if( pTheme )
        {
            INetURLObject aURL( rURL );
            DBG_ASSERT( aURL.GetProtocol() != INET_PROT_NOT_VALID, "invalid URL" );
            bRet = pTheme->InsertURL( aURL );
            pGal->ReleaseTheme( pTheme, aDummyListener );
        }
    }

    return bRet;
}

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

BOOL GalleryExplorer::InsertURL( ULONG nThemeId, const String& rURL, const ULONG nSgaFormat )
{
    Gallery* pGal = ImplGetGallery();
    return( pGal ? InsertURL( pGal->GetThemeName( nThemeId ), rURL, nSgaFormat ) : FALSE );
}

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

ULONG GalleryExplorer::GetObjCount( const String& rThemeName )
{
    Gallery*    pGal = ImplGetGallery();
    ULONG       nRet = 0;

    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( rThemeName, aDummyListener );

        if( pTheme )
        {
            nRet = pTheme->GetObjectCount();
            pGal->ReleaseTheme( pTheme, aDummyListener );
        }
    }

    return nRet;
}

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

ULONG GalleryExplorer::GetObjCount( ULONG nThemeId )
{
    Gallery* pGal = ImplGetGallery();
    return( pGal ? GetObjCount( pGal->GetThemeName( nThemeId ) ) : FALSE );
}

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

BOOL GalleryExplorer::GetGraphicObj( const String& rThemeName, ULONG nPos,
                                     Graphic* pGraphic, Bitmap* pThumb,
                                     BOOL bProgress )
{
    Gallery*    pGal = ImplGetGallery();
    BOOL        bRet = FALSE;

    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( rThemeName, aDummyListener );

        if( pTheme )
        {
            if( pGraphic )
                bRet = bRet || pTheme->GetGraphic( nPos, *pGraphic, bProgress );

            if( pThumb )
                bRet = bRet || pTheme->GetThumb( nPos, *pThumb, bProgress );

            pGal->ReleaseTheme( pTheme, aDummyListener );
        }
    }

    return bRet;
}

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

BOOL GalleryExplorer::GetGraphicObj( ULONG nThemeId, ULONG nPos,
                                     Graphic* pGraphic, Bitmap* pThumb,
                                     BOOL bProgress )
{
    Gallery* pGal = ImplGetGallery();
    return( pGal ? GetGraphicObj( pGal->GetThemeName( nThemeId ), nPos, pGraphic, pThumb, bProgress ) : FALSE );
}

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

BOOL GalleryExplorer::InsertGraphicObj( const String& rThemeName, const Graphic& rGraphic )
{
    Gallery*    pGal = ImplGetGallery();
    BOOL        bRet = FALSE;

    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( rThemeName, aDummyListener );

        if( pTheme )
        {
            bRet = pTheme->InsertGraphic( rGraphic );
            pGal->ReleaseTheme( pTheme, aDummyListener );
        }
    }

    return bRet;
}

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

BOOL GalleryExplorer::InsertGraphicObj( ULONG nThemeId, const Graphic& rGraphic )
{
    Gallery* pGal = ImplGetGallery();
    return( pGal ? InsertGraphicObj( pGal->GetThemeName( nThemeId ), rGraphic ) : FALSE );
}

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

ULONG GalleryExplorer::GetSdrObjCount( const String& rThemeName )
{
    Gallery*    pGal = ImplGetGallery();
    ULONG       nRet = 0;

    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( rThemeName, aDummyListener );

        if( pTheme )
        {
            for( ULONG i = 0, nCount = pTheme->GetObjectCount(); i < nCount; i++ )
                if( SGA_OBJ_SVDRAW == pTheme->GetObjectKind( i ) )
                    nRet++;

            pGal->ReleaseTheme( pTheme, aDummyListener );
        }
    }

    return nRet;
}

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

ULONG GalleryExplorer::GetSdrObjCount( ULONG nThemeId  )
{
    Gallery* pGal = ImplGetGallery();
    return( pGal ? GetSdrObjCount( pGal->GetThemeName( nThemeId ) ) : FALSE );
}

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

BOOL GalleryExplorer::GetSdrObj( const String& rThemeName, ULONG nSdrModelPos,
                                 FmFormModel* pModel, Bitmap* pThumb )
{
    Gallery*    pGal = ImplGetGallery();
    BOOL        bRet = FALSE;

    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( rThemeName, aDummyListener );

        if( pTheme )
        {
            BOOL bFound = FALSE;

            for( ULONG i = 0, nCount = pTheme->GetObjectCount(), nActPos = 0; ( i < nCount ) && !bRet; i++ )
            {
                if( SGA_OBJ_SVDRAW == pTheme->GetObjectKind( i ) )
                {
                    if( nActPos++ == nSdrModelPos )
                    {
                        if( pModel )
                            bRet = bRet || pTheme->GetModel( i, *pModel, FALSE );

                        if( pThumb )
                            bRet = bRet || pTheme->GetThumb( i, *pThumb );
                    }
                }
            }

            pGal->ReleaseTheme( pTheme, aDummyListener );
        }
    }

    return bRet;
}

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

BOOL GalleryExplorer::GetSdrObj( ULONG nThemeId, ULONG nSdrModelPos,
                                 FmFormModel* pModel, Bitmap* pThumb )
{
    Gallery* pGal = ImplGetGallery();
    return( pGal ? GetSdrObj( pGal->GetThemeName( nThemeId ), nSdrModelPos, pModel, pThumb ) : FALSE );
}

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

BOOL GalleryExplorer::InsertSdrObj( const String& rThemeName, FmFormModel& rModel )
{
    Gallery*    pGal = ImplGetGallery();
    BOOL        bRet = FALSE;

    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( rThemeName, aDummyListener );

        if( pTheme )
        {
            bRet = pTheme->InsertModel( rModel );
            pGal->ReleaseTheme( pTheme, aDummyListener );
        }
    }

    return bRet;
}

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

BOOL GalleryExplorer::InsertSdrObj( ULONG nThemeId, FmFormModel& rModel )
{
    Gallery* pGal = ImplGetGallery();
    return( pGal ? InsertSdrObj( pGal->GetThemeName( nThemeId ), rModel ) : FALSE );
}

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

BOOL GalleryExplorer::BeginLocking( const String& rThemeName )
{
    Gallery*    pGal = ImplGetGallery();
    BOOL        bRet = FALSE;

    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( rThemeName, aDummyListener );

        if( pTheme )
            bRet = TRUE;
    }

    return bRet;
}

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

BOOL GalleryExplorer::BeginLocking( ULONG nThemeId )
{
    Gallery* pGal = ImplGetGallery();
    return( pGal ? BeginLocking( pGal->GetThemeName( nThemeId ) ) : FALSE );
}

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

BOOL GalleryExplorer::EndLocking( const String& rThemeName )
{
    Gallery*    pGal = ImplGetGallery();
    BOOL        bRet = FALSE;

    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( rThemeName, aDummyListener );

        if( pTheme )
        {
            // release twice ( 1. acquired theme, 2. locked theme )
            pGal->ReleaseTheme( pTheme, aDummyListener );
            pGal->ReleaseTheme( pTheme, aDummyListener );
            bRet = TRUE;
        }
    }

    return bRet;
}

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

BOOL GalleryExplorer::EndLocking( ULONG nThemeId )
{
    Gallery* pGal = ImplGetGallery();
    return( pGal ? EndLocking( pGal->GetThemeName( nThemeId ) ) : FALSE );
}

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

BOOL GalleryExplorer::DrawCentered( OutputDevice* pOut, const FmFormModel& rModel )
{
    return SgaObjectSvDraw::DrawCentered( pOut, rModel );
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.668); FILE MERGED 2005/09/05 14:24:52 rt 1.7.668.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: galexpl.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 23:06:46 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <svtools/pathoptions.hxx>
#include <sfx2/viewfrm.hxx>
#include "gallery1.hxx"
#include "galtheme.hxx"
#include "galbrws.hxx"
#include "gallery.hxx"

// -----------
// - Statics -
// -----------

static SfxListener aDummyListener;

// -------------------
// - GalleryExplorer -
// -------------------

Gallery* GalleryExplorer::ImplGetGallery()
{
    static Gallery* pGallery = NULL;

    if( !pGallery )
        pGallery = Gallery::AcquireGallery( SvtPathOptions().GetGalleryPath() );

    return pGallery;
}

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

GalleryExplorer* GalleryExplorer::GetGallery()
{
    static GalleryExplorer* pThis = NULL;

    // only create a dummy object which can be accessed
    if( !pThis )
        pThis = new GalleryExplorer;

    return pThis;
}

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

INetURLObject GalleryExplorer::GetURL() const
{
    return GALLERYBROWSER()->GetURL();
}

String GalleryExplorer::GetFilterName() const
{
    return GALLERYBROWSER()->GetFilterName();
}

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

Graphic GalleryExplorer::GetGraphic() const
{
    return GALLERYBROWSER()->GetGraphic();
}

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

BOOL GalleryExplorer::GetVCDrawModel( FmFormModel& rModel ) const
{
    return GALLERYBROWSER()->GetVCDrawModel( rModel );
}

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

BOOL GalleryExplorer::IsLinkage() const
{
    return GALLERYBROWSER()->IsLinkage();
}

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

BOOL GalleryExplorer::FillThemeList( List& rThemeList )
{
    Gallery* pGal = ImplGetGallery();

    if( pGal )
    {
        for( ULONG i = 0, nCount = pGal->GetThemeCount(); i < nCount; i++ )
        {
            const GalleryThemeEntry* pEntry = pGal->GetThemeInfo( i );

            if( pEntry && !pEntry->IsReadOnly() && !pEntry->IsHidden() )
                rThemeList.Insert( new String( pEntry->GetThemeName() ), LIST_APPEND );
        }
    }

    return( rThemeList.Count() > 0 );
}

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

BOOL GalleryExplorer::FillObjList( const String& rThemeName, List& rObjList )
{
    Gallery* pGal = ImplGetGallery();

    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( rThemeName, aDummyListener );

        if( pTheme )
        {
            for( ULONG i = 0, nCount = pTheme->GetObjectCount(); i < nCount; i++ )
                rObjList.Insert( new String( pTheme->GetObjectURL( i ).GetMainURL( INetURLObject::NO_DECODE ) ), LIST_APPEND );

            pGal->ReleaseTheme( pTheme, aDummyListener );
        }
    }

    return( rObjList.Count() > 0 );
}

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

BOOL GalleryExplorer::FillObjList( ULONG nThemeId, List& rObjList )
{
    Gallery* pGal = ImplGetGallery();
    return( pGal ? FillObjList( pGal->GetThemeName( nThemeId ), rObjList ) : FALSE );
}

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

sal_Bool GalleryExplorer::FillObjListTitle( const sal_uInt32 nThemeId, std::vector< rtl::OUString >& rList )
{
    Gallery* pGal = ImplGetGallery();
    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( pGal->GetThemeName( nThemeId ), aDummyListener );
        if( pTheme )
        {
            for( ULONG i = 0, nCount = pTheme->GetObjectCount(); i < nCount; i++ )
            {
                SgaObject*  pObj = pTheme->AcquireObject( i );
                if ( pObj )
                {
                    rtl::OUString aTitle( pObj->GetTitle() );
                    rList.push_back( aTitle );
                    pTheme->ReleaseObject( pObj );
                }
            }
            pGal->ReleaseTheme( pTheme, aDummyListener );
        }
    }
    return( rList.size() > 0 );
}

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

BOOL GalleryExplorer::InsertURL( const String& rThemeName, const String& rURL )
{
    return InsertURL( rThemeName, rURL, SGA_FORMAT_ALL );
}

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

BOOL GalleryExplorer::InsertURL( ULONG nThemeId, const String& rURL )
{
    return InsertURL( nThemeId, rURL, SGA_FORMAT_ALL );
}

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

BOOL GalleryExplorer::InsertURL( const String& rThemeName, const String& rURL, const ULONG nSgaFormat )
{
    Gallery*    pGal = ImplGetGallery();
    BOOL        bRet = FALSE;

    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( rThemeName, aDummyListener );

        if( pTheme )
        {
            INetURLObject aURL( rURL );
            DBG_ASSERT( aURL.GetProtocol() != INET_PROT_NOT_VALID, "invalid URL" );
            bRet = pTheme->InsertURL( aURL );
            pGal->ReleaseTheme( pTheme, aDummyListener );
        }
    }

    return bRet;
}

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

BOOL GalleryExplorer::InsertURL( ULONG nThemeId, const String& rURL, const ULONG nSgaFormat )
{
    Gallery* pGal = ImplGetGallery();
    return( pGal ? InsertURL( pGal->GetThemeName( nThemeId ), rURL, nSgaFormat ) : FALSE );
}

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

ULONG GalleryExplorer::GetObjCount( const String& rThemeName )
{
    Gallery*    pGal = ImplGetGallery();
    ULONG       nRet = 0;

    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( rThemeName, aDummyListener );

        if( pTheme )
        {
            nRet = pTheme->GetObjectCount();
            pGal->ReleaseTheme( pTheme, aDummyListener );
        }
    }

    return nRet;
}

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

ULONG GalleryExplorer::GetObjCount( ULONG nThemeId )
{
    Gallery* pGal = ImplGetGallery();
    return( pGal ? GetObjCount( pGal->GetThemeName( nThemeId ) ) : FALSE );
}

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

BOOL GalleryExplorer::GetGraphicObj( const String& rThemeName, ULONG nPos,
                                     Graphic* pGraphic, Bitmap* pThumb,
                                     BOOL bProgress )
{
    Gallery*    pGal = ImplGetGallery();
    BOOL        bRet = FALSE;

    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( rThemeName, aDummyListener );

        if( pTheme )
        {
            if( pGraphic )
                bRet = bRet || pTheme->GetGraphic( nPos, *pGraphic, bProgress );

            if( pThumb )
                bRet = bRet || pTheme->GetThumb( nPos, *pThumb, bProgress );

            pGal->ReleaseTheme( pTheme, aDummyListener );
        }
    }

    return bRet;
}

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

BOOL GalleryExplorer::GetGraphicObj( ULONG nThemeId, ULONG nPos,
                                     Graphic* pGraphic, Bitmap* pThumb,
                                     BOOL bProgress )
{
    Gallery* pGal = ImplGetGallery();
    return( pGal ? GetGraphicObj( pGal->GetThemeName( nThemeId ), nPos, pGraphic, pThumb, bProgress ) : FALSE );
}

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

BOOL GalleryExplorer::InsertGraphicObj( const String& rThemeName, const Graphic& rGraphic )
{
    Gallery*    pGal = ImplGetGallery();
    BOOL        bRet = FALSE;

    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( rThemeName, aDummyListener );

        if( pTheme )
        {
            bRet = pTheme->InsertGraphic( rGraphic );
            pGal->ReleaseTheme( pTheme, aDummyListener );
        }
    }

    return bRet;
}

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

BOOL GalleryExplorer::InsertGraphicObj( ULONG nThemeId, const Graphic& rGraphic )
{
    Gallery* pGal = ImplGetGallery();
    return( pGal ? InsertGraphicObj( pGal->GetThemeName( nThemeId ), rGraphic ) : FALSE );
}

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

ULONG GalleryExplorer::GetSdrObjCount( const String& rThemeName )
{
    Gallery*    pGal = ImplGetGallery();
    ULONG       nRet = 0;

    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( rThemeName, aDummyListener );

        if( pTheme )
        {
            for( ULONG i = 0, nCount = pTheme->GetObjectCount(); i < nCount; i++ )
                if( SGA_OBJ_SVDRAW == pTheme->GetObjectKind( i ) )
                    nRet++;

            pGal->ReleaseTheme( pTheme, aDummyListener );
        }
    }

    return nRet;
}

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

ULONG GalleryExplorer::GetSdrObjCount( ULONG nThemeId  )
{
    Gallery* pGal = ImplGetGallery();
    return( pGal ? GetSdrObjCount( pGal->GetThemeName( nThemeId ) ) : FALSE );
}

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

BOOL GalleryExplorer::GetSdrObj( const String& rThemeName, ULONG nSdrModelPos,
                                 FmFormModel* pModel, Bitmap* pThumb )
{
    Gallery*    pGal = ImplGetGallery();
    BOOL        bRet = FALSE;

    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( rThemeName, aDummyListener );

        if( pTheme )
        {
            BOOL bFound = FALSE;

            for( ULONG i = 0, nCount = pTheme->GetObjectCount(), nActPos = 0; ( i < nCount ) && !bRet; i++ )
            {
                if( SGA_OBJ_SVDRAW == pTheme->GetObjectKind( i ) )
                {
                    if( nActPos++ == nSdrModelPos )
                    {
                        if( pModel )
                            bRet = bRet || pTheme->GetModel( i, *pModel, FALSE );

                        if( pThumb )
                            bRet = bRet || pTheme->GetThumb( i, *pThumb );
                    }
                }
            }

            pGal->ReleaseTheme( pTheme, aDummyListener );
        }
    }

    return bRet;
}

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

BOOL GalleryExplorer::GetSdrObj( ULONG nThemeId, ULONG nSdrModelPos,
                                 FmFormModel* pModel, Bitmap* pThumb )
{
    Gallery* pGal = ImplGetGallery();
    return( pGal ? GetSdrObj( pGal->GetThemeName( nThemeId ), nSdrModelPos, pModel, pThumb ) : FALSE );
}

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

BOOL GalleryExplorer::InsertSdrObj( const String& rThemeName, FmFormModel& rModel )
{
    Gallery*    pGal = ImplGetGallery();
    BOOL        bRet = FALSE;

    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( rThemeName, aDummyListener );

        if( pTheme )
        {
            bRet = pTheme->InsertModel( rModel );
            pGal->ReleaseTheme( pTheme, aDummyListener );
        }
    }

    return bRet;
}

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

BOOL GalleryExplorer::InsertSdrObj( ULONG nThemeId, FmFormModel& rModel )
{
    Gallery* pGal = ImplGetGallery();
    return( pGal ? InsertSdrObj( pGal->GetThemeName( nThemeId ), rModel ) : FALSE );
}

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

BOOL GalleryExplorer::BeginLocking( const String& rThemeName )
{
    Gallery*    pGal = ImplGetGallery();
    BOOL        bRet = FALSE;

    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( rThemeName, aDummyListener );

        if( pTheme )
            bRet = TRUE;
    }

    return bRet;
}

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

BOOL GalleryExplorer::BeginLocking( ULONG nThemeId )
{
    Gallery* pGal = ImplGetGallery();
    return( pGal ? BeginLocking( pGal->GetThemeName( nThemeId ) ) : FALSE );
}

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

BOOL GalleryExplorer::EndLocking( const String& rThemeName )
{
    Gallery*    pGal = ImplGetGallery();
    BOOL        bRet = FALSE;

    if( pGal )
    {
        GalleryTheme* pTheme = pGal->AcquireTheme( rThemeName, aDummyListener );

        if( pTheme )
        {
            // release twice ( 1. acquired theme, 2. locked theme )
            pGal->ReleaseTheme( pTheme, aDummyListener );
            pGal->ReleaseTheme( pTheme, aDummyListener );
            bRet = TRUE;
        }
    }

    return bRet;
}

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

BOOL GalleryExplorer::EndLocking( ULONG nThemeId )
{
    Gallery* pGal = ImplGetGallery();
    return( pGal ? EndLocking( pGal->GetThemeName( nThemeId ) ) : FALSE );
}

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

BOOL GalleryExplorer::DrawCentered( OutputDevice* pOut, const FmFormModel& rModel )
{
    return SgaObjectSvDraw::DrawCentered( pOut, rModel );
}
<|endoftext|>


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

#include "portxt.hxx"

class SwFont;

// DropCap-Cache, globale Variable, in txtinit.cxx initialisiert/zerstoert
// und in txtdrop.cxx benutzt bei der Initialenberechnung

class SwDropCapCache;
extern SwDropCapCache *pDropCapCache;

/*************************************************************************
 *                      class SwDropPortionPart
 *
 * A drop portion can consist of one or more parts in order to allow
 * attribute changes inside them.
 *************************************************************************/

class SwDropPortionPart
{
    SwDropPortionPart* pFollow;
    SwFont* pFnt;
    xub_StrLen nLen;
    USHORT nWidth;

public:
    SwDropPortionPart( SwFont& rFont, const xub_StrLen nL )
            : pFollow( 0 ), pFnt( &rFont ), nLen( nL ), nWidth( 0 ) {};
    ~SwDropPortionPart();

    inline SwDropPortionPart* GetFollow() const { return pFollow; };
    inline void SetFollow( SwDropPortionPart* pNew ) { pFollow = pNew; };
    inline SwFont& GetFont() const { return *pFnt; }
    inline xub_StrLen GetLen() const { return nLen; }
    inline USHORT GetWidth() const { return nWidth; }
    inline void SetWidth( USHORT nNew )  { nWidth = nNew; }
};

/*************************************************************************
 *                      class SwDropPortion
 *************************************************************************/

class SwDropPortion : public SwTxtPortion
{
    friend class SwDropCapCache;
    SwDropPortionPart* pPart; // due to script / attribute changes
    MSHORT nLines;          // Anzahl der Zeilen
    KSHORT nDropHeight;     // Hoehe
    KSHORT nDropDescent;    // Abstand zur naechsten Zeile
    KSHORT nDistance;       // Abstand zum Text
    KSHORT nFix;            // Fixposition
    short nX;               // X-PaintOffset
    short nY;               // Y-Offset

    sal_Bool FormatTxt( SwTxtFormatInfo &rInf );
    void PaintTxt( const SwTxtPaintInfo &rInf ) const;

    inline void Fix( const KSHORT nNew ) { nFix = nNew; }
public:
    SwDropPortion( const MSHORT nLineCnt,
                   const KSHORT nDropHeight,
                   const KSHORT nDropDescent,
                   const KSHORT nDistance );
    virtual ~SwDropPortion();

    virtual void Paint( const SwTxtPaintInfo &rInf ) const;
            void PaintDrop( const SwTxtPaintInfo &rInf ) const;
    virtual sal_Bool Format( SwTxtFormatInfo &rInf );
    virtual SwPosSize GetTxtSize( const SwTxtSizeInfo &rInfo ) const;
    virtual xub_StrLen GetCrsrOfst( const MSHORT nOfst ) const;

    inline MSHORT GetLines() const { return nLines; }
    inline KSHORT GetDistance() const { return nDistance; }
    inline KSHORT GetDropHeight() const { return nDropHeight; }
    inline KSHORT GetDropDescent() const { return nDropDescent; }
    inline KSHORT GetDropLeft() const { return Width() + nFix; }

    inline SwDropPortionPart* GetPart() const { return pPart; }
    inline void SetPart( SwDropPortionPart* pNew ) { pPart = pNew; }

    inline void SetY( short nNew )  { nY = nNew; }

    inline SwFont* GetFnt() { return pPart ? &pPart->GetFont() : NULL; }

    static void DeleteDropCapCache();

    OUTPUT_OPERATOR
};

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

#include "portxt.hxx"

class SwFont;

// DropCap-Cache, globale Variable, in txtinit.cxx initialisiert/zerstoert
// und in txtdrop.cxx benutzt bei der Initialenberechnung

class SwDropCapCache;
extern SwDropCapCache *pDropCapCache;

/*************************************************************************
 *                      class SwDropPortionPart
 *
 * A drop portion can consist of one or more parts in order to allow
 * attribute changes inside them.
 *************************************************************************/

class SwDropPortionPart
{
    SwDropPortionPart* pFollow;
    SwFont* pFnt;
    xub_StrLen nLen;
    USHORT nWidth;

public:
    SwDropPortionPart( SwFont& rFont, const xub_StrLen nL )
            : pFollow( 0 ), pFnt( &rFont ), nLen( nL ), nWidth( 0 ) {};
    ~SwDropPortionPart();

    inline SwDropPortionPart* GetFollow() const { return pFollow; };
    inline void SetFollow( SwDropPortionPart* pNew ) { pFollow = pNew; };
    inline SwFont& GetFont() const { return *pFnt; }
    inline xub_StrLen GetLen() const { return nLen; }
    inline USHORT GetWidth() const { return nWidth; }
    inline void SetWidth( USHORT nNew )  { nWidth = nNew; }
};

/*************************************************************************
 *                      class SwDropPortion
 *************************************************************************/

class SwDropPortion : public SwTxtPortion
{
    friend class SwDropCapCache;
    SwDropPortionPart* pPart; // due to script / attribute changes
    MSHORT nLines;          // Anzahl der Zeilen
    KSHORT nDropHeight;     // Hoehe
    KSHORT nDropDescent;    // Abstand zur naechsten Zeile
    KSHORT nDistance;       // Abstand zum Text
    KSHORT nFix;            // Fixposition
    short nX;               // X-PaintOffset
    short nY;               // Y-Offset

    sal_Bool FormatTxt( SwTxtFormatInfo &rInf );
    void PaintTxt( const SwTxtPaintInfo &rInf ) const;

    inline void Fix( const KSHORT nNew ) { nFix = nNew; }
public:
    SwDropPortion( const MSHORT nLineCnt,
                   const KSHORT nDropHeight,
                   const KSHORT nDropDescent,
                   const KSHORT nDistance );
    virtual ~SwDropPortion();

    virtual void Paint( const SwTxtPaintInfo &rInf ) const;
            void PaintDrop( const SwTxtPaintInfo &rInf ) const;
    virtual sal_Bool Format( SwTxtFormatInfo &rInf );
    virtual SwPosSize GetTxtSize( const SwTxtSizeInfo &rInfo ) const;
    virtual xub_StrLen GetCrsrOfst( const MSHORT nOfst ) const;

    inline MSHORT GetLines() const { return nLines; }
    inline KSHORT GetDistance() const { return nDistance; }
    inline KSHORT GetDropHeight() const { return nDropHeight; }
    inline KSHORT GetDropDescent() const { return nDropDescent; }
    inline KSHORT GetDropLeft() const { return Width() + nFix; }

    inline SwDropPortionPart* GetPart() const { return pPart; }
    inline void SetPart( SwDropPortionPart* pNew ) { pPart = pNew; }

    inline void SetY( short nNew )  { nY = nNew; }

    inline SwFont* GetFnt() const { return pPart ? &pPart->GetFont() : NULL; }

    static void DeleteDropCapCache();

    OUTPUT_OPERATOR
};

#endif
<|endoftext|>


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

#ifndef _XMLEXP_HXX
#define _XMLEXP_HXX

#ifndef _XMLOFF_XMLEXP_HXX
#include <xmloff/xmlexp.hxx>
#endif

#ifndef _XMLITMAP_HXX
#include "xmlitmap.hxx"
#endif
#ifndef _UNIVERSALL_REFERENCE_HXX
#include <xmloff/uniref.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif

class SwPaM;
class SwFmt;
class SwFrmFmt;
class SvXMLUnitConverter;
class SvXMLExportItemMapper;
class SvXMLAutoStylePoolP;
class SwTableLine;
class SwTableLines;
class SwTableBox;
class SwXMLTableColumn_Impl;
class SwXMLTableLines_Impl;
class SwXMLTableLinesCache_Impl;
class SwXMLTableColumnsSortByWidth_Impl;
class SwXMLTableFrmFmtsSort_Impl;
class SwXMLTableInfo_Impl;
class SwTableNode;
class XMLPropertySetMapper;

#ifndef XML_PROGRESS_REF_NOT_SET
#define XML_PROGRESS_REF_NOT_SET ((sal_Int32)-1)
#endif

class SwXMLExport : public SvXMLExport
{
    friend class SwXMLExpContext;

#ifdef XML_CORE_API
    SwPaM                       *pCurPaM;       // the current PaM
    SwPaM                       *pOrigPaM;      // the original PaM
#endif

    SvXMLUnitConverter          *pTwipUnitConv;

    SvXMLExportItemMapper       *pTableItemMapper;
    SwXMLTableLinesCache_Impl   *pTableLines;

    SvXMLItemMapEntriesRef      xTableItemMap;
    SvXMLItemMapEntriesRef      xTableRowItemMap;
    SvXMLItemMapEntriesRef      xTableCellItemMap;
    UniReference < XMLPropertySetMapper > xParaPropMapper;

    sal_Bool                    bExportWholeDoc : 1;// export whole document?
    sal_Bool                    bBlock : 1;         // export text block?
    sal_Bool                    bExportFirstTableOnly : 1;
    sal_Bool                    bShowProgress : 1;
    sal_Bool                    bSavedShowChanges : 1;

    void _InitItemExport();
    void _FinitItemExport();
    void ExportTableLinesAutoStyles( const SwTableLines& rLines,
                                 sal_uInt32 nAbsWidth,
                                 sal_uInt32 nBaseWidth,
                                 const ::rtl::OUString& rNamePrefix,
                                 SwXMLTableColumnsSortByWidth_Impl& rExpCols,
                                 SwXMLTableFrmFmtsSort_Impl& rExpRows,
                                 SwXMLTableFrmFmtsSort_Impl& rExpCells,
                                 SwXMLTableInfo_Impl& rTblInfo,
                                 sal_Bool bTop=sal_False );

    void ExportFmt( const SwFmt& rFmt,  enum ::xmloff::token::XMLTokenEnum eClass = ::xmloff::token::XML_TOKEN_INVALID );
    void ExportTableFmt( const SwFrmFmt& rFmt, sal_uInt32 nAbsWidth );

    void ExportTableColumnStyle( const SwXMLTableColumn_Impl& rCol );
    void ExportTableBox( const SwTableBox& rBox, sal_uInt16 nColSpan,
                         SwXMLTableInfo_Impl& rTblInfo );
    void ExportTableLine( const SwTableLine& rLine,
                          const SwXMLTableLines_Impl& rLines,
                          SwXMLTableInfo_Impl& rTblInfo );
    void ExportTableLines( const SwTableLines& rLines,
                           SwXMLTableInfo_Impl& rTblInfo,
                           sal_Bool bHeadline=sal_False );

    virtual void _ExportMeta();
    virtual void _ExportFontDecls();
    virtual void _ExportStyles( sal_Bool bUsed );
    virtual void _ExportAutoStyles();
    virtual void _ExportMasterStyles();
    virtual void _ExportContent();
    virtual void GetViewSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aProps);
    virtual void GetConfigurationSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aProps);

#ifdef XML_CORE_API
    void SetCurPaM( SwPaM& rPaM, sal_Bool bWhole, sal_Bool bTabOnly );
#endif

    // string constants for table cell export
    const ::rtl::OUString sNumberFormat;
    const ::rtl::OUString sIsProtected;
    const ::rtl::OUString sCell;

protected:

    virtual XMLTextParagraphExport* CreateTextParagraphExport();
    virtual SvXMLAutoStylePoolP* CreateAutoStylePool();
    virtual XMLPageExport* CreatePageExport();
    virtual XMLShapeExport* CreateShapeExport();
    virtual XMLFontAutoStylePool* CreateFontAutoStylePool();

public:

    // #110680#
    SwXMLExport(
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
        sal_uInt16 nExportFlags = EXPORT_ALL);

#ifdef XML_CORE_API
    // #110680#
    SwXMLExport(
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
        const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > & rModel,
        SwPaM& rPaM,
        const ::rtl::OUString& rFileName,
        const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > & rHandler,
        const ::com::sun::star::uno::Reference< ::com::sun::star::document::XGraphicObjectResolver > &,
        sal_Bool bExpWholeDoc,
        sal_Bool bExpFirstTableOnly,
        sal_Bool bShowProgr );
#endif
    virtual ~SwXMLExport();

    void setBlockMode();

    virtual sal_uInt32 exportDoc( enum ::xmloff::token::XMLTokenEnum eClass = ::xmloff::token::XML_TOKEN_INVALID );

    inline const SvXMLUnitConverter& GetTwipUnitConverter() const;

    void ExportTableAutoStyles( const SwTableNode& rTblNd );
    void ExportTable( const SwTableNode& rTblNd );

    SvXMLExportItemMapper& GetTableItemMapper() { return *pTableItemMapper; }
    const UniReference < XMLPropertySetMapper >& GetParaPropMapper()
    {
        return xParaPropMapper;
    }

    sal_Bool IsShowProgress() const { return bShowProgress; }
    void SetShowProgress( sal_Bool b ) { bShowProgress = b; }
    sal_Bool IsBlockMode() const { return bBlock; }

    // XUnoTunnel
    static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId() throw();
    virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);

    // XServiceInfo (override parent method)
    ::rtl::OUString SAL_CALL getImplementationName()
        throw( ::com::sun::star::uno::RuntimeException );
};

inline const SvXMLUnitConverter& SwXMLExport::GetTwipUnitConverter() const
{
    return *pTwipUnitConv;
}

#endif  //  _XMLEXP_HXX

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

#ifndef _XMLEXP_HXX
#define _XMLEXP_HXX

#ifndef _XMLOFF_XMLEXP_HXX
#include <xmloff/xmlexp.hxx>
#endif

#ifndef _XMLITMAP_HXX
#include "xmlitmap.hxx"
#endif
#ifndef _UNIVERSALL_REFERENCE_HXX
#include <xmloff/uniref.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif

class SwPaM;
class SwFmt;
class SwFrmFmt;
class SvXMLUnitConverter;
class SvXMLExportItemMapper;
class SvXMLAutoStylePoolP;
class SwTableLine;
class SwTableLines;
class SwTableBox;
class SwXMLTableColumn_Impl;
class SwXMLTableLines_Impl;
class SwXMLTableLinesCache_Impl;
class SwXMLTableColumnsSortByWidth_Impl;
class SwXMLTableFrmFmtsSort_Impl;
class SwXMLTableInfo_Impl;
class SwTableNode;
class XMLPropertySetMapper;

#ifndef XML_PROGRESS_REF_NOT_SET
#define XML_PROGRESS_REF_NOT_SET ((sal_Int32)-1)
#endif

class SwXMLExport : public SvXMLExport
{
    friend class SwXMLExpContext;

#ifdef XML_CORE_API
    SwPaM                       *pCurPaM;       // the current PaM
    SwPaM                       *pOrigPaM;      // the original PaM
#endif

    SvXMLUnitConverter          *pTwipUnitConv;

    SvXMLExportItemMapper       *pTableItemMapper;
    SwXMLTableLinesCache_Impl   *pTableLines;

    SvXMLItemMapEntriesRef      xTableItemMap;
    SvXMLItemMapEntriesRef      xTableRowItemMap;
    SvXMLItemMapEntriesRef      xTableCellItemMap;
    UniReference < XMLPropertySetMapper > xParaPropMapper;

    sal_Bool                    bExportWholeDoc : 1;// export whole document?
    sal_Bool                    bBlock : 1;         // export text block?
    sal_Bool                    bExportFirstTableOnly : 1;
    sal_Bool                    bShowProgress : 1;
    sal_Bool                    bSavedShowChanges : 1;

    void _InitItemExport();
    void _FinitItemExport();
    void ExportTableLinesAutoStyles( const SwTableLines& rLines,
                                 sal_uInt32 nAbsWidth,
                                 sal_uInt32 nBaseWidth,
                                 const ::rtl::OUString& rNamePrefix,
                                 SwXMLTableColumnsSortByWidth_Impl& rExpCols,
                                 SwXMLTableFrmFmtsSort_Impl& rExpRows,
                                 SwXMLTableFrmFmtsSort_Impl& rExpCells,
                                 SwXMLTableInfo_Impl& rTblInfo,
                                 sal_Bool bTop=sal_False );

    void ExportFmt( const SwFmt& rFmt,  enum ::xmloff::token::XMLTokenEnum eClass = ::xmloff::token::XML_TOKEN_INVALID );
    void ExportTableFmt( const SwFrmFmt& rFmt, sal_uInt32 nAbsWidth );

    void ExportTableColumnStyle( const SwXMLTableColumn_Impl& rCol );
    void ExportTableBox( const SwTableBox& rBox, sal_uInt16 nColSpan,
                         SwXMLTableInfo_Impl& rTblInfo );
    void ExportTableLine( const SwTableLine& rLine,
                          const SwXMLTableLines_Impl& rLines,
                          SwXMLTableInfo_Impl& rTblInfo );
    void ExportTableLines( const SwTableLines& rLines,
                           SwXMLTableInfo_Impl& rTblInfo,
                           USHORT nHeaderRows = 0 );

    virtual void _ExportMeta();
    virtual void _ExportFontDecls();
    virtual void _ExportStyles( sal_Bool bUsed );
    virtual void _ExportAutoStyles();
    virtual void _ExportMasterStyles();
    virtual void _ExportContent();
    virtual void GetViewSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aProps);
    virtual void GetConfigurationSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aProps);

#ifdef XML_CORE_API
    void SetCurPaM( SwPaM& rPaM, sal_Bool bWhole, sal_Bool bTabOnly );
#endif

    // string constants for table cell export
    const ::rtl::OUString sNumberFormat;
    const ::rtl::OUString sIsProtected;
    const ::rtl::OUString sCell;

protected:

    virtual XMLTextParagraphExport* CreateTextParagraphExport();
    virtual SvXMLAutoStylePoolP* CreateAutoStylePool();
    virtual XMLPageExport* CreatePageExport();
    virtual XMLShapeExport* CreateShapeExport();
    virtual XMLFontAutoStylePool* CreateFontAutoStylePool();

public:

    // #110680#
    SwXMLExport(
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
        sal_uInt16 nExportFlags = EXPORT_ALL);

#ifdef XML_CORE_API
    // #110680#
    SwXMLExport(
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
        const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > & rModel,
        SwPaM& rPaM,
        const ::rtl::OUString& rFileName,
        const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > & rHandler,
        const ::com::sun::star::uno::Reference< ::com::sun::star::document::XGraphicObjectResolver > &,
        sal_Bool bExpWholeDoc,
        sal_Bool bExpFirstTableOnly,
        sal_Bool bShowProgr );
#endif
    virtual ~SwXMLExport();

    void setBlockMode();

    virtual sal_uInt32 exportDoc( enum ::xmloff::token::XMLTokenEnum eClass = ::xmloff::token::XML_TOKEN_INVALID );

    inline const SvXMLUnitConverter& GetTwipUnitConverter() const;

    void ExportTableAutoStyles( const SwTableNode& rTblNd );
    void ExportTable( const SwTableNode& rTblNd );

    SvXMLExportItemMapper& GetTableItemMapper() { return *pTableItemMapper; }
    const UniReference < XMLPropertySetMapper >& GetParaPropMapper()
    {
        return xParaPropMapper;
    }

    sal_Bool IsShowProgress() const { return bShowProgress; }
    void SetShowProgress( sal_Bool b ) { bShowProgress = b; }
    sal_Bool IsBlockMode() const { return bBlock; }

    // XUnoTunnel
    static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId() throw();
    virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);

    // XServiceInfo (override parent method)
    ::rtl::OUString SAL_CALL getImplementationName()
        throw( ::com::sun::star::uno::RuntimeException );
};

inline const SvXMLUnitConverter& SwXMLExport::GetTwipUnitConverter() const
{
    return *pTwipUnitConv;
}

#endif  //  _XMLEXP_HXX

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: swuiexp.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 07:15:56 $
 *
 *  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
 *
 ************************************************************************/

#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif

#include "swdlgfact.hxx"

#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif

namespace swui
{
    static SwAbstractDialogFactory_Impl* pFactory=NULL;
    SwAbstractDialogFactory * GetFactory()
    {
        if ( !pFactory )
            pFactory = new SwAbstractDialogFactory_Impl;
        if ( !pSwResMgr)
            SwDialogsResMgr::GetResMgr();
        return pFactory;
    }
};

extern "C"
{
    SAL_DLLPUBLIC_EXPORT SwAbstractDialogFactory* CreateDialogFactory()
    {
        return ::swui::GetFactory();
    }
}
<commit_msg>INTEGRATION: CWS writercorehandoff (1.3.462); FILE MERGED 2005/09/13 16:41:23 tra 1.3.462.3: RESYNC: (1.3-1.4); FILE MERGED 2005/06/07 14:15:29 fme 1.3.462.2: #i50348# General cleanup - removed unused header files, functions, members, declarations etc. 2005/06/06 09:29:27 tra 1.3.462.1: Unnecessary includes removed #i50348#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: swuiexp.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-08-14 17:33:27 $
 *
 *  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
 *
 ************************************************************************/
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif

#include "swdlgfact.hxx"

namespace swui
{
    static SwAbstractDialogFactory_Impl* pFactory=NULL;
    SwAbstractDialogFactory * GetFactory()
    {
        if ( !pFactory )
            pFactory = new SwAbstractDialogFactory_Impl;
        if ( !pSwResMgr)
            SwDialogsResMgr::GetResMgr();
        return pFactory;
    }
};

extern "C"
{
    SAL_DLLPUBLIC_EXPORT SwAbstractDialogFactory* CreateDialogFactory()
    {
        return ::swui::GetFactory();
    }
}
<|endoftext|>


<commit_before>#include "catch.hpp"
#include "board.h"

TEST_CASE("Pawn move generation is correct") {
    Board board;

    SECTION("White pawn moves are generated correctly from start position") {
      board.setToStartPos();

      REQUIRE(board.getWhitePawnMoves().size() == 16);
    }

    SECTION("Black pawn moves are generated correctly from start position") {
      board.setToStartPos();

      REQUIRE(board.getBlackPawnMoves().size() == 16);
    }

    SECTION("White pawn attacks are generated correctly from start position") {
      board.setToStartPos();

      REQUIRE(board.getWhitePawnAttacks().size() == 0);
    }

    SECTION("Black pawn attacks are generated correctly from start position") {
      board.setToStartPos();

      REQUIRE(board.getBlackPawnAttacks().size() == 0);
    }
}
<commit_msg>Fully test pawn move generation<commit_after>#include "catch.hpp"
#include "board.h"

TEST_CASE("Pawn move generation is correct") {
    Board board;

    SECTION("White pawn moves are generated correctly from start position") {
      board.setToStartPos();

      REQUIRE(board.getWhitePawnMoves().size() == 16);
    }

    SECTION("Black pawn moves are generated correctly from start position") {
      board.setToStartPos();

      REQUIRE(board.getBlackPawnMoves().size() == 16);
    }

    SECTION("White pawn moves are generated correctly after a1a4") {
      board.setToFen("rnbqkbnr/pppppppp/8/8/P7/8/1PPPPPPP/RNBQKBNR w KQkq -");

      REQUIRE(board.getWhitePawnMoves().size() == 15);
    }

    SECTION("White pawn moves are generated correctly after h1h4") {
      board.setToFen("rnbqkbnr/pppppppp/8/8/7P/8/PPPPPPP1/RNBQKBNR w KQkq -");

      REQUIRE(board.getWhitePawnMoves().size() == 15);
    }
}

TEST_CASE("Pawn attack generation is correct") {
  Board board;

  SECTION("White pawn attacks are generated correctly from start position") {
    board.setToStartPos();

    REQUIRE(board.getWhitePawnAttacks().size() == 0);
  }

  SECTION("Black pawn attacks are generated correctly from start position") {
    board.setToStartPos();

    REQUIRE(board.getBlackPawnAttacks().size() == 0);
  }

  SECTION("White pawn attacks are generated correctly for 2 possible attacks") {
    board.setToFen("8/8/8/3r1r2/4P3/8/8/8 w KQkq -");

    REQUIRE(board.getWhitePawnAttacks().size() == 2);
  }

  SECTION("White pawn attacks are generated correctly for 1 possible attack") {
    board.setToFen("8/8/8/5r2/4P3/8/8/8 w - -");

    REQUIRE(board.getWhitePawnAttacks().size() == 1);
  }

  SECTION("White pawn attacks are generated correctly for 1 possible attack on the H file") {
    board.setToFen("8/8/8/6r1/7P/8/8/8 w - -");

    REQUIRE(board.getWhitePawnAttacks().size() == 1);
  }

  SECTION("White pawn attacks are generated correctly for 1 possible attack on the A file") {
    board.setToFen("8/8/8/1r6/P7/8/8/8 w - -");

    REQUIRE(board.getWhitePawnAttacks().size() == 1);
  }

  SECTION("Black pawn attacks are generated correctly for 2 possible attacks") {
    board.setToFen("8/8/3p4/2R1R3/8/8/8/8 w - -");

    REQUIRE(board.getBlackPawnAttacks().size() == 2);
  }

  SECTION("Black pawn attacks are generated correctly for 1 possible attack") {
    board.setToFen("8/8/3p4/2R5/8/8/8/8 w - -");

    REQUIRE(board.getBlackPawnAttacks().size() == 1);
  }

  SECTION("Black pawn attacks are generated correctly for 1 possible attack on the H file") {
    board.setToFen("8/8/7p/6R1/8/8/8/8 w - -");

    REQUIRE(board.getBlackPawnAttacks().size() == 1);
  }

  SECTION("Black pawn attacks are generated correctly for 1 possible attack on the A file") {
    board.setToFen("8/8/p7/1R6/8/8/8/8 w - -");

    REQUIRE(board.getBlackPawnAttacks().size() == 1);
  }

}
<|endoftext|>


<commit_before>/*
    idle_interface.hpp - This file is part of LVTK
    Copyright (C) 2013  Michael Fisher <mfisher31@gmail.com>

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

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#ifndef LVTK_IDLE_INTERFACE_HPP
#define LVTK_IDLE_INTERFACE_HPP

#include <lv2/lv2plug.in/ns/extensions/ui/ui.h>

namespace lvtk {

template <bool Required = true>
struct IdleInterface
{
     template <class Derived>
     struct I : Extension<Required>
     {

      /** @skip */
      static void
      map_feature_handlers (FeatureHandlerMap& hmap)
      {
         hmap[LV2_UI__idleInterface] = &I<Derived>::handle_feature;
      }

      /** @skip */
      static void
      handle_feature (void* instance, FeatureData data)
      {
          std::clog << "HANDLE FEATURE FEATERUDUDUD\n";
         Derived* d = reinterpret_cast<Derived*> (instance);
         I<Derived>* fe = static_cast<I<Derived>*> (d);
         fe->m_ok = true;
      }

      /** Sanity check the mixin */
      bool
      check_ok()
      {
         if (LVTK_DEBUG) {
           std::clog<<"    [IdleInterface] validation "
                    <<(this->m_ok ? "succeeded" : "failed")<<"."<<std::endl;
         }
         return true;
      }

      /** @skip */
      static const void*
      extension_data (const char* uri)
      {
         if (! std::strcmp (uri, LV2_UI__idleInterface)) {
            std::clog << "giving back idle interface struct\n";
            static LV2UI_Idle_Interface idle_iface = { &I<Derived>::_idle };
            return &idle_iface;
         }

         std::clog << "giving back idle interface struct FALED\n";
         return 0;
      }

      int idle() { }

     protected:

      /** @internal */
      static int _idle (LV2UI_Handle ui)
      {
          std::clog << "idle\n";
         Derived* d = reinterpret_cast<Derived*> (ui);
         return d->idle();
      }
   };
};

}

#endif /* LVTK_IDLE_INTERFACE_HPP */
<commit_msg>Remove debug output. Formatting<commit_after>/*
    idle_interface.hpp - This file is part of LVTK
    Copyright (C) 2013  Michael Fisher <mfisher31@gmail.com>

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

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#ifndef LVTK_IDLE_INTERFACE_HPP
#define LVTK_IDLE_INTERFACE_HPP

#include <lv2/lv2plug.in/ns/extensions/ui/ui.h>

namespace lvtk {

template <bool Required = true>
struct IdleInterface
{
    template <class Derived>
    struct I : Extension<Required>
    {
        /** @skip */
        static void
        map_feature_handlers (FeatureHandlerMap& hmap)
        {
            hmap[LV2_UI__idleInterface] = &I<Derived>::handle_feature;
        }

        /** @skip */
        static void
        handle_feature (void* instance, FeatureData data)
        {
            Derived* d = reinterpret_cast<Derived*> (instance);
            I<Derived>* fe = static_cast<I<Derived>*> (d);
            fe->m_ok = true;
        }

        /** Sanity check the mixin */
        bool
        check_ok()
        {
            if (LVTK_DEBUG) {
                std::clog<<"    [IdleInterface] validation "
                        <<(this->m_ok ? "succeeded" : "failed")<<"."<<std::endl;
            }
            return true;
        }

        /** @skip */
        static const void*
        extension_data (const char* uri)
        {
            if (! std::strcmp (uri, LV2_UI__idleInterface)) {
                static LV2UI_Idle_Interface idle_iface = { &I<Derived>::_idle };
                return &idle_iface;
            }

            return 0;
        }

        int idle() { }

    protected:

        /** @internal */
        static int _idle (LV2UI_Handle ui)
        {
            if (Derived* d = reinterpret_cast<Derived*> (ui))
                return d->idle();
            return 1;
        }
    };
};

}

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


<commit_before>#include <iostream>
#include <cstring>
#include <cstdlib>
#include "dacloud.h"

using namespace std;

int
main(int argc, char *argv[]) {
    if (argc < 3)
        return (-1);
    string configpath = argv[1];
    string useragent = argv[2];
    da_cloud_config config;
    ::memset(&config, 0, sizeof(config));
    if (da_cloud_init(&config, configpath.c_str()) == 0) {
        da_cloud_header_head head;
        da_cloud_property_head phead;
        da_cloud_header_init(&head);
        da_cloud_header_add(&head, "user-agent", useragent.c_str());
        if (da_cloud_detect(&config, &head, &phead) == 0) {
            da_cloud_property *p;
            SLIST_FOREACH(p, &phead.list, entries) {
                da_cloud_property_type type = p->type;
                cout << p->name << ": ";
                switch (type) {
                case DA_CLOUD_LONG:
                    cout << p->value.l;
                    break;
                case DA_CLOUD_BOOL:
                    cout << (p->value.l > 0 ? "true" : "false");
                    break;
                case DA_CLOUD_STRING:
                case DA_CLOUD_UNKNOWN:
                    cout << p->value.s;
                    break;
                }
                cout << endl;
            }
            da_cloud_properties_free(&phead);
        }
        da_cloud_header_free(&head);
    }

    da_cloud_fini(&config);
    return (0);
}
<commit_msg>displaying cache source for C++ example<commit_after>#include <iostream>
#include <cstring>
#include <cstdlib>
#include "dacloud.h"

using namespace std;

int
main(int argc, char *argv[]) {
    if (argc < 3)
        return (-1);
    string configpath = argv[1];
    string useragent = argv[2];
    da_cloud_config config;
    ::memset(&config, 0, sizeof(config));
    if (da_cloud_init(&config, configpath.c_str()) == 0) {
        da_cloud_header_head head;
        da_cloud_property_head phead;
        da_cloud_header_init(&head);
        da_cloud_header_add(&head, "user-agent", useragent.c_str());
        if (da_cloud_detect(&config, &head, &phead) == 0) {
            da_cloud_property *p;
            SLIST_FOREACH(p, &phead.list, entries) {
                da_cloud_property_type type = p->type;
                cout << p->name << ": ";
                switch (type) {
                case DA_CLOUD_LONG:
                    cout << p->value.l;
                    break;
                case DA_CLOUD_BOOL:
                    cout << (p->value.l > 0 ? "true" : "false");
                    break;
                case DA_CLOUD_STRING:
                case DA_CLOUD_UNKNOWN:
                    cout << p->value.s;
                    break;
                }
                cout << endl;
            }
            cout << "source: " << phead.cachesource << endl;
            da_cloud_properties_free(&phead);
        }
        da_cloud_header_free(&head);
    }

    da_cloud_fini(&config);
    return (0);
}
<|endoftext|>


<commit_before>/**
 *  For conditions of distribution and use, see copyright notice in license.txt
 *
 *  @file   InWorldChatModule.cpp
 *  @brief  Simple OpenSim world chat module. Listens for ChatFromSimulator packets and shows the chat on the UI.
 *          Outgoing chat sent using ChatFromViewer packets. Manages EC_ChatBubbles
 */

#include "StableHeaders.h"
#include "InWorldChatModule.h"

#include "EC_ChatBubble.h"
#include "EC_Billboard.h"

#include "WorldStream.h"
#include "SceneManager.h"
#include "EventManager.h"
#include "ModuleManager.h"
#include "RealXtend/RexProtocolMsgIDs.h"
#include "NetworkMessages/NetInMessage.h"
#include "CoreStringUtils.h"
#include "UiModule.h"

#include "EntityComponent/EC_OpenSimPresence.h"

namespace Naali
{

InWorldChatModule::InWorldChatModule() :
    ModuleInterfaceImpl(NameStatic()),
    networkStateEventCategory_(0),
    networkInEventCategory_(0),
    frameworkEventCategory_(0)
{
}

InWorldChatModule::~InWorldChatModule()
{
}

void InWorldChatModule::Load()
{
    DECLARE_MODULE_EC(EC_Billboard);
    DECLARE_MODULE_EC(EC_ChatBubble);
}

void InWorldChatModule::PostInitialize()
{
    frameworkEventCategory_ = framework_->GetEventManager()->QueryEventCategory("Framework");
    if (frameworkEventCategory_ == 0)
        LogError("Failed to query \"Framework\" event category");

    uiModule_ = framework_->GetModuleManager()->GetModule<UiServices::UiModule>(Foundation::Module::MT_UiServices);

    RegisterConsoleCommand(Console::CreateCommand("bbtest",
        "Adds a billboard to each entity in the scene.",
        Console::Bind(this, &InWorldChatModule::TestAddBillboard)));

    RegisterConsoleCommand(Console::CreateCommand("chat",
        "Sends a chat message.  Usage: \"chat(message)\"",
        Console::Bind(this, &InWorldChatModule::ConsoleChat)));
}

void InWorldChatModule::Update(f64 frametime)
{
}

bool InWorldChatModule::HandleEvent(
    event_category_id_t category_id,
    event_id_t event_id,
    Foundation::EventDataInterface *data)
{
    if (category_id == frameworkEventCategory_)
    {
        if (event_id == Foundation::NETWORKING_REGISTERED)
        {
            ProtocolUtilities::NetworkingRegisteredEvent *event_data = dynamic_cast<ProtocolUtilities::NetworkingRegisteredEvent *>(data);
            if (event_data)
                SubscribeToNetworkEvents(event_data->currentProtocolModule);
            return false;
        }

        if(event_id == Foundation::WORLD_STREAM_READY)
        {
            ProtocolUtilities::WorldStreamReadyEvent *event_data = dynamic_cast<ProtocolUtilities::WorldStreamReadyEvent *>(data);
            if (event_data)
                currentWorldStream_ = event_data->WorldStream;

            //if (chatWindow_)
            //    chatWindow_->SetWorldStreamPtr(current_world_stream_);

            networkInEventCategory_ = framework_->GetEventManager()->QueryEventCategory("NetworkIn");
            if (networkInEventCategory_ == 0)
                LogError("Failed to query \"NetworkIn\" event category");

            return false;
        }
    }

    if (category_id == networkStateEventCategory_)
    {
        // Connected to server. Create chat UI.
        if (event_id == ProtocolUtilities::Events::EVENT_SERVER_CONNECTED)
        {
            if (!uiModule_.expired())
            {
                //uiModule_.lock()->
            }
        }
        // Disconnected from server. Delete chat UI.
        if (event_id == ProtocolUtilities::Events::EVENT_SERVER_DISCONNECTED)
        {
            if (!uiModule_.expired())
            {
                //uiModule_.lock()->
            }
        }
    }

    if (category_id == networkInEventCategory_)
    {
        if(event_id == RexNetMsgChatFromSimulator)
        {
            ProtocolUtilities::NetworkEventInboundData *netdata = checked_static_cast<ProtocolUtilities::NetworkEventInboundData *>(data);
            assert(netdata);
            if (!netdata)
                return false;

//            assert(currentWorldStream_);

            std::stringstream ss;

            ProtocolUtilities::NetInMessage &msg = *netdata->message;
            msg.ResetReading();

            std::string fromName = msg.ReadString();
            RexUUID sourceId = msg.ReadUUID();

//            if (sourceId == currentWorldStream_->GetInfo().agentID)
//                return false;

            msg.SkipToFirstVariableByName("Message");
            std::string message = msg.ReadString();
            if (message.size() < 1)
                return false;

            ss << "[" << GetLocalTimeString() << "] " << fromName << ": " << message << std::endl;

            LogInfo(ss.str());

            Scene::ScenePtr scene = GetFramework()->GetDefaultWorldScene();
            for(Scene::SceneManager::iterator iter = scene->begin(); iter != scene->end(); ++iter)
            {
                Scene::Entity &entity = **iter;
                boost::shared_ptr<RexLogic::EC_OpenSimPresence> ec_presence = entity.GetComponent<RexLogic::EC_OpenSimPresence>();
                if (!ec_presence)
                    continue;

                if (ec_presence->FullId != sourceId)
                    continue;

                Foundation::ComponentInterfacePtr component = entity.GetOrCreateComponent(EC_ChatBubble::NameStatic());
                assert(component.get());
                EC_ChatBubble &chatBubble = *(checked_static_cast<EC_ChatBubble *>(component.get()));
                chatBubble.ShowMessage(message.c_str());
            }

/*
            QPixmap pixmap = GetPixmap("./media/textures/ChatBubble.png", message.c_str());
            if (!pixmap)
                return false;

            QLabel *w = new QLabel;
            w->setPixmap(pixmap);
            w->setAttribute(Qt::WA_DeleteOnClose);
            w->show();
*/
            // Connect chat ui to this modules ChatReceived
            // emit ChatReceived()
            //if (chatWindow_)
            //    chatWindow_->CharReceived(name, msg);

            return false;
        }
    }

    return false;
}

void InWorldChatModule::SubscribeToNetworkEvents(ProtocolUtilities::ProtocolWeakPtr currentProtocolModule)
{
    networkStateEventCategory_ = framework_->GetEventManager()->QueryEventCategory("NetworkState");
    if (networkStateEventCategory_ == 0)
        LogError("Failed to query \"NetworkState\" event category");

    networkInEventCategory_ = framework_->GetEventManager()->QueryEventCategory("NetworkIn");
    if (networkInEventCategory_ == 0)
        LogError("Failed to query \"NetworkIn\" event category");
}

const std::string InWorldChatModule::moduleName = std::string("InWorldChatModule");

const std::string &InWorldChatModule::NameStatic()
{
    return moduleName;
}

Console::CommandResult InWorldChatModule::TestAddBillboard(const StringVector &params)
{
    Scene::ScenePtr scene = GetFramework()->GetDefaultWorldScene();
    /// If/when there are multiple scenes at some day, have the SceneManager know the currently active one instead of RexLogicModule, so no dependency to it is needed.

    for(Scene::SceneManager::iterator iter = scene->begin(); iter != scene->end(); ++iter)
    {
        Scene::EntityPtr entity = *iter;
        entity->AddComponent(framework_->GetComponentManager()->CreateComponent("EC_Billboard"));
        EC_Billboard *billboard = entity->GetComponent<EC_Billboard>().get();
        assert(billboard);
        billboard->Show(Vector3df(0.f, 0.f, 1.5f), 10.f, "bubble.png");
    }

    return Console::ResultSuccess();
}

Console::CommandResult InWorldChatModule::ConsoleChat(const StringVector &params)
{
    if (params.size() == 0)
        return Console::ResultFailure("Can't send empty chat message!");

    SendChatFromViewer(params[0].c_str());
    return Console::ResultSuccess();
}

void InWorldChatModule::SendChatFromViewer(const QString &msg)
{
    if (currentWorldStream_)
        currentWorldStream_->SendChatFromViewerPacket(msg.toStdString());
}

extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler);
void SetProfiler(Foundation::Profiler *profiler)
{
    Foundation::ProfilerSection::SetProfiler(profiler);
}

}

using namespace Naali;

POCO_BEGIN_MANIFEST(Foundation::ModuleInterface)
    POCO_EXPORT_CLASS(InWorldChatModule)
POCO_END_MANIFEST
<commit_msg>Skeleton of RexEmotionIcon genericmessage handling.<commit_after>/**
 *  For conditions of distribution and use, see copyright notice in license.txt
 *
 *  @file   InWorldChatModule.cpp
 *  @brief  Simple OpenSim world chat module. Listens for ChatFromSimulator packets and shows the chat on the UI.
 *          Outgoing chat sent using ChatFromViewer packets. Manages EC_ChatBubbles
 */

#include "StableHeaders.h"
#include "InWorldChatModule.h"

#include "EC_ChatBubble.h"
#include "EC_Billboard.h"

#include "WorldStream.h"
#include "SceneManager.h"
#include "EventManager.h"
#include "ModuleManager.h"
#include "RealXtend/RexProtocolMsgIDs.h"
#include "NetworkMessages/NetInMessage.h"
#include "CoreStringUtils.h"
#include "GenericMessageUtils.h"
#include "UiModule.h"

#include "EntityComponent/EC_OpenSimPresence.h"

namespace Naali
{

InWorldChatModule::InWorldChatModule() :
    ModuleInterfaceImpl(NameStatic()),
    networkStateEventCategory_(0),
    networkInEventCategory_(0),
    frameworkEventCategory_(0)
{
}

InWorldChatModule::~InWorldChatModule()
{
}

void InWorldChatModule::Load()
{
    DECLARE_MODULE_EC(EC_Billboard);
    DECLARE_MODULE_EC(EC_ChatBubble);
}

void InWorldChatModule::PostInitialize()
{
    frameworkEventCategory_ = framework_->GetEventManager()->QueryEventCategory("Framework");
    if (frameworkEventCategory_ == 0)
        LogError("Failed to query \"Framework\" event category");

    uiModule_ = framework_->GetModuleManager()->GetModule<UiServices::UiModule>(Foundation::Module::MT_UiServices);

    RegisterConsoleCommand(Console::CreateCommand("bbtest",
        "Adds a billboard to each entity in the scene.",
        Console::Bind(this, &InWorldChatModule::TestAddBillboard)));

    RegisterConsoleCommand(Console::CreateCommand("chat",
        "Sends a chat message.  Usage: \"chat(message)\"",
        Console::Bind(this, &InWorldChatModule::ConsoleChat)));
}

void InWorldChatModule::Update(f64 frametime)
{
}

bool InWorldChatModule::HandleEvent(
    event_category_id_t category_id,
    event_id_t event_id,
    Foundation::EventDataInterface *data)
{
    if (category_id == frameworkEventCategory_)
    {
        if (event_id == Foundation::NETWORKING_REGISTERED)
        {
            ProtocolUtilities::NetworkingRegisteredEvent *event_data = dynamic_cast<ProtocolUtilities::NetworkingRegisteredEvent *>(data);
            if (event_data)
                SubscribeToNetworkEvents(event_data->currentProtocolModule);
            return false;
        }

        if(event_id == Foundation::WORLD_STREAM_READY)
        {
            ProtocolUtilities::WorldStreamReadyEvent *event_data = dynamic_cast<ProtocolUtilities::WorldStreamReadyEvent *>(data);
            if (event_data)
                currentWorldStream_ = event_data->WorldStream;

            //if (chatWindow_)
            //    chatWindow_->SetWorldStreamPtr(current_world_stream_);

            networkInEventCategory_ = framework_->GetEventManager()->QueryEventCategory("NetworkIn");
            if (networkInEventCategory_ == 0)
                LogError("Failed to query \"NetworkIn\" event category");

            return false;
        }
    }

    if (category_id == networkStateEventCategory_)
    {
        // Connected to server. Create chat UI.
        if (event_id == ProtocolUtilities::Events::EVENT_SERVER_CONNECTED)
        {
            if (!uiModule_.expired())
            {
                //uiModule_.lock()->
            }
        }
        // Disconnected from server. Delete chat UI.
        if (event_id == ProtocolUtilities::Events::EVENT_SERVER_DISCONNECTED)
        {
            if (!uiModule_.expired())
            {
                //uiModule_.lock()->
            }
        }
    }

    if (category_id == networkInEventCategory_)
    {
        if(event_id == RexNetMsgGenericMessage)
        {
            ProtocolUtilities::NetworkEventInboundData *netdata = checked_static_cast<ProtocolUtilities::NetworkEventInboundData *>(data);
            assert(netdata);
            if (!netdata)
                return false;
            ProtocolUtilities::NetInMessage &msg = *netdata->message;
            std::string method = ProtocolUtilities::ParseGenericMessageMethod(msg);
            StringVector params = ProtocolUtilities::ParseGenericMessageParameters(msg);
            if (method == "RexEmotionIcon")
            {
                // Param 0: avatar UUID
                // Param 1: texture ID
                // Param 2: timeout (remember to replace any , with . before parsing)
                if (params.size() >= 3)
                    LogInfo("Received RexEmotionIcon: " + params[0] + " " + params[1] + " " + params[2]);
            }

            return false;
        }

        if(event_id == RexNetMsgChatFromSimulator)
        {
            ProtocolUtilities::NetworkEventInboundData *netdata = checked_static_cast<ProtocolUtilities::NetworkEventInboundData *>(data);
            assert(netdata);
            if (!netdata)
                return false;

//            assert(currentWorldStream_);

            std::stringstream ss;

            ProtocolUtilities::NetInMessage &msg = *netdata->message;
            msg.ResetReading();

            std::string fromName = msg.ReadString();
            RexUUID sourceId = msg.ReadUUID();

//            if (sourceId == currentWorldStream_->GetInfo().agentID)
//                return false;

            msg.SkipToFirstVariableByName("Message");
            std::string message = msg.ReadString();
            if (message.size() < 1)
                return false;

            ss << "[" << GetLocalTimeString() << "] " << fromName << ": " << message << std::endl;

            LogInfo(ss.str());

            Scene::ScenePtr scene = GetFramework()->GetDefaultWorldScene();
            for(Scene::SceneManager::iterator iter = scene->begin(); iter != scene->end(); ++iter)
            {
                Scene::Entity &entity = **iter;
                boost::shared_ptr<RexLogic::EC_OpenSimPresence> ec_presence = entity.GetComponent<RexLogic::EC_OpenSimPresence>();
                if (!ec_presence)
                    continue;

                if (ec_presence->FullId != sourceId)
                    continue;

                Foundation::ComponentInterfacePtr component = entity.GetOrCreateComponent(EC_ChatBubble::NameStatic());
                assert(component.get());
                EC_ChatBubble &chatBubble = *(checked_static_cast<EC_ChatBubble *>(component.get()));
                chatBubble.ShowMessage(message.c_str());
            }

/*
            QPixmap pixmap = GetPixmap("./media/textures/ChatBubble.png", message.c_str());
            if (!pixmap)
                return false;

            QLabel *w = new QLabel;
            w->setPixmap(pixmap);
            w->setAttribute(Qt::WA_DeleteOnClose);
            w->show();
*/
            // Connect chat ui to this modules ChatReceived
            // emit ChatReceived()
            //if (chatWindow_)
            //    chatWindow_->CharReceived(name, msg);

            return false;
        }
    }

    return false;
}

void InWorldChatModule::SubscribeToNetworkEvents(ProtocolUtilities::ProtocolWeakPtr currentProtocolModule)
{
    networkStateEventCategory_ = framework_->GetEventManager()->QueryEventCategory("NetworkState");
    if (networkStateEventCategory_ == 0)
        LogError("Failed to query \"NetworkState\" event category");

    networkInEventCategory_ = framework_->GetEventManager()->QueryEventCategory("NetworkIn");
    if (networkInEventCategory_ == 0)
        LogError("Failed to query \"NetworkIn\" event category");
}

const std::string InWorldChatModule::moduleName = std::string("InWorldChatModule");

const std::string &InWorldChatModule::NameStatic()
{
    return moduleName;
}

Console::CommandResult InWorldChatModule::TestAddBillboard(const StringVector &params)
{
    Scene::ScenePtr scene = GetFramework()->GetDefaultWorldScene();
    /// If/when there are multiple scenes at some day, have the SceneManager know the currently active one instead of RexLogicModule, so no dependency to it is needed.

    for(Scene::SceneManager::iterator iter = scene->begin(); iter != scene->end(); ++iter)
    {
        Scene::EntityPtr entity = *iter;
        entity->AddComponent(framework_->GetComponentManager()->CreateComponent("EC_Billboard"));
        EC_Billboard *billboard = entity->GetComponent<EC_Billboard>().get();
        assert(billboard);
        billboard->Show(Vector3df(0.f, 0.f, 1.5f), 10.f, "bubble.png");
    }

    return Console::ResultSuccess();
}

Console::CommandResult InWorldChatModule::ConsoleChat(const StringVector &params)
{
    if (params.size() == 0)
        return Console::ResultFailure("Can't send empty chat message!");

    SendChatFromViewer(params[0].c_str());
    return Console::ResultSuccess();
}

void InWorldChatModule::SendChatFromViewer(const QString &msg)
{
    if (currentWorldStream_)
        currentWorldStream_->SendChatFromViewerPacket(msg.toStdString());
}

extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler);
void SetProfiler(Foundation::Profiler *profiler)
{
    Foundation::ProfilerSection::SetProfiler(profiler);
}

}

using namespace Naali;

POCO_BEGIN_MANIFEST(Foundation::ModuleInterface)
    POCO_EXPORT_CLASS(InWorldChatModule)
POCO_END_MANIFEST
<|endoftext|>


<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN for_each tests

#include <boost/test/unit_test.hpp>

#include <algorithm>
#include <functional>
#include <vector>

#include <point.h>

BOOST_AUTO_TEST_SUITE( for_each_test_suite )

BOOST_AUTO_TEST_CASE( sum_each_number )
{
    std::vector<int> numbers{1, 2, 3};
    auto f = [](int& n) { ++n; };

    std::for_each(std::begin(numbers), std::end(numbers), f);

    const std::vector<int> expected{2, 3, 4};
    BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(numbers), std::end(numbers), std::begin(expected), std::end(expected));
}

BOOST_AUTO_TEST_CASE( accumulate_total )
{
    std::vector<int> numbers;
    for (std::size_t i = 1; i <= 1000; ++i)
    {
        numbers.push_back(i);
    }

    int total = 0;
    auto f = [&total](int n) { total += n; };

    /*! Yes, this can be done with std::accumulate. */
    std::for_each(std::begin(numbers), std::end(numbers), f);

    /*! If you don't know this formula, review your discrete math or calculus
     * notes. Or google it. */
    int expected = 1000 * 1001 / 2;
    BOOST_CHECK_EQUAL(total, expected);
}

BOOST_AUTO_TEST_CASE( implicit_conversion_by_copy )
{
    using coord = int;
    using point = point_t<coord>;
    using rectangle = rectangle_t<coord>;
    const std::vector<point> points{{1, 2}, {-5, 3}, {4, 7}};

    coord total_area = 0;
    /*! This function takes a rectangle as parameter. The points in the
     * collection are implicitly converted to rectangle */
    auto area_accumulator = [&total_area](rectangle const& rect)
    {
        total_area += area(rect);
    };

    /*! Pass the function by copy. */
    std::for_each(std::begin(points), std::end(points), area_accumulator);

    coord expected_area = 1 * 2 + 5 * 3 + 4 * 7;
    BOOST_CHECK_EQUAL(total_area, expected_area);
}

BOOST_AUTO_TEST_CASE( implicit_conversion_by_reference )
{
    using point = point_t<int>;
    using rectangle = rectangle_t<int>;
    const std::vector<point> points{{1, 2}, {-5, 3}, {4, 7}};

    struct area_accumulator
    {
        area_accumulator()
            : total_area(0)
        {
        }

        inline void
        operator()(rectangle const& rect) const
        {
            total_area += area(rect);
        }

        mutable int total_area;
    };

    area_accumulator accumulator;

    /*! Pass the function by reference. */
    std::for_each(std::begin(points), std::end(points), std::ref(accumulator));

    int expected_area = 1 * 2 + 5 * 3 + 4 * 7;
    BOOST_CHECK_EQUAL(accumulator.total_area, expected_area);

    /*! Note how passing the accumulator by copy should give a
     * default-constructed value for the total area, which is zero. */
    area_accumulator another_accumulator;
    std::for_each(std::begin(points), std::end(points), another_accumulator);
    BOOST_CHECK_EQUAL(another_accumulator.total_area, 0);
}

BOOST_AUTO_TEST_SUITE_END( /* for_each_test_suite */ )
<commit_msg>Adds an interesting case for for_each.<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN for_each tests

#include <boost/test/unit_test.hpp>

#include <algorithm>
#include <functional>
#include <vector>

#include <point.h>

BOOST_AUTO_TEST_SUITE( for_each_test_suite )

BOOST_AUTO_TEST_CASE( sum_each_number )
{
    std::vector<int> numbers{1, 2, 3};
    auto f = [](int& n) { ++n; };

    std::for_each(std::begin(numbers), std::end(numbers), f);

    const std::vector<int> expected{2, 3, 4};
    BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(numbers), std::end(numbers), std::begin(expected), std::end(expected));
}

BOOST_AUTO_TEST_CASE( sum_each_number_twice )
{
    std::vector<int> numbers{1, 2, 3};

    /*! As std::for_each returns the function, we can use it as a lambda and
     * then apply it again, so the numbers will be increased twice. Of course
     * this particular scenario can also be achieved by adding 2 to each number,
     * but other uses can include calling the same lambda on different
     * collections. */
    std::for_each(std::begin(numbers), std::end(numbers),
            std::for_each(std::begin(numbers), std::end(numbers), [](int& n){ ++n; })
    );

    const std::vector<int> expected{3, 4, 5};
    BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(numbers), std::end(numbers), std::begin(expected), std::end(expected));
}

BOOST_AUTO_TEST_CASE( accumulate_total )
{
    std::vector<int> numbers;
    for (std::size_t i = 1; i <= 1000; ++i)
    {
        numbers.push_back(i);
    }

    int total = 0;
    auto f = [&total](int n) { total += n; };

    /*! Yes, this can be done with std::accumulate. */
    std::for_each(std::begin(numbers), std::end(numbers), f);

    /*! If you don't know this formula, review your discrete math or calculus
     * notes. Or google it. */
    int expected = 1000 * 1001 / 2;
    BOOST_CHECK_EQUAL(total, expected);
}

BOOST_AUTO_TEST_CASE( implicit_conversion_by_copy )
{
    using coord = int;
    using point = point_t<coord>;
    using rectangle = rectangle_t<coord>;
    const std::vector<point> points{{1, 2}, {-5, 3}, {4, 7}};

    coord total_area = 0;
    /*! This function takes a rectangle as parameter. The points in the
     * collection are implicitly converted to rectangle */
    auto area_accumulator = [&total_area](rectangle const& rect)
    {
        total_area += area(rect);
    };

    /*! Pass the function by copy. */
    std::for_each(std::begin(points), std::end(points), area_accumulator);

    coord expected_area = 1 * 2 + 5 * 3 + 4 * 7;
    BOOST_CHECK_EQUAL(total_area, expected_area);
}

BOOST_AUTO_TEST_CASE( implicit_conversion_by_reference )
{
    using point = point_t<int>;
    using rectangle = rectangle_t<int>;
    const std::vector<point> points{{1, 2}, {-5, 3}, {4, 7}};

    struct area_accumulator
    {
        area_accumulator()
            : total_area(0)
        {
        }

        inline void
        operator()(rectangle const& rect) const
        {
            total_area += area(rect);
        }

        mutable int total_area;
    };

    area_accumulator accumulator;

    /*! Pass the function by reference. */
    std::for_each(std::begin(points), std::end(points), std::ref(accumulator));

    int expected_area = 1 * 2 + 5 * 3 + 4 * 7;
    BOOST_CHECK_EQUAL(accumulator.total_area, expected_area);

    /*! Note how passing the accumulator by copy should give a
     * default-constructed value for the total area, which is zero. */
    area_accumulator another_accumulator;
    std::for_each(std::begin(points), std::end(points), another_accumulator);
    BOOST_CHECK_EQUAL(another_accumulator.total_area, 0);
}

BOOST_AUTO_TEST_SUITE_END( /* for_each_test_suite */ )
<|endoftext|>