<commit_before>/*************************************************************************
 *
 *  $RCSfile: svgfilter.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: ka $ $Date: 2003-12-15 13:57:22 $
 *
 *  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 SVGFILTER_HXX
#define SVGFILTER_HXX

#ifndef _COM_SUN_STAR_DRAWING_XMASTERPAGETARGET_HPP_
#include <com/sun/star/drawing/XMasterPageTarget.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGESSUPPLIER_HPP_
#include <com/sun/star/drawing/XDrawPagesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_
#include <com/sun/star/container/XNamed.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGESSUPPLIER_HPP_
#include <com/sun/star/drawing/XDrawPagesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XMASTERPAGESSUPPLIER_HPP_
#include <com/sun/star/drawing/XMasterPagesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_XPRESENTATIONSUPPLIER_HPP_
#include <com/sun/star/presentation/XPresentationSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XFILTER_HPP_
#include <com/sun/star/document/XFilter.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_
#include <com/sun/star/document/XImporter.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_
#include <com/sun/star/document/XExporter.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase5.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_
#include <com/sun/star/io/XActiveDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONEFFECT_HPP_
#include <com/sun/star/presentation/AnimationEffect.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONSPEED_HPP_
#include <com/sun/star/presentation/AnimationSpeed.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_CLICKACTION_HPP_
#include <com/sun/star/presentation/ClickAction.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_FADEEFFECT_HPP_
#include <com/sun/star/presentation/FadeEffect.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif

#include <com/sun/star/java/XJavaVM.hpp>
#include <com/sun/star/java/XJavaThreadRegister_11.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

#include <hash_map>
#include <osl/diagnose.h>
#include <rtl/process.h>
#include <tools/debug.hxx>
#include <comphelper/processfactory.hxx>
#include <unotools/tempfile.hxx>
#include <unotools/localfilehelper.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <unotools/streamwrap.hxx>
#include <vcl/cvtgrf.hxx>
#include <vcl/svapp.hxx>
#include <vcl/outdev.hxx>
#include <vcl/metaact.hxx>
#include <goodies/grfmgr.hxx>
#include <svx/unomodel.hxx>
#include <svx/unoapi.hxx>
#include <svx/svdxcgv.hxx>
#include <svx/svdobj.hxx>
#include <xmloff/xmlexp.hxx>
#include <sj2/jnihelp.hxx>
#include "svgfilter.hxx"
#include "svgscript.hxx"

using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::java;
using namespace ::com::sun::star::drawing;
using namespace ::com::sun::star::presentation;
using namespace ::com::sun::star::document;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::xml::sax;
using namespace ::std;

// -----------
// - Defines -
// -----------

#define SVG_EXPORT_ALLPAGES ((sal_Int32)-1)

// -------------
// - SVGExport -
// -------------

class SVGExport : public SvXMLExport
{
private:

                            SVGExport();

protected:

    virtual void            _ExportMeta() {}
    virtual void            _ExportStyles( BOOL bUsed ) {}
    virtual void            _ExportAutoStyles() {}
    virtual void            _ExportContent() {}
    virtual void            _ExportMasterStyles() {}
    virtual ULONG           exportDoc( enum ::xmloff::token::XMLTokenEnum eClass ) { return 0; }

public:

                            SVGExport( const Reference< XDocumentHandler >& rxHandler );
    virtual                 ~SVGExport();
};

// ------------------------
// - ObjectRepresentation -
// ------------------------

class ObjectRepresentation
{
private:

    Reference< XInterface >         mxObject;
    GDIMetaFile*                    mpMtf;

public:

                                    ObjectRepresentation();
                                    ObjectRepresentation( const Reference< XInterface >& rxIf,
                                                          const GDIMetaFile& rMtf );
                                    ObjectRepresentation( const ObjectRepresentation& rPresentation );
                                    ~ObjectRepresentation();

    ObjectRepresentation&           operator=( const ObjectRepresentation& rPresentation );
    bool                            operator==( const ObjectRepresentation& rPresentation ) const;

    const Reference< XInterface >&  GetObject() const { return mxObject; }
    sal_Bool                        HasRepresentation() const { return mpMtf != NULL; }
    const GDIMetaFile&              GetRepresentation() const { return *mpMtf; }
};

// ---------------------------
// - HashReferenceXInterface -
// ---------------------------

struct HashReferenceXInterface
{
    size_t operator()( const Reference< XInterface >& rxIf ) const { return reinterpret_cast< size_t >( rxIf.get() ); }
};

// -------------
// - SVGFilter -
// -------------

class SVGFontExport;
class SVGActionWriter;

class SVGFilter : public cppu::WeakImplHelper5 < XFilter,
                                                 XImporter,
                                                 XExporter,
                                                 XInitialization,
                                                 XServiceInfo >
{
    typedef ::std::hash_map< Reference< XInterface >, ObjectRepresentation, HashReferenceXInterface > ObjectMap;

private:

    ObjectMap*                          mpObjects;
    Reference< XMultiServiceFactory >   mxMSF;
    Reference< XComponent >             mxSrcDoc;
    Reference< XComponent >             mxDstDoc;
    SvXMLElementExport*                 mpSVGDoc;
    SVGExport*                          mpSVGExport;
    SVGFontExport*                      mpSVGFontExport;
    SVGActionWriter*                    mpSVGWriter;
    sal_Bool                            mbPresentation;

    sal_Bool                            implImport( const Sequence< PropertyValue >& rDescriptor ) throw (RuntimeException);

    sal_Bool                            implExport( const Sequence< PropertyValue >& rDescriptor ) throw (RuntimeException);
    Reference< XDocumentHandler >       implCreateExportDocumentHandler( const Reference< XOutputStream >& rxOStm );

    sal_Bool                            implGenerateMetaData( const Reference< XDrawPages >& rxMasterPages,
                                                              const Reference< XDrawPages >& rxDrawPages );
    sal_Bool                            implGenerateScript( const Reference< XDrawPages >& rxMasterPages,
                                                            const Reference< XDrawPages >& rxDrawPages );

    sal_Bool                            implExportDocument( const Reference< XDrawPages >& rxMasterPages,
                                                            const Reference< XDrawPages >& rxDrawPages,
                                                            sal_Int32 nPageToExport );

    sal_Bool                            implExportPages( const Reference< XDrawPages >& rxPages,
                                                         sal_Int32 nFirstPage, sal_Int32 nLastPage,
                                                         sal_Int32 nVisiblePage, sal_Bool bMaster );

    sal_Bool                            implExportShapes( const Reference< XShapes >& rxShapes );
    sal_Bool                            implExportShape( const Reference< XShape >& rxShape );

    sal_Bool                            implCreateObjects( const Reference< XDrawPages >& rxMasterPages,
                                                           const Reference< XDrawPages >& rxDrawPages,
                                                           sal_Int32 nPageToExport );

    sal_Bool                            implCreateObjectsFromShapes( const Reference< XShapes >& rxShapes );
    sal_Bool                            implCreateObjectsFromShape( const Reference< XShape >& rxShape );
    sal_Bool                            implCreateObjectsFromBackground( const Reference< XDrawPage >& rxMasterPage );
    OUString                            implGetDescriptionFromShape( const Reference< XShape >& rxShape );
    OUString                            implGetValidIDFromInterface( const Reference< XInterface >& rxIf );

protected:

    // XFilter
    virtual sal_Bool SAL_CALL filter( const Sequence< PropertyValue >& rDescriptor ) throw(RuntimeException);
    virtual void SAL_CALL cancel( ) throw (RuntimeException);

    // XImporter
    virtual void SAL_CALL setTargetDocument( const Reference< XComponent >& xDoc ) throw(IllegalArgumentException, RuntimeException);

    // XExporter
    virtual void SAL_CALL setSourceDocument( const Reference< XComponent >& xDoc ) throw(IllegalArgumentException, RuntimeException);

    // XInitialization
    virtual void SAL_CALL initialize( const Sequence< Any >& aArguments ) throw(Exception, RuntimeException);

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

public:

                SVGFilter( const Reference< XMultiServiceFactory > &rxMSF );
    virtual     ~SVGFilter();
};

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

::rtl::OUString SVGFilter_getImplementationName ()
    throw ( ::com::sun::star::uno::RuntimeException );

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

sal_Bool SAL_CALL SVGFilter_supportsService( const ::rtl::OUString& ServiceName )
    throw ( ::com::sun::star::uno::RuntimeException );

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

::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL SVGFilter_getSupportedServiceNames(  )
    throw ( ::com::sun::star::uno::RuntimeException );

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

::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
SAL_CALL SVGFilter_createInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rSMgr)
    throw ( ::com::sun::star::uno::Exception );

#endif // SVGFILTER_HXX
<commit_msg>INTEGRATION: CWS geordi2q11 (1.4.144); FILE MERGED 2003/12/16 12:04:15 hr 1.4.144.1: #111934#: join CWS ooo111fix1<commit_after>/*************************************************************************
 *
 *  $RCSfile: svgfilter.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: vg $ $Date: 2003-12-17 15:25: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 SVGFILTER_HXX
#define SVGFILTER_HXX

#ifndef _COM_SUN_STAR_DRAWING_XMASTERPAGETARGET_HPP_
#include <com/sun/star/drawing/XMasterPageTarget.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGESSUPPLIER_HPP_
#include <com/sun/star/drawing/XDrawPagesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_
#include <com/sun/star/container/XNamed.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGESSUPPLIER_HPP_
#include <com/sun/star/drawing/XDrawPagesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XMASTERPAGESSUPPLIER_HPP_
#include <com/sun/star/drawing/XMasterPagesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_XPRESENTATIONSUPPLIER_HPP_
#include <com/sun/star/presentation/XPresentationSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XFILTER_HPP_
#include <com/sun/star/document/XFilter.hpp>
#endif
#ifdef SOLAR_JAVA
#ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_
#include <com/sun/star/document/XImporter.hpp>
#endif
#endif // SOLAR_JAVA
#ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_
#include <com/sun/star/document/XExporter.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifdef SOLAR_JAVA
#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase5.hxx>
#endif
#else // !SOLAR_JAVA
#ifndef _CPPUHELPER_IMPLBASE4_HXX_
#include <cppuhelper/implbase4.hxx>
#endif
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_
#include <com/sun/star/io/XActiveDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONEFFECT_HPP_
#include <com/sun/star/presentation/AnimationEffect.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONSPEED_HPP_
#include <com/sun/star/presentation/AnimationSpeed.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_CLICKACTION_HPP_
#include <com/sun/star/presentation/ClickAction.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_FADEEFFECT_HPP_
#include <com/sun/star/presentation/FadeEffect.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif

#include <com/sun/star/java/XJavaVM.hpp>
#include <com/sun/star/java/XJavaThreadRegister_11.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

#include <hash_map>
#include <osl/diagnose.h>
#include <rtl/process.h>
#include <tools/debug.hxx>
#include <comphelper/processfactory.hxx>
#include <unotools/tempfile.hxx>
#include <unotools/localfilehelper.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <unotools/streamwrap.hxx>
#include <vcl/cvtgrf.hxx>
#include <vcl/svapp.hxx>
#include <vcl/outdev.hxx>
#include <vcl/metaact.hxx>
#include <goodies/grfmgr.hxx>
#include <svx/unomodel.hxx>
#include <svx/unoapi.hxx>
#include <svx/svdxcgv.hxx>
#include <svx/svdobj.hxx>
#include <xmloff/xmlexp.hxx>
#ifdef SOLAR_JAVA
#include <sj2/jnihelp.hxx>
#endif
#include "svgfilter.hxx"
#include "svgscript.hxx"

using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::java;
using namespace ::com::sun::star::drawing;
using namespace ::com::sun::star::presentation;
using namespace ::com::sun::star::document;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::xml::sax;
using namespace ::std;

// -----------
// - Defines -
// -----------

#define SVG_EXPORT_ALLPAGES ((sal_Int32)-1)

// -------------
// - SVGExport -
// -------------

class SVGExport : public SvXMLExport
{
private:

                            SVGExport();

protected:

    virtual void            _ExportMeta() {}
    virtual void            _ExportStyles( BOOL bUsed ) {}
    virtual void            _ExportAutoStyles() {}
    virtual void            _ExportContent() {}
    virtual void            _ExportMasterStyles() {}
    virtual ULONG           exportDoc( enum ::xmloff::token::XMLTokenEnum eClass ) { return 0; }

public:

                            SVGExport( const Reference< XDocumentHandler >& rxHandler );
    virtual                 ~SVGExport();
};

// ------------------------
// - ObjectRepresentation -
// ------------------------

class ObjectRepresentation
{
private:

    Reference< XInterface >         mxObject;
    GDIMetaFile*                    mpMtf;

public:

                                    ObjectRepresentation();
                                    ObjectRepresentation( const Reference< XInterface >& rxIf,
                                                          const GDIMetaFile& rMtf );
                                    ObjectRepresentation( const ObjectRepresentation& rPresentation );
                                    ~ObjectRepresentation();

    ObjectRepresentation&           operator=( const ObjectRepresentation& rPresentation );
    bool                            operator==( const ObjectRepresentation& rPresentation ) const;

    const Reference< XInterface >&  GetObject() const { return mxObject; }
    sal_Bool                        HasRepresentation() const { return mpMtf != NULL; }
    const GDIMetaFile&              GetRepresentation() const { return *mpMtf; }
};

// ---------------------------
// - HashReferenceXInterface -
// ---------------------------

struct HashReferenceXInterface
{
    size_t operator()( const Reference< XInterface >& rxIf ) const { return reinterpret_cast< size_t >( rxIf.get() ); }
};

// -------------
// - SVGFilter -
// -------------

class SVGFontExport;
class SVGActionWriter;

#ifdef SOLAR_JAVA
class SVGFilter : public cppu::WeakImplHelper5 < XFilter,
                                                 XImporter,
                                                 XExporter,
                                                 XInitialization,
                                                 XServiceInfo >
#else // !SOLAR_JAVA
class SVGFilter : public cppu::WeakImplHelper4 < XFilter,
                                                 XExporter,
                                                 XInitialization,
                                                 XServiceInfo >
#endif
{
    typedef ::std::hash_map< Reference< XInterface >, ObjectRepresentation, HashReferenceXInterface > ObjectMap;

private:

    ObjectMap*                          mpObjects;
    Reference< XMultiServiceFactory >   mxMSF;
    Reference< XComponent >             mxSrcDoc;
#ifdef SOLAR_JAVA
    Reference< XComponent >             mxDstDoc;
#endif
    SvXMLElementExport*                 mpSVGDoc;
    SVGExport*                          mpSVGExport;
    SVGFontExport*                      mpSVGFontExport;
    SVGActionWriter*                    mpSVGWriter;
    sal_Bool                            mbPresentation;

#ifdef SOLAR_JAVA
    sal_Bool                            implImport( const Sequence< PropertyValue >& rDescriptor ) throw (RuntimeException);
#endif

    sal_Bool                            implExport( const Sequence< PropertyValue >& rDescriptor ) throw (RuntimeException);
    Reference< XDocumentHandler >       implCreateExportDocumentHandler( const Reference< XOutputStream >& rxOStm );

    sal_Bool                            implGenerateMetaData( const Reference< XDrawPages >& rxMasterPages,
                                                              const Reference< XDrawPages >& rxDrawPages );
    sal_Bool                            implGenerateScript( const Reference< XDrawPages >& rxMasterPages,
                                                            const Reference< XDrawPages >& rxDrawPages );

    sal_Bool                            implExportDocument( const Reference< XDrawPages >& rxMasterPages,
                                                            const Reference< XDrawPages >& rxDrawPages,
                                                            sal_Int32 nPageToExport );

    sal_Bool                            implExportPages( const Reference< XDrawPages >& rxPages,
                                                         sal_Int32 nFirstPage, sal_Int32 nLastPage,
                                                         sal_Int32 nVisiblePage, sal_Bool bMaster );

    sal_Bool                            implExportShapes( const Reference< XShapes >& rxShapes );
    sal_Bool                            implExportShape( const Reference< XShape >& rxShape );

    sal_Bool                            implCreateObjects( const Reference< XDrawPages >& rxMasterPages,
                                                           const Reference< XDrawPages >& rxDrawPages,
                                                           sal_Int32 nPageToExport );

    sal_Bool                            implCreateObjectsFromShapes( const Reference< XShapes >& rxShapes );
    sal_Bool                            implCreateObjectsFromShape( const Reference< XShape >& rxShape );
    sal_Bool                            implCreateObjectsFromBackground( const Reference< XDrawPage >& rxMasterPage );
    OUString                            implGetDescriptionFromShape( const Reference< XShape >& rxShape );
    OUString                            implGetValidIDFromInterface( const Reference< XInterface >& rxIf );

protected:

    // XFilter
    virtual sal_Bool SAL_CALL filter( const Sequence< PropertyValue >& rDescriptor ) throw(RuntimeException);
    virtual void SAL_CALL cancel( ) throw (RuntimeException);

#ifdef SOLAR_JAVA
    // XImporter
    virtual void SAL_CALL setTargetDocument( const Reference< XComponent >& xDoc ) throw(IllegalArgumentException, RuntimeException);
#endif

    // XExporter
    virtual void SAL_CALL setSourceDocument( const Reference< XComponent >& xDoc ) throw(IllegalArgumentException, RuntimeException);

    // XInitialization
    virtual void SAL_CALL initialize( const Sequence< Any >& aArguments ) throw(Exception, RuntimeException);

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

public:

                SVGFilter( const Reference< XMultiServiceFactory > &rxMSF );
    virtual     ~SVGFilter();
};

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

::rtl::OUString SVGFilter_getImplementationName ()
    throw ( ::com::sun::star::uno::RuntimeException );

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

sal_Bool SAL_CALL SVGFilter_supportsService( const ::rtl::OUString& ServiceName )
    throw ( ::com::sun::star::uno::RuntimeException );

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

::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL SVGFilter_getSupportedServiceNames(  )
    throw ( ::com::sun::star::uno::RuntimeException );

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

::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
SAL_CALL SVGFilter_createInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rSMgr)
    throw ( ::com::sun::star::uno::Exception );

#endif // SVGFILTER_HXX
<|endoftext|>


<commit_before>// Copyright (2015) Gustav

#include "finans/core/commandline.h"

#include "gtest/gtest.h"
#include "gmock/gmock.h"

using namespace testing;

class TestSubParser : public argparse::SubParser {
public:
  TestSubParser() {
  }

  void AddParser(argparse::Parser& parser) override {
    parser.AddOption("-name", name);
  }

  void ParseCompleted() override {
  }

  std::string name;
};

struct CommandlineTest : public Test {
  std::ostringstream output;
  std::ostringstream error;

  argparse::Parser parser;
  std::string animal;
  std::string another;

  TestSubParser sp1;
  TestSubParser sp2;
  argparse::Parser sub;

  CommandlineTest() : parser("description"), sub("description") {
    parser.AddOption("pos", animal);
    parser.AddOption("-op", another);
    sub.AddSubParser("one", &sp1);
    sub.AddSubParser("two", &sp2);
  }
};

#define GTEST(x) TEST_F(CommandlineTest, x)

GTEST(TestEmpty) {
  argparse::Parser parser("description");
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", {}), output, error);
  EXPECT_EQ(true, ok);

  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
}

GTEST(TestError) {

  argparse::Parser parser("description");
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "hello", "world" }), output, error);

  EXPECT_EQ(false, ok);
  EXPECT_EQ("Usage: [-h]\n", output.str());
  EXPECT_EQ("error: All positional arguments have been consumed: hello\n", error.str());
}

GTEST(TestOptionalDefault) {
  int op = 2;

  argparse::Parser parser("description");
  parser.AddOption("-op", op);
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", {}), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
  EXPECT_EQ(2, op);
}

GTEST(TestOptionalValue) {
  int op = 2;

  argparse::Parser parser("description");
  parser.AddOption("-op", op);
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-op", "42" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
  EXPECT_EQ(42, op);
}

GTEST(TestPositionalValue) {
  int op = 2;

  argparse::Parser parser("description");
  parser.AddOption("op", op);
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "42" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
  EXPECT_EQ(42, op);
}

GTEST(TestPositionalValueErr) {
  int op = 42;

  argparse::Parser parser("description");
  parser.AddOption("op", op);
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", {}), output, error);

  EXPECT_EQ(false, ok);
  EXPECT_EQ("error: too few arguments.\n", error.str());
  EXPECT_EQ("Usage: [-h] op\n", output.str());
  EXPECT_EQ(42, op); // not touched
}

GTEST(TestStdVector) {
  std::vector<std::string> strings;

  argparse::Parser parser("description");
  parser.AddGreedy("-strings", strings, "string");
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-strings", "cat", "dog", "fish" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
  EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish"));
}

GTEST(TestStdVectorInts) {
  std::vector<int> ints;

  argparse::Parser parser("description");
  parser.AddGreedy("-ints", ints, "string");
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-ints", "2", "3", "-5", "4" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
  EXPECT_THAT(ints, ElementsAre(2, 3, -5, 4));
}

GTEST(TestNonGreedyVector) {
  std::vector<std::string> strings;

  argparse::Parser parser("description");
  parser.AddOption("-s", strings);
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-s", "cat", "-s", "dog", "-s", "fish" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
  EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish"));
}

enum class Day
{
  TODAY, YESTERDAY, TOMORROW
};

ARGPARSE_DEFINE_ENUM(Day, "day", ("Today", Day::TODAY)("Tomorrow", Day::TOMORROW)("Yesterday", Day::YESTERDAY))

GTEST(TestEnum) {
  Day op = Day::TOMORROW;

  argparse::Parser parser("description");
  parser.AddOption("op", op);
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "tod" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
  EXPECT_EQ(Day::TODAY, op);
}

GTEST(TestCommaOp) {
  int op = 2;

  argparse::Parser parser("description");
  parser.AddOption("-int,-i", op);
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-int", "42" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
  EXPECT_EQ(42, op);
}

GTEST(TestSpecifyTwice) {
  int op = 2;

  argparse::Parser parser("description");
  parser.AddOption("-int,-i", op);
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-int", "42", "-i", "50" }), output, error);

  EXPECT_EQ(false, ok);
  EXPECT_EQ("error: All positional arguments have been consumed: -i\n", error.str());
  EXPECT_EQ("Usage: [-h] [-int,-i int]\n", output.str());
  EXPECT_EQ(42, op);
}

GTEST(TestPrecedencePos) {
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "dog" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
  EXPECT_EQ("dog", animal);
  EXPECT_EQ("", another);
}

GTEST(TestPrecedencePosOp) {
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-dog", "-op", "cat" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", output.str());
  EXPECT_EQ("", error.str());
  EXPECT_EQ("-dog", animal);
  EXPECT_EQ("cat", another);
}

GTEST(TestPrecedenceOpPos) {
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-op", "cat", "dog" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
  EXPECT_EQ("dog", animal);
  EXPECT_EQ("cat", another);
}

GTEST(TestStoreConstInt) {
  int op = 12;

  argparse::Parser parser("description");
  parser.StoreConst("-store", op, 42);
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-store" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", output.str());
  EXPECT_EQ("", error.str());
  EXPECT_EQ(42, op);
}

GTEST(TestStoreConstString) {
  std::string op = "";

  argparse::Parser parser("description");
  parser.StoreConst<std::string>("-store", op, "dog");
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-store" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", output.str());
  EXPECT_EQ("", error.str());
  EXPECT_EQ("dog", op);
}

GTEST(TestSubParserBasic) {
  const bool ok = argparse::Parser::ParseComplete ==
    sub.ParseArgs(argparse::Arguments("app.exe", { "one", "-name", "dog" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", output.str());
  EXPECT_EQ("", error.str());
  EXPECT_EQ("dog", sp1.name);
  EXPECT_EQ("", sp2.name);
}

GTEST(TestSubParserOptional) {
  std::string op = "";
  sub.AddOption("-op", op);
  const bool ok = argparse::Parser::ParseComplete ==
    sub.ParseArgs(argparse::Arguments("app.exe", { "-op", "cat", "on", "-name", "dog" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", output.str());
  EXPECT_EQ("", error.str());
  EXPECT_EQ("cat", op);
  EXPECT_EQ("dog", sp1.name);
  EXPECT_EQ("", sp2.name);
}

GTEST(TestSubParserPositional) {
  std::string op = "";
  sub.AddOption("op", op);
  const bool ok = argparse::Parser::ParseComplete ==
    sub.ParseArgs(argparse::Arguments("app.exe", { "cat", "on", "-name", "dog" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", output.str());
  EXPECT_EQ("", error.str());
  EXPECT_EQ("cat", op);
  EXPECT_EQ("dog", sp1.name);
  EXPECT_EQ("", sp2.name);
}

GTEST(TestCallingSubParserWithBadArguments) {
  const bool ok = argparse::Parser::ParseComplete ==
    sub.ParseArgs(argparse::Arguments("app.exe", { "on", "cat" }), output, error);

  EXPECT_EQ(false, ok);
  EXPECT_EQ("Usage: [-h] ONE [-h] [-name name]\n", output.str());
  EXPECT_EQ("error: Failed to parse ONE:\nerror: All positional arguments have been consumed: cat\n", error.str());
  EXPECT_EQ("", sp1.name);
  EXPECT_EQ("", sp2.name);
}

GTEST(TestCallingInvalidSubParser) {
  const bool ok = argparse::Parser::ParseComplete ==
    sub.ParseArgs(argparse::Arguments("app.exe", { "dog", "cat" }), output, error);

  EXPECT_EQ(false, ok);
  EXPECT_EQ("Usage: [-h] {ONE|TWO}\n", output.str());
  EXPECT_EQ("error: Unable to match DOG as a subparser.\n", error.str());
  EXPECT_EQ("", sp1.name);
  EXPECT_EQ("", sp2.name);
}

// todo: test help string when calling -h

GTEST(TestCallingHelpBasic) {
  argparse::Parser parser("Description of app.");
  const bool ok = argparse::Parser::ParseQuit ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-h" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("Usage: app.exe [-h]\nDescription of app.\n\nOptional arguments:\n  -h\tShow this help message and exit.\n\n", output.str());
  EXPECT_EQ("", error.str());
}

GTEST(TestCallingHelpBasicCustomName) {
  argparse::Parser parser("Description of app.", "awesome.exe");
  const bool ok = argparse::Parser::ParseQuit ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-h" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("Usage: awesome.exe [-h]\nDescription of app.\n\nOptional arguments:\n  -h\tShow this help message and exit.\n\n", output.str());
  EXPECT_EQ("", error.str());
}

<commit_msg>added another test case<commit_after>// Copyright (2015) Gustav

#include "finans/core/commandline.h"

#include "gtest/gtest.h"
#include "gmock/gmock.h"

using namespace testing;

class TestSubParser : public argparse::SubParser {
public:
  TestSubParser() {
  }

  void AddParser(argparse::Parser& parser) override {
    parser.AddOption("-name", name);
  }

  void ParseCompleted() override {
  }

  std::string name;
};

struct CommandlineTest : public Test {
  std::ostringstream output;
  std::ostringstream error;

  argparse::Parser parser;
  std::string animal;
  std::string another;

  TestSubParser sp1;
  TestSubParser sp2;
  argparse::Parser sub;

  CommandlineTest() : parser("description"), sub("description") {
    parser.AddOption("pos", animal);
    parser.AddOption("-op", another);
    sub.AddSubParser("one", &sp1);
    sub.AddSubParser("two", &sp2);
  }
};

#define GTEST(x) TEST_F(CommandlineTest, x)

GTEST(TestEmpty) {
  argparse::Parser parser("description");
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", {}), output, error);
  EXPECT_EQ(true, ok);

  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
}

GTEST(TestError) {

  argparse::Parser parser("description");
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "hello", "world" }), output, error);

  EXPECT_EQ(false, ok);
  EXPECT_EQ("Usage: [-h]\n", output.str());
  EXPECT_EQ("error: All positional arguments have been consumed: hello\n", error.str());
}

GTEST(TestOptionalDefault) {
  int op = 2;

  argparse::Parser parser("description");
  parser.AddOption("-op", op);
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", {}), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
  EXPECT_EQ(2, op);
}

GTEST(TestOptionalValue) {
  int op = 2;

  argparse::Parser parser("description");
  parser.AddOption("-op", op);
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-op", "42" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
  EXPECT_EQ(42, op);
}

GTEST(TestPositionalValue) {
  int op = 2;

  argparse::Parser parser("description");
  parser.AddOption("op", op);
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "42" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
  EXPECT_EQ(42, op);
}

GTEST(TestPositionalValueErr) {
  int op = 42;

  argparse::Parser parser("description");
  parser.AddOption("op", op);
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", {}), output, error);

  EXPECT_EQ(false, ok);
  EXPECT_EQ("error: too few arguments.\n", error.str());
  EXPECT_EQ("Usage: [-h] op\n", output.str());
  EXPECT_EQ(42, op); // not touched
}

GTEST(TestStdVector) {
  std::vector<std::string> strings;

  argparse::Parser parser("description");
  parser.AddGreedy("-strings", strings, "string");
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-strings", "cat", "dog", "fish" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
  EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish"));
}

GTEST(TestStdVectorInts) {
  std::vector<int> ints;

  argparse::Parser parser("description");
  parser.AddGreedy("-ints", ints, "string");
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-ints", "2", "3", "-5", "4" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
  EXPECT_THAT(ints, ElementsAre(2, 3, -5, 4));
}

GTEST(TestNonGreedyVector) {
  std::vector<std::string> strings;

  argparse::Parser parser("description");
  parser.AddOption("-s", strings);
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-s", "cat", "-s", "dog", "-s", "fish" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
  EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish"));
}

enum class Day
{
  TODAY, YESTERDAY, TOMORROW
};

ARGPARSE_DEFINE_ENUM(Day, "day", ("Today", Day::TODAY)("Tomorrow", Day::TOMORROW)("Yesterday", Day::YESTERDAY))

GTEST(TestEnum) {
  Day op = Day::TOMORROW;

  argparse::Parser parser("description");
  parser.AddOption("op", op);
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "tod" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
  EXPECT_EQ(Day::TODAY, op);
}

GTEST(TestCommaOp) {
  int op = 2;

  argparse::Parser parser("description");
  parser.AddOption("-int,-i", op);
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-int", "42" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
  EXPECT_EQ(42, op);
}

GTEST(TestSpecifyTwice) {
  int op = 2;

  argparse::Parser parser("description");
  parser.AddOption("-int,-i", op);
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-int", "42", "-i", "50" }), output, error);

  EXPECT_EQ(false, ok);
  EXPECT_EQ("error: All positional arguments have been consumed: -i\n", error.str());
  EXPECT_EQ("Usage: [-h] [-int,-i int]\n", output.str());
  EXPECT_EQ(42, op);
}

GTEST(TestPrecedencePos) {
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "dog" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
  EXPECT_EQ("dog", animal);
  EXPECT_EQ("", another);
}

GTEST(TestPrecedencePosOp) {
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-dog", "-op", "cat" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", output.str());
  EXPECT_EQ("", error.str());
  EXPECT_EQ("-dog", animal);
  EXPECT_EQ("cat", another);
}

GTEST(TestPrecedenceOpPos) {
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-op", "cat", "dog" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", output.str());
  EXPECT_EQ("dog", animal);
  EXPECT_EQ("cat", another);
}

GTEST(TestStoreConstInt) {
  int op = 12;

  argparse::Parser parser("description");
  parser.StoreConst("-store", op, 42);
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-store" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", output.str());
  EXPECT_EQ("", error.str());
  EXPECT_EQ(42, op);
}

GTEST(TestStoreConstString) {
  std::string op = "";

  argparse::Parser parser("description");
  parser.StoreConst<std::string>("-store", op, "dog");
  const bool ok = argparse::Parser::ParseComplete ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-store" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", output.str());
  EXPECT_EQ("", error.str());
  EXPECT_EQ("dog", op);
}

GTEST(TestSubParserBasic) {
  const bool ok = argparse::Parser::ParseComplete ==
    sub.ParseArgs(argparse::Arguments("app.exe", { "one", "-name", "dog" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", output.str());
  EXPECT_EQ("", error.str());
  EXPECT_EQ("dog", sp1.name);
  EXPECT_EQ("", sp2.name);
}

GTEST(TestSubParserOptional) {
  std::string op = "";
  sub.AddOption("-op", op);
  const bool ok = argparse::Parser::ParseComplete ==
    sub.ParseArgs(argparse::Arguments("app.exe", { "-op", "cat", "on", "-name", "dog" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", output.str());
  EXPECT_EQ("", error.str());
  EXPECT_EQ("cat", op);
  EXPECT_EQ("dog", sp1.name);
  EXPECT_EQ("", sp2.name);
}

GTEST(TestSubParserPositional) {
  std::string op = "";
  sub.AddOption("op", op);
  const bool ok = argparse::Parser::ParseComplete ==
    sub.ParseArgs(argparse::Arguments("app.exe", { "cat", "on", "-name", "dog" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("", output.str());
  EXPECT_EQ("", error.str());
  EXPECT_EQ("cat", op);
  EXPECT_EQ("dog", sp1.name);
  EXPECT_EQ("", sp2.name);
}

GTEST(TestCallingSubParserWithBadArguments) {
  const bool ok = argparse::Parser::ParseComplete ==
    sub.ParseArgs(argparse::Arguments("app.exe", { "on", "cat" }), output, error);

  EXPECT_EQ(false, ok);
  EXPECT_EQ("Usage: [-h] ONE [-h] [-name name]\n", output.str());
  EXPECT_EQ("error: Failed to parse ONE:\nerror: All positional arguments have been consumed: cat\n", error.str());
  EXPECT_EQ("", sp1.name);
  EXPECT_EQ("", sp2.name);
}

GTEST(TestCallingInvalidSubParser) {
  const bool ok = argparse::Parser::ParseComplete ==
    sub.ParseArgs(argparse::Arguments("app.exe", { "dog", "cat" }), output, error);

  EXPECT_EQ(false, ok);
  EXPECT_EQ("Usage: [-h] {ONE|TWO}\n", output.str());
  EXPECT_EQ("error: Unable to match DOG as a subparser.\n", error.str());
  EXPECT_EQ("", sp1.name);
  EXPECT_EQ("", sp2.name);
}

// todo: test help string when calling -h

GTEST(TestCallingHelpBasic) {
  argparse::Parser parser("Description of app.");
  const bool ok = argparse::Parser::ParseQuit ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-h" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("Usage: app.exe [-h]\nDescription of app.\n\nOptional arguments:\n  -h\tShow this help message and exit.\n\n", output.str());
  EXPECT_EQ("", error.str());
}

GTEST(TestCallingHelpBasicCustomName) {
  argparse::Parser parser("Description of app.", "awesome.exe");
  const bool ok = argparse::Parser::ParseQuit ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-h" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("Usage: awesome.exe [-h]\nDescription of app.\n\nOptional arguments:\n  -h\tShow this help message and exit.\n\n", output.str());
  EXPECT_EQ("", error.str());
}

GTEST(TestCallingHelpOp) {
  argparse::Parser parser("Description of app.");
  std::string op = "";
  std::string ap = "";
  parser.AddOption("-op", op);
  parser.AddOption("-ap", ap);
  const bool ok = argparse::Parser::ParseQuit ==
    parser.ParseArgs(argparse::Arguments("app.exe", { "-h" }), output, error);

  EXPECT_EQ(true, ok);
  EXPECT_EQ("Usage: app.exe [-h] [-op op] [-ap ap]\nDescription of app.\n\nOptional arguments:\n"
    "  -ap ap\n"
    "  -h\tShow this help message and exit.\n"
    "  -op op\n"
    "\n", output.str());
  EXPECT_EQ("", error.str());
}
<|endoftext|>


<commit_before>/*
 * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
#define BOOST_TEST_MAIN

#define BOOST_TEST_MODULE jobtopology_test
#include <boost/test/unit_test.hpp>
#include <votca/xtp/jobtopology.h>

using namespace votca::xtp;
using namespace std;

BOOST_AUTO_TEST_SUITE(jobtopology_test)

BOOST_AUTO_TEST_CASE(constructor) {

  ofstream jobstream("job.xml");
  jobstream << "	<job>" << std::endl;
  jobstream << "		<id>0</id>" << std::endl;
  jobstream << "		<tag>seg0:n</tag>" << std::endl;
  jobstream << "		<input>" << std::endl;
  jobstream << "			<site_energy>0:n</site_energy>"
            << std::endl;
  jobstream << "			<regions>" << std::endl;
  jobstream << "				<region>" << std::endl;
  jobstream << "					<id>0</id>" << std::endl;
  jobstream
      << "					<segments>0:n</segments>"
      << std::endl;
  jobstream << "				</region>" << std::endl;
  jobstream << "			</regions>" << std::endl;
  jobstream << "		</input>" << std::endl;
  jobstream << "		<status>AVAILABLE</status>" << std::endl;
  jobstream << "	</job>" << std::endl;

  votca::tools::Property prop;
  votca::tools::load_property_from_xml(prop, "job.xml");
  std::string workdir = ".";
  Logger log;
  Job job(prop.get("job"));
  JobTopology top(job, log, workdir);
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>fix format<commit_after>/*
 * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
#define BOOST_TEST_MAIN

#define BOOST_TEST_MODULE jobtopology_test
#include <boost/test/unit_test.hpp>
#include <votca/xtp/jobtopology.h>

using namespace votca::xtp;
using namespace std;

BOOST_AUTO_TEST_SUITE(jobtopology_test)

BOOST_AUTO_TEST_CASE(constructor) {

  ofstream jobstream("job.xml");
  jobstream << "	<job>" << std::endl;
  jobstream << "		<id>0</id>" << std::endl;
  jobstream << "		<tag>seg0:n</tag>" << std::endl;
  jobstream << "		<input>" << std::endl;
  jobstream << "			<site_energy>0:n</site_energy>"
            << std::endl;
  jobstream << "			<regions>" << std::endl;
  jobstream << "				<region>" << std::endl;
  jobstream << "					<id>0</id>"
            << std::endl;
  jobstream
      << "					<segments>0:n</segments>"
      << std::endl;
  jobstream << "				</region>" << std::endl;
  jobstream << "			</regions>" << std::endl;
  jobstream << "		</input>" << std::endl;
  jobstream << "		<status>AVAILABLE</status>" << std::endl;
  jobstream << "	</job>" << std::endl;

  votca::tools::Property prop;
  votca::tools::load_property_from_xml(prop, "job.xml");
  std::string workdir = ".";
  Logger log;
  Job job(prop.get("job"));
  JobTopology top(job, log, workdir);
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>
#include <iostream>
#include <vector>

#include <cmdline.hpp>

#include <mergehelper.hpp>
#include <merging/automergestrategy.hpp>
#include <merging/onesidestrategy.hpp>
#include <merging/newkeystrategy.hpp>
#include <merging/interactivemergestrategy.hpp>

using namespace kdb;
using namespace kdb::tools::merging;
using namespace std;

MergeHelper::MergeHelper()
{
	// TODO: this is just a quickfix, find a better solution
	// without eager instantiating all the strategies. Maybe even automatically
	// discover all available strategies
	// comment markus: the factory could be part of libtools
	strategyMap.insert (make_pair ("preserve", new AutoMergeStrategy()));

	strategyMap.insert (make_pair ("ours", new OneSideStrategy(OURS)));
	strategyMap.insert (make_pair ("theirs", new OneSideStrategy(THEIRS)));
	strategyMap.insert (make_pair ("base", new OneSideStrategy(BASE)));
	strategyMap.insert (make_pair ("newkey", new NewKeyStrategy()));
	strategyMap.insert (make_pair ("ourvalue", new OneSideStrategy(OURS)));
	strategyMap.insert (make_pair ("theirvalue", new OneSideStrategy(THEIRS)));
}

MergeHelper::~MergeHelper()
{
	vector<MergeConflictStrategy*> strategies = getAllStrategies();
	for (vector<MergeConflictStrategy*>::iterator it = strategies.begin(); it != strategies.end (); ++it)
	{
		delete (*it);
	}
}

vector<MergeConflictStrategy*> MergeHelper::getAllStrategies()
{
	vector<MergeConflictStrategy*> result;
	for (map<string, MergeConflictStrategy*>::iterator it = strategyMap.begin (); it != strategyMap.end (); ++it)
	{
		result.push_back ((*it).second);
	}

	return result;
}

string MergeHelper::getStrategyList()
{
	ostringstream oss;
	for (map<string, MergeConflictStrategy*>::iterator it = strategyMap.begin (); it != strategyMap.end (); ++it)
	{
		oss << (*it).first << ",";
	}

	return oss.str ();
}

void MergeHelper::parseStrategies(Cmdline const& cl, ThreeWayMerge& merger)
{

	if (cl.interactive)
	{
		merger.addConflictStrategy (new InteractiveMergeStrategy (cin, cout));
		cout << "Chose interactive merge" << endl;
	}
	else
	{
		if (cl.strategy.size () > 0)
		{
			// strategies are comma separated, split them
			istringstream sstream (cl.strategy);
			string current;
			while (getline (sstream, current, ','))
			{
				if (strategyMap.find (current) == strategyMap.end ())
				{
					throw invalid_argument (
							"'" + current + "' is not a valid strategy. Valid strategies are: " + getStrategyList ());
				}

				MergeConflictStrategy *strategy = strategyMap[current];
				merger.addConflictStrategy (strategy);
			}
		}
	}
}

void MergeHelper::reportResult(Cmdline const& cl, MergeResult& result, ostream& out, ostream& err)
{

	if (!result.hasConflicts ())
	{
		if (cl.verbose)
		{
			out << result.getMergedKeys().size() << " keys in the result" << endl;
			out << result.getNumberOfEqualKeys() << " keys were equal" << endl;
			out << result.getNumberOfResolvedKeys() << " keys were resolved" << endl;
		}
	}
	else
	{
		KeySet conflicts = result.getConflictSet();

		err << conflicts.size() << " conflicts were detected that could not be resolved automatically:" << endl;
		conflicts.rewind();
		Key current;
		while ((current = conflicts.next()))
		{
			string ourConflict = current.getMeta<string> ("conflict/operation/our");
			string theirConflict = current.getMeta<string> ("conflict/operation/their");

			err << current << endl;
			err << "ours: " << ourConflict << ", theirs: " << theirConflict << endl;
			err << endl;
		}

		err << "Merge unsuccessful." << endl;
	}
}
<commit_msg>Fixed a merge conflict presentation bug<commit_after>
#include <iostream>
#include <vector>

#include <cmdline.hpp>
#include <keysetio.hpp>

#include <mergehelper.hpp>
#include <merging/automergestrategy.hpp>
#include <merging/onesidestrategy.hpp>
#include <merging/newkeystrategy.hpp>
#include <merging/interactivemergestrategy.hpp>

using namespace kdb;
using namespace kdb::tools::merging;
using namespace std;

MergeHelper::MergeHelper()
{
	// TODO: this is just a quickfix, find a better solution
	// without eager instantiating all the strategies. Maybe even automatically
	// discover all available strategies
	// comment markus: the factory could be part of libtools
	strategyMap.insert (make_pair ("preserve", new AutoMergeStrategy()));

	strategyMap.insert (make_pair ("ours", new OneSideStrategy(OURS)));
	strategyMap.insert (make_pair ("theirs", new OneSideStrategy(THEIRS)));
	strategyMap.insert (make_pair ("base", new OneSideStrategy(BASE)));
	strategyMap.insert (make_pair ("newkey", new NewKeyStrategy()));
	strategyMap.insert (make_pair ("ourvalue", new OneSideStrategy(OURS)));
	strategyMap.insert (make_pair ("theirvalue", new OneSideStrategy(THEIRS)));
}

MergeHelper::~MergeHelper()
{
	vector<MergeConflictStrategy*> strategies = getAllStrategies();
	for (vector<MergeConflictStrategy*>::iterator it = strategies.begin(); it != strategies.end (); ++it)
	{
		delete (*it);
	}
}

vector<MergeConflictStrategy*> MergeHelper::getAllStrategies()
{
	vector<MergeConflictStrategy*> result;
	for (map<string, MergeConflictStrategy*>::iterator it = strategyMap.begin (); it != strategyMap.end (); ++it)
	{
		result.push_back ((*it).second);
	}

	return result;
}

string MergeHelper::getStrategyList()
{
	ostringstream oss;
	for (map<string, MergeConflictStrategy*>::iterator it = strategyMap.begin (); it != strategyMap.end (); ++it)
	{
		oss << (*it).first << ",";
	}

	return oss.str ();
}

void MergeHelper::parseStrategies(Cmdline const& cl, ThreeWayMerge& merger)
{

	if (cl.interactive)
	{
		merger.addConflictStrategy (new InteractiveMergeStrategy (cin, cout));
		cout << "Chose interactive merge" << endl;
	}
	else
	{
		if (cl.strategy.size () > 0)
		{
			// strategies are comma separated, split them
			istringstream sstream (cl.strategy);
			string current;
			while (getline (sstream, current, ','))
			{
				if (strategyMap.find (current) == strategyMap.end ())
				{
					throw invalid_argument (
							"'" + current + "' is not a valid strategy. Valid strategies are: " + getStrategyList ());
				}

				MergeConflictStrategy *strategy = strategyMap[current];
				merger.addConflictStrategy (strategy);
			}
		}
	}
}

void MergeHelper::reportResult(Cmdline const& cl, MergeResult& result, ostream& out, ostream& err)
{

	if (!result.hasConflicts ())
	{
		if (cl.verbose)
		{
			out << result.getMergedKeys().size() << " keys in the result" << endl;
			out << result.getNumberOfEqualKeys() << " keys were equal" << endl;
			out << result.getNumberOfResolvedKeys() << " keys were resolved" << endl;
		}
	}
	else
	{
		KeySet conflicts = result.getConflictSet();

		err << conflicts.size() << " conflicts were detected that could not be resolved automatically:" << endl;
		conflicts.rewind();
		Key current;
		while ((current = conflicts.next()))
		{
			string ourConflict = current.getMeta<string> ("conflict/operation/our");
			string theirConflict = current.getMeta<string> ("conflict/operation/their");

			err << current << endl;
			err << "ours: " << ourConflict << ", theirs: " << theirConflict << endl;
			err << endl;
		}

		err << "Merge unsuccessful." << endl;
	}
}
<|endoftext|>


<commit_before>#include "WeatherParser.h"
#include "JsonListener.h"
#include "EWCConfig.h"
typedef void (*FunctPtr)(int8_t x);
String _lastKey = "";
FunctPtr _temperature;
FunctPtr _weather;
bool _temperatureDone = false;
bool _weatherDone = false;

void WeatherListener::weather(FunctPtr callback)
{
  _weather = callback;
}

void WeatherListener::temperature(FunctPtr callback)
{
  _temperature = callback;
}

void WeatherListener::whitespace(char c) {
//  Serial.println("whitespace");
}

void WeatherListener::startDocument() {
//  Serial.println("start document");
  _lastKey = "";
  _temperatureDone = false;
  _weatherDone = false;
}

void WeatherListener::key(String key) {
  // Serial.println("key: " + key);
  _lastKey = key;
}

void WeatherListener::value(String value) {
  if (_lastKey == "day" && !_temperatureDone) {
    DEBUG_PRINTLN("-temp: " + value);
    _temperature((int8_t)ROUND_INT(value.toFloat()));
    _temperatureDone = true;
  }
  else if (_lastKey = "icon" && !_weatherDone) {
    DEBUG_PRINTLN("-icon: " + value);
    _weatherDone = true;
    if (value == "01d") {
      _weather((int8_t)WEATHER_SONNE);
    }
    else if (value == "02d") {
      _weather((int8_t)WEATHER_SONNEMITWOLKEN);
    }
    else if (value == "03d") {
      _weather((int8_t)WEATHER_WOLKEN);
    }
    else if (value == "04d") {
      _weather((int8_t)WEATHER_WOLKEN);
    }
    else if (value == "09d") {
      _weather((int8_t)WEATHER_REGEN);
    }
    else if (value == "10d") {
      _weather((int8_t)WEATHER_REGEN);
    }
    else if (value == "11d") {
      _weather((int8_t)WEATHER_STURM);
    }
    else if (value == "13d") {
      _weather((int8_t)WEATHER_SCHNEE);
    }
    else if (value == "50d") {
      _weather((int8_t)WEATHER_NEBEL);
    }
  }
}

void WeatherListener::endArray() {
//  Serial.println("end array. ");
}

void WeatherListener::endObject() {
//  Serial.println("end object. ");
}

void WeatherListener::endDocument() {
//  Serial.println("end document. ");
}

void WeatherListener::startArray() {
//  Serial.println("start array. ");
}

void WeatherListener::startObject() {
//  Serial.println("start object. ");
}
<commit_msg>Fix weather assignment<commit_after>#include "WeatherParser.h"
#include "JsonListener.h"
#include "EWCConfig.h"
typedef void (*FunctPtr)(int8_t x);
String _lastKey = "";
FunctPtr _temperature;
FunctPtr _weather;
bool _temperatureDone = false;
bool _weatherDone = false;

void WeatherListener::weather(FunctPtr callback)
{
  _weather = callback;
}

void WeatherListener::temperature(FunctPtr callback)
{
  _temperature = callback;
}

void WeatherListener::whitespace(char c) {
//  Serial.println("whitespace");
}

void WeatherListener::startDocument() {
//  Serial.println("start document");
  _lastKey = "";
  _temperatureDone = false;
  _weatherDone = false;
}

void WeatherListener::key(String key) {
  // Serial.println("key: " + key);
  _lastKey = key;
}

void WeatherListener::value(String value) {
  if (_lastKey == "day" && !_temperatureDone) {
    DEBUG_PRINTLN("-temp: " + value);
    _temperature((int8_t)ROUND_INT(value.toFloat()));
    _temperatureDone = true;
  }
  else if (_lastKey == "icon" && !_weatherDone) {
    DEBUG_PRINTLN("-icon: " + value);
    _weatherDone = true;
    if (value == "01d") {
      _weather((int8_t)WEATHER_SONNE);
    }
    else if (value == "02d") {
      _weather((int8_t)WEATHER_SONNEMITWOLKEN);
    }
    else if (value == "03d") {
      _weather((int8_t)WEATHER_WOLKEN);
    }
    else if (value == "04d") {
      _weather((int8_t)WEATHER_WOLKEN);
    }
    else if (value == "09d") {
      _weather((int8_t)WEATHER_REGEN);
    }
    else if (value == "10d") {
      _weather((int8_t)WEATHER_REGEN);
    }
    else if (value == "11d") {
      _weather((int8_t)WEATHER_STURM);
    }
    else if (value == "13d") {
      _weather((int8_t)WEATHER_SCHNEE);
    }
    else if (value == "50d") {
      _weather((int8_t)WEATHER_NEBEL);
    }
  }
}

void WeatherListener::endArray() {
//  Serial.println("end array. ");
}

void WeatherListener::endObject() {
//  Serial.println("end object. ");
}

void WeatherListener::endDocument() {
//  Serial.println("end document. ");
}

void WeatherListener::startArray() {
//  Serial.println("start array. ");
}

void WeatherListener::startObject() {
//  Serial.println("start object. ");
}
<|endoftext|>


<commit_before>// $Id: GlobalTypes_test.C,v 1.1 2000/12/13 16:44:38 oliver Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////

#include <BALL/common.h>

///////////////////////////

// Verify that the globally defined data types (from
// COMMON/global.h) have the correct size on all platforms.
// This is required for portable persistence.

START_TEST(sizes of the global data types, "$Id: GlobalTypes_test.C,v 1.1 2000/12/13 16:44:38 oliver Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;

CHECK(size of Distance)
	TEST_EQUAL(sizeof(Distance), 4)
RESULT

CHECK(size of Handle)
	TEST_EQUAL(sizeof(Handle), 4)
RESULT

CHECK(size of Index)
	TEST_EQUAL(sizeof(Index), 4)
RESULT

CHECK(size of Size)
	TEST_EQUAL(sizeof(Size), 4)
RESULT

CHECK(size of Time)
	TEST_EQUAL(sizeof(Size), sizeof(time_t))
RESULT

CHECK(size of HashIndex)
	TEST_EQUAL(sizeof(HashIndex), 4)
RESULT

CHECK(size of Position)
	TEST_EQUAL(sizeof(Position), 4)
RESULT

CHECK(size of Real)
	TEST_EQUAL(sizeof(Real), 4)
RESULT

CHECK(size of DoubleReal)
	TEST_EQUAL(sizeof(DoubleReal), 8)
RESULT

CHECK(size of Property)
	TEST_EQUAL(sizeof(Property), 4)
RESULT

CHECK(size of ErrorCode)
	TEST_EQUAL(sizeof(ErrorCode), 4)
RESULT

CHECK(size of Byte)
	TEST_EQUAL(sizeof(Byte), 1)
RESULT

CHECK(size of PointerSizeInt)
	TEST_EQUAL(sizeof(PointerSizeInt), 8)
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>fixed: time_t is not platform independent in size (trouble on 64bit machines)<commit_after>// $Id: GlobalTypes_test.C,v 1.2 2001/05/17 18:20:14 oliver Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////

#include <BALL/common.h>

///////////////////////////

// Verify that the globally defined data types (from
// COMMON/global.h) have the correct size on all platforms.
// This is required for portable persistence.

START_TEST(sizes of the global data types, "$Id: GlobalTypes_test.C,v 1.2 2001/05/17 18:20:14 oliver Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;

CHECK(size of Distance)
	TEST_EQUAL(sizeof(Distance), 4)
RESULT

CHECK(size of Handle)
	TEST_EQUAL(sizeof(Handle), 4)
RESULT

CHECK(size of Index)
	TEST_EQUAL(sizeof(Index), 4)
RESULT

CHECK(size of Size)
	TEST_EQUAL(sizeof(Size), 4)
RESULT

CHECK(size of Time)
	TEST_EQUAL(sizeof(Time), sizeof(time_t))
RESULT

CHECK(size of HashIndex)
	TEST_EQUAL(sizeof(HashIndex), 4)
RESULT

CHECK(size of Position)
	TEST_EQUAL(sizeof(Position), 4)
RESULT

CHECK(size of Real)
	TEST_EQUAL(sizeof(Real), 4)
RESULT

CHECK(size of DoubleReal)
	TEST_EQUAL(sizeof(DoubleReal), 8)
RESULT

CHECK(size of Property)
	TEST_EQUAL(sizeof(Property), 4)
RESULT

CHECK(size of ErrorCode)
	TEST_EQUAL(sizeof(ErrorCode), 4)
RESULT

CHECK(size of Byte)
	TEST_EQUAL(sizeof(Byte), 1)
RESULT

CHECK(size of PointerSizeInt)
	TEST_EQUAL(sizeof(PointerSizeInt), 8)
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|>


<commit_before>#define __CL_ENABLE_EXCEPTIONS

#include <CL/cl.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "DeviceInfo.h"

const int COMPLETE = -1;
const int READ = 0;
const int WRITE = 1;
const int QUEUE_SIZE = 16;

const char *KERNEL_MACROS = "-D QUEUE_SIZE=16 -D COMPLETE=-1 -D READ=0 -D WRITE=1";
const char *KERNEL_FILE = "kernels/vm.cl";

int main() {
  std::vector<cl::Platform> platforms;
  std::vector<cl::Device> devices;
  cl::Device device;
  cl::Program program;

  DeviceInfo dInfo;

  try {
    /* Create a vector of available platforms. */
    cl::Platform::get(&platforms);

    /* Create a vector of available devices (GPU Priority). */
    try {
      platforms[0].getDevices(CL_DEVICE_TYPE_GPU, &devices);
    } catch (cl::Error error) {
      platforms[0].getDevices(CL_DEVICE_TYPE_DEFAULT, &devices);
    }

    /* Create a platform context for the available devices. */
    cl::Context context(devices);

    /* Use the first available device. */
    device = devices[0];

    /* Get the number of compute units for the device. */
    int computeUnits = dInfo.max_compute_units(device);

    /* Calculate the number of queues we need. */
    int nQueues = computeUnits * computeUnits;

    /* Create a command queue for the device. */
    cl::CommandQueue commandQueue = cl::CommandQueue(context, device);

    /* Read the kernel program source. */
    std::ifstream kernelSourceFile(KERNEL_FILE);
    std::string kernelSource(std::istreambuf_iterator<char>(kernelSourceFile), (std::istreambuf_iterator<char>()));
    cl::Program::Sources source(1, std::make_pair(kernelSource.c_str(), kernelSource.length() + 1));

    /* Create a program in the context using the kernel source code. */
    program = cl::Program(context, source);

    /* Build the program for the available devices. */
    program.build(devices, KERNEL_MACROS);

    /* Create the qtest kernel. */
    cl::Kernel kernel(program, "vm");

    /* Allocate memory for the queues. */
    cl_uint2 *queues = new cl_uint2[(nQueues * QUEUE_SIZE) + nQueues];
    cl_uint2 *readQueues = new cl_uint2[(nQueues * QUEUE_SIZE) + nQueues];

    /* Initialise queue elements to zero. */
    for (int i = 0; i < (nQueues * QUEUE_SIZE) + nQueues; i++) {
      queues[i].x = 0;
      queues[i].y = 0;
      readQueues[i].x = 0;
      readQueues[i].y = 0;
    }

    int *state = new int;
    *state = WRITE;

    /* Create memory buffers on the device. */
    cl::Buffer qBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, ((nQueues * QUEUE_SIZE) + nQueues) * sizeof(cl_uint2));
    commandQueue.enqueueWriteBuffer(qBuffer, CL_TRUE, 0, ((nQueues * QUEUE_SIZE) + nQueues) * sizeof(cl_uint2), queues);

    cl::Buffer rqBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, ((nQueues * QUEUE_SIZE) + nQueues) * sizeof(cl_uint2));
    commandQueue.enqueueWriteBuffer(rqBuffer, CL_TRUE, 0, ((nQueues * QUEUE_SIZE) + nQueues) * sizeof(cl_uint2), readQueues);

    cl::Buffer stateBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, sizeof(int));
    commandQueue.enqueueWriteBuffer(stateBuffer, CL_TRUE, 0, sizeof(int), state);

    /* Set kernel arguments. */
    kernel.setArg(0, qBuffer);
    kernel.setArg(1, rqBuffer);
    kernel.setArg(2, computeUnits);
    kernel.setArg(3, stateBuffer);

    /* Set the NDRange. */
    cl::NDRange global(computeUnits), local(1);

    /* Run the kernel on NDRange until completion. */
    while (*state != COMPLETE) {
      commandQueue.enqueueNDRangeKernel(kernel, cl::NullRange, global, local);
      commandQueue.finish();
      commandQueue.enqueueReadBuffer(stateBuffer, CL_TRUE, 0, sizeof(int), state);
    }

    /* Read the modified queue buffer. */
    commandQueue.enqueueReadBuffer(qBuffer, CL_TRUE, 0, ((nQueues * QUEUE_SIZE) + nQueues) * sizeof(cl_uint2), queues);

    for (int i = 0; i < nQueues; i++) {
      std::cout << "(" << queues[i].x << " " << queues[i].y << ")" << " ";
    }
    std::cout << std::endl;
    std::cout << std::endl;

    /* Print the queues. */
    for (int i = nQueues; i < (nQueues * QUEUE_SIZE) + nQueues; i++) {
      if ((i % QUEUE_SIZE) == 0) std::cout << std::endl;
      std::cout << "(" << queues[i].x << " " << queues[i].y << ")" << " ";
    }
    std::cout << std::endl;

    /* Cleanup */
    delete[] queues;
  } catch (cl::Error error) {
    std::cout << "EXCEPTION: " << error.what() << " [" << error.err() << "]" << std::endl;
    std::cout << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device) << std::endl;
  }

  return 0;
}
<commit_msg>Changed some variable names and cleaned up.<commit_after>#define __CL_ENABLE_EXCEPTIONS

#include <CL/cl.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "DeviceInfo.h"

const int QUEUE_SIZE = 16;
const int COMPLETE = -1;
const int READ = 0;
const int WRITE = 1;

const char *KERNEL_MACROS = "-D QUEUE_SIZE=16 -D COMPLETE=-1 -D READ=0 -D WRITE=1";
const char *KERNEL_FILE = "kernels/vm.cl";

int main() {
  std::vector<cl::Platform> platforms;
  std::vector<cl::Device> devices;
  cl::Device device;
  cl::Program program;

  DeviceInfo dInfo;

  try {
    /* Create a vector of available platforms. */
    cl::Platform::get(&platforms);

    /* Create a vector of available devices (GPU Priority). */
    try {
      platforms[0].getDevices(CL_DEVICE_TYPE_GPU, &devices);
    } catch (cl::Error error) {
      platforms[0].getDevices(CL_DEVICE_TYPE_DEFAULT, &devices);
    }

    /* Create a platform context for the available devices. */
    cl::Context context(devices);

    /* Use the first available device. */
    device = devices[0];

    /* Get the number of compute units for the device. */
    int computeUnits = dInfo.max_compute_units(device);

    /* Calculate the number of queues we need. */
    int nQueues = computeUnits * computeUnits;

    /* Create a command queue for the device. */
    cl::CommandQueue commandQueue = cl::CommandQueue(context, device);

    /* Read the kernel program source. */
    std::ifstream kernelSourceFile(KERNEL_FILE);
    std::string kernelSource(std::istreambuf_iterator<char>(kernelSourceFile), (std::istreambuf_iterator<char>()));
    cl::Program::Sources source(1, std::make_pair(kernelSource.c_str(), kernelSource.length() + 1));

    /* Create a program in the context using the kernel source code. */
    program = cl::Program(context, source);

    /* Build the program for the available devices. */
    program.build(devices, KERNEL_MACROS);

    /* Create the qtest kernel. */
    cl::Kernel kernel(program, "vm");

    /* Calculate the memory required to store the queues. */
    int qBufSize = (nQueues * QUEUE_SIZE) + nQueues;

    /* Allocate memory for the queues. */
    cl_uint2 *queues = new cl_uint2[qBufSize];
    cl_uint2 *readQueues = new cl_uint2[qBufSize];

    /* Initialise queue elements to zero. */
    for (int i = 0; i < qBufSize; i++) {
      queues[i].x = 0;
      queues[i].y = 0;
      readQueues[i].x = 0;
      readQueues[i].y = 0;
    }

    int *state = new int;
    *state = WRITE;

    /* Create memory buffers on the device. */
    cl::Buffer qBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, qBufSize * sizeof(cl_uint2));
    commandQueue.enqueueWriteBuffer(qBuffer, CL_TRUE, 0, qBufSize * sizeof(cl_uint2), queues);

    cl::Buffer rqBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, qBufSize * sizeof(cl_uint2));
    commandQueue.enqueueWriteBuffer(rqBuffer, CL_TRUE, 0, qBufSize * sizeof(cl_uint2), readQueues);

    cl::Buffer stateBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, sizeof(int));
    commandQueue.enqueueWriteBuffer(stateBuffer, CL_TRUE, 0, sizeof(int), state);

    /* Set kernel arguments. */
    kernel.setArg(0, qBuffer);
    kernel.setArg(1, rqBuffer);
    kernel.setArg(2, computeUnits);
    kernel.setArg(3, stateBuffer);

    /* Set the NDRange. */
    cl::NDRange global(computeUnits), local(1);

    /* Run the kernel on NDRange until completion. */
    while (*state != COMPLETE) {
      commandQueue.enqueueNDRangeKernel(kernel, cl::NullRange, global, local);
      commandQueue.finish();
      commandQueue.enqueueReadBuffer(stateBuffer, CL_TRUE, 0, sizeof(int), state);
    }

    /* Read the modified queue buffer. */
    commandQueue.enqueueReadBuffer(qBuffer, CL_TRUE, 0, qBufSize * sizeof(cl_uint2), queues);

    /* Print the queue details. */
    for (int i = 0; i < nQueues; i++) {
      std::cout << "(" << queues[i].x << " " << queues[i].y << ")" << " ";
    }
    std::cout << std::endl;
    std::cout << std::endl;

    /* Print the queues. */
    for (int i = nQueues; i < qBufSize; i++) {
      if ((i % QUEUE_SIZE) == 0) std::cout << std::endl;
      std::cout << "(" << queues[i].x << " " << queues[i].y << ")" << " ";
    }
    std::cout << std::endl;

    /* Cleanup */
    delete[] queues;
  } catch (cl::Error error) {
    std::cout << "EXCEPTION: " << error.what() << " [" << error.err() << "]" << std::endl;
    std::cout << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device) << std::endl;
  }

  return 0;
}
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// manager.cpp
//
// Identification: src/backend/catalog/manager.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <cassert>

#include "backend/catalog/manager.h"
#include "backend/storage/database.h"
#include "backend/storage/data_table.h"

namespace peloton {
namespace catalog {

Manager &Manager::GetInstance() {
  static Manager manager;
  return manager;
}

//===--------------------------------------------------------------------===//
// OBJECT MAP
//===--------------------------------------------------------------------===//

void Manager::SetTileGroup(const oid_t oid, storage::TileGroup *location) {
  {
    std::lock_guard<std::mutex> lock(locator_mutex);
    locator.insert(std::pair<oid_t, storage::TileGroup *>(oid, location));
  }
}

storage::TileGroup *Manager::GetTileGroup(const oid_t oid) {
  storage::TileGroup *location = nullptr;

  {
    std::lock_guard<std::mutex> lock(locator_mutex);
    location = locator.at(oid);
  }

  return location;
}

//used for logging test
void Manager::ClearTileGroup(){
  {
    std::lock_guard<std::mutex> lock(locator_mutex);
    locator.clear();
  }
}

//===--------------------------------------------------------------------===//
// DATABASE
//===--------------------------------------------------------------------===//

void Manager::AddDatabase(storage::Database *database) {
  {
    std::lock_guard<std::mutex> lock(catalog_mutex);
    databases.push_back(database);
  }
}

storage::Database *Manager::GetDatabaseWithOid(const oid_t database_oid) const {
  for (auto database : databases)
    if (database->GetOid() == database_oid) return database;

  return nullptr;
}

void Manager::DropDatabaseWithOid(const oid_t database_oid) {
  {
    std::lock_guard<std::mutex> lock(catalog_mutex);

    oid_t database_offset = 0;
    for (auto database : databases) {
      if (database->GetOid() == database_oid) {
        delete database;
        break;
      }
      database_offset++;
    }
    assert(database_offset < databases.size());

    // Drop the database
    databases.erase(databases.begin() + database_offset);
  }
}

storage::Database *Manager::GetDatabase(const oid_t database_offset) const {
  assert(database_offset < databases.size());
  auto database = databases.at(database_offset);
  return database;
}

oid_t Manager::GetDatabaseCount() const { return databases.size(); }

//===--------------------------------------------------------------------===//
// CONVENIENCE WRAPPERS
//===--------------------------------------------------------------------===//

storage::DataTable *Manager::GetTableWithOid(const oid_t database_oid,
                                             const oid_t table_oid) const {
  // Lookup DB
  auto database = GetDatabaseWithOid(database_oid);

  // Lookup table
  if (database != nullptr) {
    auto table = database->GetTableWithOid(table_oid);
    return table;
  }

  return nullptr;
}

storage::DataTable *Manager::GetTableWithName(
    const oid_t database_oid, const std::string table_name) const {
  // Lookup DB
  auto database = GetDatabaseWithOid(database_oid);

  // Lookup table
  if (database != nullptr) {
    auto table = database->GetTableWithName(table_name);
    return table;
  }

  return nullptr;
}

index::Index *Manager::GetIndexWithOid(const oid_t database_oid,
                                       const oid_t table_oid,
                                       const oid_t index_oid) const {
  // Lookup table
  auto table = GetTableWithOid(database_oid, table_oid);

  // Lookup index
  if (table != nullptr) {
    auto index = table->GetIndexWithOid(index_oid);
    return index;
  }

  return nullptr;
}

}  // End catalog namespace
}  // End peloton namespace
<commit_msg>Fix GetTileGroup bug<commit_after>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// manager.cpp
//
// Identification: src/backend/catalog/manager.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <cassert>

#include "backend/catalog/manager.h"
#include "backend/storage/database.h"
#include "backend/storage/data_table.h"

namespace peloton {
namespace catalog {

Manager &Manager::GetInstance() {
  static Manager manager;
  return manager;
}

//===--------------------------------------------------------------------===//
// OBJECT MAP
//===--------------------------------------------------------------------===//

void Manager::SetTileGroup(const oid_t oid, storage::TileGroup *location) {
  {
    std::lock_guard<std::mutex> lock(locator_mutex);
    locator.insert(std::pair<oid_t, storage::TileGroup *>(oid, location));
  }
}

storage::TileGroup *Manager::GetTileGroup(const oid_t oid) {
  storage::TileGroup *location = nullptr;

  {
    std::lock_guard<std::mutex> lock(locator_mutex);
    if (locator.find(oid) != locator.end())
      location = locator.at(oid);
  }

  return location;
}

//used for logging test
void Manager::ClearTileGroup(){
  {
    std::lock_guard<std::mutex> lock(locator_mutex);
    locator.clear();
  }
}

//===--------------------------------------------------------------------===//
// DATABASE
//===--------------------------------------------------------------------===//

void Manager::AddDatabase(storage::Database *database) {
  {
    std::lock_guard<std::mutex> lock(catalog_mutex);
    databases.push_back(database);
  }
}

storage::Database *Manager::GetDatabaseWithOid(const oid_t database_oid) const {
  for (auto database : databases)
    if (database->GetOid() == database_oid) return database;

  return nullptr;
}

void Manager::DropDatabaseWithOid(const oid_t database_oid) {
  {
    std::lock_guard<std::mutex> lock(catalog_mutex);

    oid_t database_offset = 0;
    for (auto database : databases) {
      if (database->GetOid() == database_oid) {
        delete database;
        break;
      }
      database_offset++;
    }
    assert(database_offset < databases.size());

    // Drop the database
    databases.erase(databases.begin() + database_offset);
  }
}

storage::Database *Manager::GetDatabase(const oid_t database_offset) const {
  assert(database_offset < databases.size());
  auto database = databases.at(database_offset);
  return database;
}

oid_t Manager::GetDatabaseCount() const { return databases.size(); }

//===--------------------------------------------------------------------===//
// CONVENIENCE WRAPPERS
//===--------------------------------------------------------------------===//

storage::DataTable *Manager::GetTableWithOid(const oid_t database_oid,
                                             const oid_t table_oid) const {
  // Lookup DB
  auto database = GetDatabaseWithOid(database_oid);

  // Lookup table
  if (database != nullptr) {
    auto table = database->GetTableWithOid(table_oid);
    return table;
  }

  return nullptr;
}

storage::DataTable *Manager::GetTableWithName(
    const oid_t database_oid, const std::string table_name) const {
  // Lookup DB
  auto database = GetDatabaseWithOid(database_oid);

  // Lookup table
  if (database != nullptr) {
    auto table = database->GetTableWithName(table_name);
    return table;
  }

  return nullptr;
}

index::Index *Manager::GetIndexWithOid(const oid_t database_oid,
                                       const oid_t table_oid,
                                       const oid_t index_oid) const {
  // Lookup table
  auto table = GetTableWithOid(database_oid, table_oid);

  // Lookup index
  if (table != nullptr) {
    auto index = table->GetIndexWithOid(index_oid);
    return index;
  }

  return nullptr;
}

}  // End catalog namespace
}  // End peloton namespace
<|endoftext|>


<commit_before>//
// Realm C++ coding standard - by example
//

// Lines should never exceed 118 characters --------------------------------------------------------------------------

// Macro names use uppercase and have "REALM_" as prefix. Non-macro
// names never use all uppercase.

#define REALM_MY_MACRO 1

// A function name uses lowercase and its parts are separated by
// underscores.

my_type my_func()
{
    // Put the opening brace of a function body in the next line below
    // the function prototype. This also applies to class member
    // functions.

    // Put all other opening braces on the same line as the syntax
    // element to which the brace is subordinate.

    // Use 4 spaces per indentation level (no tabs please).

    if (...) {
        // ...
    }
    else {
        // ...
    }

    // Always put subordinate statements on a new line (to ease
    // debugging).

    if (...)
        return ...;

    // No space between type and '*' or '&'
    int* foo1 = ...;
    int& foo2 = ...;

    // 'const' goes before the type
    const int foo3 = ...;

    // ... but not when 'const' operates on a pointer type
    const int* foo3 = ...; // 'const' operates on 'int' not 'int*'
    int* const foo4 = ...; // 'const' operates on 'int*'
    int* const* const foo5 = ...;
}

void my_func_2()
{
    // This indentation and brace placement style agrees with K&R
    // style except for the 'extra' indentation of 'cases' in a switch
    // statement.

    switch (...) {
        case type_Foo: {
            // ...
            break;
        }
        case type_FooBar: {
            // ...
            break;
        }
    }

    try {
        // ...
    }
    catch (...) {
        // ...
    }
}

// A name space name uses lowercase and its parts are separated by
// underscores.

namespace my_namespace {

// No indentation inside name spaces.

// A Class name uses CamelCase with uppercase initial.

template<class T>
class MyClass: public Base {
public:
    MyClass(...):
        Base(...),
        m_bar(7),
        ...
    {
        // ...
    }

private:
    // Static member variables have prefix 's_'.
    static int s_foo;

    // Regular member variables have prefix 'm_'.
    int m_bar;
};

} // namespace my_namespace

// Names of values of an enumeration are composed of two parts
// separated by an underscore. The first part is a common lowercase
// prefix. The second part identifies the value and uses CamelCase
// with uppercase initial.

enum mode {
    mode_Foo,
    mode_FooBar
};

// Order of class members (roughly):

class MyClass2 {
public:
    // Types

    // Static variables
    // Regular variables

    // Static functions
    // Regular functions

protected:
    // Same as 'public'

private:
    // Same as 'public'

    // Friends
};

// About FIXMEs:
//
// A FIXME conveys information about a known issue or shortcoming. It
// may also include information on how to fix the problem, and on
// possible conflicts with anticipated future features.
//
// A FIXME is often added in the following situations:
//
// - While working on, or studying a particular part of the code you
//   uncover an issue or a shortcoming. Additionally, you may have
//   gained an understanding of how to fix it.
//
// - While implementing a new feature, you are forced to cut a corner,
//   but you have some good ideas about how to continue later, and/or
//   you may have knowledge about a certain planned feature that would
//   require a more complete solution.
//
// A FIXME is generally not about a bug or an error, and is should
// generally not be considered a task either. Is is simply a memo to
// oneself or to some other developer who is going to work on the code
// at some later point in time.
//
// A FIXME should never be deleted unless by somebody who understands
// the mening of it and knows that the problem is fixed, or has
// otherwise diappeard.
<commit_msg>code guidelines<commit_after>//
// Realm C++ coding standard - by example
//

// Lines should never exceed 118 characters --------------------------------------------------------------------------

// Macro names use uppercase and have "REALM_" as prefix. Non-macro
// names never use all uppercase.

#define REALM_MY_MACRO 1

// A function name uses lowercase and its parts are separated by
// underscores.

my_type my_func()
{
    // Put the opening brace of a function body in the next line below
    // the function prototype. This also applies to class member
    // functions.

    // Put all other opening braces on the same line as the syntax
    // element to which the brace is subordinate.

    // Use 4 spaces per indentation level (no tabs please).

    if (...) {
        // ...
    }
    else {
        // ...
    }

    // Always put subordinate statements on a new line (to ease
    // debugging).

    if (...)
        return ...;

    // No space between type and '*' or '&'
    int* foo1 = ...;
    int& foo2 = ...;

    // 'const' goes before the type
    const int foo3 = ...;

    // ... but not when 'const' operates on a pointer type
    const int* foo3 = ...; // 'const' operates on 'int' not 'int*'
    int* const foo4 = ...; // 'const' operates on 'int*'
    int* const* const foo5 = ...;
}

void my_func_2()
{
    // This indentation and brace placement style agrees with K&R
    // style except for the 'extra' indentation of 'cases' in a switch
    // statement.

    switch (...) {
        case type_Foo: {
            // ...
            break;
        }
        case type_FooBar: {
            // ...
            break;
        }
    }

    try {
        // ...
    }
    catch (...) {
        // ...
    }
}

// A name space name uses lowercase and its parts are separated by
// underscores.

namespace my_namespace {

// No indentation inside name spaces.

// A Class name uses CamelCase with uppercase initial.

template<class T>
class MyClass: public Base {
public:
    MyClass(...):
        Base(...),
        m_bar(7),
        ...
    {
        // ...
    }

private:
    // Static member variables have prefix 's_'.
    static int s_foo;

    // Regular member variables have prefix 'm_'.
    int m_bar;
};

} // namespace my_namespace

// Names of values of an enumeration are composed of two parts
// separated by an underscore. The first part is a common lowercase
// prefix. The second part identifies the value and uses CamelCase
// with uppercase initial.

enum mode {
    mode_Foo,
    mode_FooBar
};

// Order of class members (roughly):

class MyClass2 {
public:
    // Types

    // Static variables
    // Regular variables

    // Static functions
    // Regular functions

protected:
    // Same as 'public'

private:
    // Same as 'public'

    // Friends
};

// Use of 'auto' keyword:
//
// 'auto' should *not* be used for trivial cases where the type declaration
// is short, non-templated, and non-derived (type_t, int64_t, std::string,
// etc.

// About FIXMEs:
//
// A FIXME conveys information about a known issue or shortcoming. It
// may also include information on how to fix the problem, and on
// possible conflicts with anticipated future features.
//
// A FIXME is often added in the following situations:
//
// - While working on, or studying a particular part of the code you
//   uncover an issue or a shortcoming. Additionally, you may have
//   gained an understanding of how to fix it.
//
// - While implementing a new feature, you are forced to cut a corner,
//   but you have some good ideas about how to continue later, and/or
//   you may have knowledge about a certain planned feature that would
//   require a more complete solution.
//
// A FIXME is generally not about a bug or an error, and is should
// generally not be considered a task either. Is is simply a memo to
// oneself or to some other developer who is going to work on the code
// at some later point in time.
//
// A FIXME should never be deleted unless by somebody who understands
// the mening of it and knows that the problem is fixed, or has
// otherwise diappeard.
<|endoftext|>