<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: conditio.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 17:28:47 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SC_CONDITIO_HXX
#define SC_CONDITIO_HXX

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

#ifndef _SVARRAY_HXX //autogen
#include <svtools/svarray.hxx>
#endif

class ScBaseCell;
class ScFormulaCell;
class ScTokenArray;
class ScMultipleReadHeader;
class ScMultipleWriteHeader;
class ScRangeList;

#define SC_COND_GROW 16

//  nOptions Flags
#define SC_COND_NOBLANKS    1

            // Reihenfolge von ScConditionMode wie ScQueryOp,
            // damit einmal zusammengefasst werden kann:

enum ScConditionMode
{
    SC_COND_EQUAL,
    SC_COND_LESS,
    SC_COND_GREATER,
    SC_COND_EQLESS,
    SC_COND_EQGREATER,
    SC_COND_NOTEQUAL,
    SC_COND_BETWEEN,
    SC_COND_NOTBETWEEN,
    SC_COND_DIRECT,
    SC_COND_NONE
};

enum ScConditionValType
{
    SC_VAL_VALUE,
    SC_VAL_STRING,
    SC_VAL_FORMULA
};

class ScConditionEntry
{
                                        // gespeicherte Daten:
    ScConditionMode     eOp;
    USHORT              nOptions;
    double              nVal1;          // eingegeben oder berechnet
    double              nVal2;
    String              aStrVal1;       // eingegeben oder berechnet
    String              aStrVal2;
    BOOL                bIsStr1;        // um auch leere Strings zu erkennen
    BOOL                bIsStr2;
    ScTokenArray*       pFormula1;      // eingegebene Formel
    ScTokenArray*       pFormula2;
    ScAddress           aSrcPos;        // source position for formulas
                                        // temporary data:
    String              aSrcString;     // formula source position as text during XML import
    ScFormulaCell*      pFCell1;
    ScFormulaCell*      pFCell2;
    ScDocument*         pDoc;
    BOOL                bRelRef1;
    BOOL                bRelRef2;
    BOOL                bFirstRun;

    void    MakeCells( const ScAddress& rPos );
    void    Compile( const String& rExpr1, const String& rExpr2, BOOL bEnglish,
                        BOOL bCompileXML, BOOL bTextToReal );
    void    Interpret( const ScAddress& rPos );

    BOOL    IsValid( double nArg ) const;
    BOOL    IsValidStr( const String& rArg ) const;

protected:
            ScConditionEntry( SvStream& rStream, ScMultipleReadHeader& rHdr,
                                ScDocument* pDocument );
    void    StoreCondition(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;

public:
            ScConditionEntry( ScConditionMode eOper,
                                const String& rExpr1, const String& rExpr2,
                                ScDocument* pDocument, const ScAddress& rPos,
                                BOOL bCompileEnglish, BOOL bCompileXML );
            ScConditionEntry( ScConditionMode eOper,
                                const ScTokenArray* pArr1, const ScTokenArray* pArr2,
                                ScDocument* pDocument, const ScAddress& rPos );
            ScConditionEntry( const ScConditionEntry& r );  // flache Kopie der Formeln
            // echte Kopie der Formeln (fuer Ref-Undo):
            ScConditionEntry( ScDocument* pDocument, const ScConditionEntry& r );
    virtual ~ScConditionEntry();

    int             operator== ( const ScConditionEntry& r ) const;

    BOOL            IsCellValid( ScBaseCell* pCell, const ScAddress& rPos ) const;

    ScConditionMode GetOperation() const        { return eOp; }
    BOOL            IsIgnoreBlank() const       { return ( nOptions & SC_COND_NOBLANKS ) == 0; }
    void            SetIgnoreBlank(BOOL bSet);
    ScAddress       GetSrcPos() const           { return aSrcPos; }

    ScAddress       GetValidSrcPos() const;     // adjusted to allow textual representation of expressions

    void            SetSrcString( const String& rNew );     // for XML import

    String          GetExpression( const ScAddress& rCursor, USHORT nPos, ULONG nNumFmt = 0,
                                    BOOL bEnglish = FALSE, BOOL bCompileXML = FALSE,
                                    BOOL bTextToReal = FALSE ) const;

    ScTokenArray*   CreateTokenArry( USHORT nPos ) const;

    void            CompileAll();
    void            CompileXML();
    void            UpdateReference( UpdateRefMode eUpdateRefMode,
                                const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
    void            UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );

    void            SourceChanged( const ScAddress& rChanged );

protected:
    virtual void    DataChanged( const ScRange* pModified ) const;
    ScDocument*     GetDocument() const     { return pDoc; }
};

//
//  einzelner Eintrag fuer bedingte Formatierung
//

class ScConditionalFormat;

class ScCondFormatEntry : public ScConditionEntry
{
    String                  aStyleName;
    ScConditionalFormat*    pParent;

public:
            ScCondFormatEntry( ScConditionMode eOper,
                                const String& rExpr1, const String& rExpr2,
                                ScDocument* pDocument, const ScAddress& rPos,
                                const String& rStyle,
                                BOOL bCompileEnglish = FALSE, BOOL bCompileXML = FALSE );
            ScCondFormatEntry( ScConditionMode eOper,
                                const ScTokenArray* pArr1, const ScTokenArray* pArr2,
                                ScDocument* pDocument, const ScAddress& rPos,
                                const String& rStyle );
            ScCondFormatEntry( const ScCondFormatEntry& r );
            ScCondFormatEntry( ScDocument* pDocument, const ScCondFormatEntry& r );
            ScCondFormatEntry( SvStream& rStream, ScMultipleReadHeader& rHdr,
                                ScDocument* pDocument );
    virtual ~ScCondFormatEntry();

    void            SetParent( ScConditionalFormat* pNew )  { pParent = pNew; }

    void            Store(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;

    int             operator== ( const ScCondFormatEntry& r ) const;

    const String&   GetStyle() const        { return aStyleName; }

protected:
    virtual void    DataChanged( const ScRange* pModified ) const;
};

//
//  komplette bedingte Formatierung
//

class ScConditionalFormat
{
    ScDocument*         pDoc;
    ScRangeList*        pAreas;             // Bereiche fuer Paint
    ULONG               nKey;               // Index in Attributen
    ScCondFormatEntry** ppEntries;
    USHORT              nEntryCount;
    BOOL                bIsUsed;            // temporaer beim Speichern

public:
            ScConditionalFormat(ULONG nNewKey, ScDocument* pDocument);
            ScConditionalFormat(const ScConditionalFormat& r);
            ScConditionalFormat(SvStream& rStream, ScMultipleReadHeader& rHdr,
                                ScDocument* pDocument);
            ~ScConditionalFormat();

    // echte Kopie der Formeln (fuer Ref-Undo / zwischen Dokumenten)
    ScConditionalFormat* Clone(ScDocument* pNewDoc = NULL) const;

    void            Store(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;

    void            AddEntry( const ScCondFormatEntry& rNew );

    BOOL            IsEmpty() const         { return (nEntryCount == 0); }
    USHORT          Count() const           { return nEntryCount; }

    void            CompileAll();
    void            CompileXML();
    void            UpdateReference( UpdateRefMode eUpdateRefMode,
                                const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
    void            UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );

    void            SourceChanged( const ScAddress& rAddr );

    const ScCondFormatEntry* GetEntry( USHORT nPos ) const;

    const String&   GetCellStyle( ScBaseCell* pCell, const ScAddress& rPos ) const;

    BOOL            EqualEntries( const ScConditionalFormat& r ) const;

    void            DoRepaint( const ScRange* pModified );
    void            InvalidateArea();

    ULONG           GetKey() const          { return nKey; }
    void            SetKey(ULONG nNew)      { nKey = nNew; }    // nur wenn nicht eingefuegt!

    void            SetUsed(BOOL bSet)      { bIsUsed = bSet; }
    BOOL            IsUsed() const          { return bIsUsed; }

    //  sortiert (per PTRARR) nach Index
    //  operator== nur fuer die Sortierung
    BOOL operator ==( const ScConditionalFormat& r ) const  { return nKey == r.nKey; }
    BOOL operator < ( const ScConditionalFormat& r ) const  { return nKey <  r.nKey; }
};

//
//  Liste der Bereiche und Formate:
//

typedef ScConditionalFormat* ScConditionalFormatPtr;

SV_DECL_PTRARR_SORT(ScConditionalFormats_Impl, ScConditionalFormatPtr,
                        SC_COND_GROW, SC_COND_GROW);

class ScConditionalFormatList : public ScConditionalFormats_Impl
{
public:
        ScConditionalFormatList() {}
        ScConditionalFormatList(const ScConditionalFormatList& rList);
        ScConditionalFormatList(ScDocument* pNewDoc, const ScConditionalFormatList& rList);
        ~ScConditionalFormatList() {}

    void    InsertNew( ScConditionalFormat* pNew )
                { if (!Insert(pNew)) delete pNew; }

    ScConditionalFormat* GetFormat( ULONG nKey );

    void    Load( SvStream& rStream, ScDocument* pDocument );
    void    Store( SvStream& rStream ) const;
    void    ResetUsed();

    void    CompileAll();
    void    CompileXML();
    void    UpdateReference( UpdateRefMode eUpdateRefMode,
                                const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
    void    UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );

    void    SourceChanged( const ScAddress& rAddr );

    BOOL    operator==( const ScConditionalFormatList& r ) const;       // fuer Ref-Undo
};

#endif

<commit_msg>INTEGRATION: CWS sixtyfour04 (1.8.142); FILE MERGED 2006/03/15 16:14:03 cmc 1.8.142.1: #i63168# make sc 64bit happy<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: conditio.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: vg $ $Date: 2006-04-07 08:24:31 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SC_CONDITIO_HXX
#define SC_CONDITIO_HXX

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

#ifndef _SVARRAY_HXX //autogen
#include <svtools/svarray.hxx>
#endif

class ScBaseCell;
class ScFormulaCell;
class ScTokenArray;
class ScMultipleReadHeader;
class ScMultipleWriteHeader;
class ScRangeList;

#define SC_COND_GROW 16

//  nOptions Flags
#define SC_COND_NOBLANKS    1

            // Reihenfolge von ScConditionMode wie ScQueryOp,
            // damit einmal zusammengefasst werden kann:

enum ScConditionMode
{
    SC_COND_EQUAL,
    SC_COND_LESS,
    SC_COND_GREATER,
    SC_COND_EQLESS,
    SC_COND_EQGREATER,
    SC_COND_NOTEQUAL,
    SC_COND_BETWEEN,
    SC_COND_NOTBETWEEN,
    SC_COND_DIRECT,
    SC_COND_NONE
};

enum ScConditionValType
{
    SC_VAL_VALUE,
    SC_VAL_STRING,
    SC_VAL_FORMULA
};

class ScConditionEntry
{
                                        // gespeicherte Daten:
    ScConditionMode     eOp;
    USHORT              nOptions;
    double              nVal1;          // eingegeben oder berechnet
    double              nVal2;
    String              aStrVal1;       // eingegeben oder berechnet
    String              aStrVal2;
    BOOL                bIsStr1;        // um auch leere Strings zu erkennen
    BOOL                bIsStr2;
    ScTokenArray*       pFormula1;      // eingegebene Formel
    ScTokenArray*       pFormula2;
    ScAddress           aSrcPos;        // source position for formulas
                                        // temporary data:
    String              aSrcString;     // formula source position as text during XML import
    ScFormulaCell*      pFCell1;
    ScFormulaCell*      pFCell2;
    ScDocument*         pDoc;
    BOOL                bRelRef1;
    BOOL                bRelRef2;
    BOOL                bFirstRun;

    void    MakeCells( const ScAddress& rPos );
    void    Compile( const String& rExpr1, const String& rExpr2, BOOL bEnglish,
                        BOOL bCompileXML, BOOL bTextToReal );
    void    Interpret( const ScAddress& rPos );

    BOOL    IsValid( double nArg ) const;
    BOOL    IsValidStr( const String& rArg ) const;

protected:
            ScConditionEntry( SvStream& rStream, ScMultipleReadHeader& rHdr,
                                ScDocument* pDocument );
    void    StoreCondition(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;

public:
            ScConditionEntry( ScConditionMode eOper,
                                const String& rExpr1, const String& rExpr2,
                                ScDocument* pDocument, const ScAddress& rPos,
                                BOOL bCompileEnglish, BOOL bCompileXML );
            ScConditionEntry( ScConditionMode eOper,
                                const ScTokenArray* pArr1, const ScTokenArray* pArr2,
                                ScDocument* pDocument, const ScAddress& rPos );
            ScConditionEntry( const ScConditionEntry& r );  // flache Kopie der Formeln
            // echte Kopie der Formeln (fuer Ref-Undo):
            ScConditionEntry( ScDocument* pDocument, const ScConditionEntry& r );
    virtual ~ScConditionEntry();

    int             operator== ( const ScConditionEntry& r ) const;

    BOOL            IsCellValid( ScBaseCell* pCell, const ScAddress& rPos ) const;

    ScConditionMode GetOperation() const        { return eOp; }
    BOOL            IsIgnoreBlank() const       { return ( nOptions & SC_COND_NOBLANKS ) == 0; }
    void            SetIgnoreBlank(BOOL bSet);
    ScAddress       GetSrcPos() const           { return aSrcPos; }

    ScAddress       GetValidSrcPos() const;     // adjusted to allow textual representation of expressions

    void            SetSrcString( const String& rNew );     // for XML import

    String          GetExpression( const ScAddress& rCursor, USHORT nPos, ULONG nNumFmt = 0,
                                    BOOL bEnglish = FALSE, BOOL bCompileXML = FALSE,
                                    BOOL bTextToReal = FALSE ) const;

    ScTokenArray*   CreateTokenArry( USHORT nPos ) const;

    void            CompileAll();
    void            CompileXML();
    void            UpdateReference( UpdateRefMode eUpdateRefMode,
                                const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
    void            UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );

    void            SourceChanged( const ScAddress& rChanged );

protected:
    virtual void    DataChanged( const ScRange* pModified ) const;
    ScDocument*     GetDocument() const     { return pDoc; }
};

//
//  einzelner Eintrag fuer bedingte Formatierung
//

class ScConditionalFormat;

class ScCondFormatEntry : public ScConditionEntry
{
    String                  aStyleName;
    ScConditionalFormat*    pParent;

public:
            ScCondFormatEntry( ScConditionMode eOper,
                                const String& rExpr1, const String& rExpr2,
                                ScDocument* pDocument, const ScAddress& rPos,
                                const String& rStyle,
                                BOOL bCompileEnglish = FALSE, BOOL bCompileXML = FALSE );
            ScCondFormatEntry( ScConditionMode eOper,
                                const ScTokenArray* pArr1, const ScTokenArray* pArr2,
                                ScDocument* pDocument, const ScAddress& rPos,
                                const String& rStyle );
            ScCondFormatEntry( const ScCondFormatEntry& r );
            ScCondFormatEntry( ScDocument* pDocument, const ScCondFormatEntry& r );
            ScCondFormatEntry( SvStream& rStream, ScMultipleReadHeader& rHdr,
                                ScDocument* pDocument );
    virtual ~ScCondFormatEntry();

    void            SetParent( ScConditionalFormat* pNew )  { pParent = pNew; }

    void            Store(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;

    int             operator== ( const ScCondFormatEntry& r ) const;

    const String&   GetStyle() const        { return aStyleName; }

protected:
    virtual void    DataChanged( const ScRange* pModified ) const;
};

//
//  komplette bedingte Formatierung
//

class ScConditionalFormat
{
    ScDocument*         pDoc;
    ScRangeList*        pAreas;             // Bereiche fuer Paint
    sal_uInt32          nKey;               // Index in Attributen
    ScCondFormatEntry** ppEntries;
    USHORT              nEntryCount;
    BOOL                bIsUsed;            // temporaer beim Speichern

public:
            ScConditionalFormat(sal_uInt32 nNewKey, ScDocument* pDocument);
            ScConditionalFormat(const ScConditionalFormat& r);
            ScConditionalFormat(SvStream& rStream, ScMultipleReadHeader& rHdr,
                                ScDocument* pDocument);
            ~ScConditionalFormat();

    // echte Kopie der Formeln (fuer Ref-Undo / zwischen Dokumenten)
    ScConditionalFormat* Clone(ScDocument* pNewDoc = NULL) const;

    void            Store(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;

    void            AddEntry( const ScCondFormatEntry& rNew );

    BOOL            IsEmpty() const         { return (nEntryCount == 0); }
    USHORT          Count() const           { return nEntryCount; }

    void            CompileAll();
    void            CompileXML();
    void            UpdateReference( UpdateRefMode eUpdateRefMode,
                                const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
    void            UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );

    void            SourceChanged( const ScAddress& rAddr );

    const ScCondFormatEntry* GetEntry( USHORT nPos ) const;

    const String&   GetCellStyle( ScBaseCell* pCell, const ScAddress& rPos ) const;

    BOOL            EqualEntries( const ScConditionalFormat& r ) const;

    void            DoRepaint( const ScRange* pModified );
    void            InvalidateArea();

    sal_uInt32      GetKey() const          { return nKey; }
    void            SetKey(sal_uInt32 nNew) { nKey = nNew; }    // nur wenn nicht eingefuegt!

    void            SetUsed(BOOL bSet)      { bIsUsed = bSet; }
    BOOL            IsUsed() const          { return bIsUsed; }

    //  sortiert (per PTRARR) nach Index
    //  operator== nur fuer die Sortierung
    BOOL operator ==( const ScConditionalFormat& r ) const  { return nKey == r.nKey; }
    BOOL operator < ( const ScConditionalFormat& r ) const  { return nKey <  r.nKey; }
};

//
//  Liste der Bereiche und Formate:
//

typedef ScConditionalFormat* ScConditionalFormatPtr;

SV_DECL_PTRARR_SORT(ScConditionalFormats_Impl, ScConditionalFormatPtr,
                        SC_COND_GROW, SC_COND_GROW);

class ScConditionalFormatList : public ScConditionalFormats_Impl
{
public:
        ScConditionalFormatList() {}
        ScConditionalFormatList(const ScConditionalFormatList& rList);
        ScConditionalFormatList(ScDocument* pNewDoc, const ScConditionalFormatList& rList);
        ~ScConditionalFormatList() {}

    void    InsertNew( ScConditionalFormat* pNew )
                { if (!Insert(pNew)) delete pNew; }

    ScConditionalFormat* GetFormat( sal_uInt32 nKey );

    void    Load( SvStream& rStream, ScDocument* pDocument );
    void    Store( SvStream& rStream ) const;
    void    ResetUsed();

    void    CompileAll();
    void    CompileXML();
    void    UpdateReference( UpdateRefMode eUpdateRefMode,
                                const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
    void    UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );

    void    SourceChanged( const ScAddress& rAddr );

    BOOL    operator==( const ScConditionalFormatList& r ) const;       // fuer Ref-Undo
};

#endif

<|endoftext|>


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

#ifndef SC_NOTESUNO_HXX
#define SC_NOTESUNO_HXX

#ifndef SC_SCGLOB_HXX
#include "global.hxx"           // ScRange, ScAddress
#endif

#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif

#ifndef _COM_SUN_STAR_SHEET_XSHEETANNOTATION_HPP_
#include <com/sun/star/sheet/XSheetAnnotation.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XSIMPLETEXT_HPP_
#include <com/sun/star/text/XSimpleText.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE4_HXX_
#include <cppuhelper/implbase4.hxx>
#endif

class ScDocShell;
class SvxUnoText;

class ScAnnotationObj : public cppu::WeakImplHelper4<
                            com::sun::star::container::XChild,
                            com::sun::star::text::XSimpleText,
                            com::sun::star::sheet::XSheetAnnotation,
                            com::sun::star::lang::XServiceInfo >,
                        public SfxListener
{
private:
    ScDocShell*             pDocShell;
    ScAddress               aCellPos;
    SvxUnoText*             pUnoText;

private:
    SvxUnoText& GetUnoText();

public:
                            ScAnnotationObj(ScDocShell* pDocSh, const ScAddress& rPos);
    virtual                 ~ScAnnotationObj();

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

                            // XChild
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
                            getParent() throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL   setParent( const ::com::sun::star::uno::Reference<
                                        ::com::sun::star::uno::XInterface >& Parent )
                                    throw(::com::sun::star::lang::NoSupportException,
                                            ::com::sun::star::uno::RuntimeException);

                            // XSimpleText
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XTextCursor > SAL_CALL
                            createTextCursor() throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XTextCursor > SAL_CALL
                            createTextCursorByRange( const ::com::sun::star::uno::Reference<
                                        ::com::sun::star::text::XTextRange >& aTextPosition )
                                    throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL   insertString( const ::com::sun::star::uno::Reference<
                                        ::com::sun::star::text::XTextRange >& xRange,
                                        const ::rtl::OUString& aString, sal_Bool bAbsorb )
                                    throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL   insertControlCharacter( const ::com::sun::star::uno::Reference<
                                        ::com::sun::star::text::XTextRange >& xRange,
                                        sal_Int16 nControlCharacter, sal_Bool bAbsorb )
                                    throw(::com::sun::star::lang::IllegalArgumentException,
                                        ::com::sun::star::uno::RuntimeException);

                            // XTextRange
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XText > SAL_CALL
                            getText() throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XTextRange > SAL_CALL
                            getStart() throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XTextRange > SAL_CALL
                            getEnd() throw(::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getString() throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL   setString( const ::rtl::OUString& aString )
                                    throw(::com::sun::star::uno::RuntimeException);

                            // XSheetAnnotation
    virtual ::com::sun::star::table::CellAddress SAL_CALL getPosition()
                                    throw(::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getAuthor() throw(::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getDate() throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL getIsVisible() throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setIsVisible( sal_Bool bIsVisible )
                                    throw(::com::sun::star::uno::RuntimeException);

                            // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName()
                                throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
                                throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
                                throw(::com::sun::star::uno::RuntimeException);
};

#endif

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

#ifndef SC_NOTESUNO_HXX
#define SC_NOTESUNO_HXX

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif

#ifndef _COM_SUN_STAR_SHEET_XSHEETANNOTATION_HPP_
#include <com/sun/star/sheet/XSheetAnnotation.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XSIMPLETEXT_HPP_
#include <com/sun/star/text/XSimpleText.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE4_HXX_
#include <cppuhelper/implbase4.hxx>
#endif

class ScDocShell;
class SvxUnoText;

class ScAnnotationObj : public cppu::WeakImplHelper4<
                            com::sun::star::container::XChild,
                            com::sun::star::text::XSimpleText,
                            com::sun::star::sheet::XSheetAnnotation,
                            com::sun::star::lang::XServiceInfo >,
                        public SfxListener
{
private:
    ScDocShell*             pDocShell;
    ScAddress               aCellPos;
    SvxUnoText*             pUnoText;

private:
    SvxUnoText& GetUnoText();

public:
                            ScAnnotationObj(ScDocShell* pDocSh, const ScAddress& rPos);
    virtual                 ~ScAnnotationObj();

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

                            // XChild
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
                            getParent() throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL   setParent( const ::com::sun::star::uno::Reference<
                                        ::com::sun::star::uno::XInterface >& Parent )
                                    throw(::com::sun::star::lang::NoSupportException,
                                            ::com::sun::star::uno::RuntimeException);

                            // XSimpleText
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XTextCursor > SAL_CALL
                            createTextCursor() throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XTextCursor > SAL_CALL
                            createTextCursorByRange( const ::com::sun::star::uno::Reference<
                                        ::com::sun::star::text::XTextRange >& aTextPosition )
                                    throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL   insertString( const ::com::sun::star::uno::Reference<
                                        ::com::sun::star::text::XTextRange >& xRange,
                                        const ::rtl::OUString& aString, sal_Bool bAbsorb )
                                    throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL   insertControlCharacter( const ::com::sun::star::uno::Reference<
                                        ::com::sun::star::text::XTextRange >& xRange,
                                        sal_Int16 nControlCharacter, sal_Bool bAbsorb )
                                    throw(::com::sun::star::lang::IllegalArgumentException,
                                        ::com::sun::star::uno::RuntimeException);

                            // XTextRange
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XText > SAL_CALL
                            getText() throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XTextRange > SAL_CALL
                            getStart() throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XTextRange > SAL_CALL
                            getEnd() throw(::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getString() throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL   setString( const ::rtl::OUString& aString )
                                    throw(::com::sun::star::uno::RuntimeException);

                            // XSheetAnnotation
    virtual ::com::sun::star::table::CellAddress SAL_CALL getPosition()
                                    throw(::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getAuthor() throw(::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getDate() throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL getIsVisible() throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setIsVisible( sal_Bool bIsVisible )
                                    throw(::com::sun::star::uno::RuntimeException);

                            // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName()
                                throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
                                throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
                                throw(::com::sun::star::uno::RuntimeException);
};

#endif

<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkTestingMacros.h"
#include <mitkTestingConfig.h>
#include <mitkTestFixture.h>

#include <mitkIOUtil.h>
#include <mitkImageGenerator.h>

#include <itksys/SystemTools.hxx>

class mitkIOUtilTestSuite : public mitk::TestFixture
{

  CPPUNIT_TEST_SUITE(mitkIOUtilTestSuite);
  MITK_TEST(TestTempMethods);
  MITK_TEST(TestLoadAndSaveImage);
  MITK_TEST(TestLoadAndSavePointSet);
  MITK_TEST(TestLoadAndSaveSurface);
  CPPUNIT_TEST_SUITE_END();

private:

  std::string m_ImagePath;
  std::string m_SurfacePath;
  std::string m_PointSetPath;

public:

  void setUp()
  {
    m_ImagePath = std::string(MITK_DATA_DIR) + "/" + "Pic3D.nrrd";
    m_SurfacePath = std::string(MITK_DATA_DIR) + "/" + "binary.stl";
    m_PointSetPath = std::string(MITK_DATA_DIR) + "/" + "pointSet.mps";
  }

  void TestTempMethods()
  {
    std::string tmpPath = mitk::IOUtil::GetTempPath();
    CPPUNIT_ASSERT(!tmpPath.empty());

    std::ofstream tmpFile;
    std::string tmpFilePath = mitk::IOUtil::CreateTemporaryFile(tmpFile);
    CPPUNIT_ASSERT(tmpFile && tmpFile.is_open());
    CPPUNIT_ASSERT(tmpFilePath.size() > tmpPath.size());
    CPPUNIT_ASSERT(tmpFilePath.substr(0, tmpPath.size()) == tmpPath);

    tmpFile.close();
    CPPUNIT_ASSERT(std::remove(tmpFilePath.c_str()) == 0);

    std::string programPath = mitk::IOUtil::GetProgramPath();
    CPPUNIT_ASSERT(!programPath.empty());
    std::ofstream tmpFile2;
    std::string tmpFilePath2 = mitk::IOUtil::CreateTemporaryFile(tmpFile2, "my-XXXXXX", programPath);
    CPPUNIT_ASSERT(tmpFile2 && tmpFile2.is_open());
    CPPUNIT_ASSERT(tmpFilePath2.size() > programPath.size());
    CPPUNIT_ASSERT(tmpFilePath2.substr(0, programPath.size()) == programPath);
    tmpFile2.close();
    CPPUNIT_ASSERT(std::remove(tmpFilePath2.c_str()) == 0);

    std::ofstream tmpFile3;
    std::string tmpFilePath3 = mitk::IOUtil::CreateTemporaryFile(tmpFile3, std::ios_base::binary,
                                                                 "my-XXXXXX.TXT", programPath);
    CPPUNIT_ASSERT(tmpFile3 && tmpFile3.is_open());
    CPPUNIT_ASSERT(tmpFilePath3.size() > programPath.size());
    CPPUNIT_ASSERT(tmpFilePath3.substr(0, programPath.size()) == programPath);
    CPPUNIT_ASSERT(tmpFilePath3.substr(tmpFilePath3.size() - 13, 3) == "my-");
    CPPUNIT_ASSERT(tmpFilePath3.substr(tmpFilePath3.size() - 4) == ".TXT");
    tmpFile3.close();
    //CPPUNIT_ASSERT(std::remove(tmpFilePath3.c_str()) == 0)

    CPPUNIT_ASSERT_THROW(mitk::IOUtil::CreateTemporaryFile(tmpFile2, "XX"), mitk::Exception);

    std::string tmpDir = mitk::IOUtil::CreateTemporaryDirectory();
    CPPUNIT_ASSERT(tmpDir.size() > tmpPath.size());
    CPPUNIT_ASSERT(tmpDir.substr(0, tmpPath.size()) == tmpPath);
    CPPUNIT_ASSERT(itksys::SystemTools::RemoveADirectory(tmpDir.c_str()));

    std::string tmpDir2 = mitk::IOUtil::CreateTemporaryDirectory("my-XXXXXX", programPath);
    CPPUNIT_ASSERT(tmpDir2.size() > programPath.size());
    CPPUNIT_ASSERT(tmpDir2.substr(0, programPath.size()) == programPath);
    CPPUNIT_ASSERT(itksys::SystemTools::RemoveADirectory(tmpDir2.c_str()));
  }

  void TestLoadAndSaveImage()
  {
    mitk::Image::Pointer img1 = mitk::IOUtil::LoadImage(m_ImagePath);
    CPPUNIT_ASSERT( img1.IsNotNull());

    std::ofstream tmpStream;
    std::string imagePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "diffpic3d-XXXXXX.nrrd");
    tmpStream.close();
    std::string imagePath2 = mitk::IOUtil::CreateTemporaryFile(tmpStream, "diffpic3d-XXXXXX.nii.gz");
    tmpStream.close();

    // the cases where no exception should be thrown
    CPPUNIT_ASSERT(mitk::IOUtil::SaveImage(img1, imagePath));
    CPPUNIT_ASSERT(mitk::IOUtil::SaveBaseData(img1.GetPointer(), imagePath2));

    //load data which does not exist
    CPPUNIT_ASSERT_THROW(mitk::IOUtil::LoadImage("fileWhichDoesNotExist.nrrd"), mitk::Exception);

    //delete the files after the test is done
    std::remove(imagePath.c_str());
    std::remove(imagePath2.c_str());

    mitk::Image::Pointer relativImage = mitk::ImageGenerator::GenerateGradientImage<float>(4,4,4,1);
    std::string imagePath3 = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.nrrd");
    tmpStream.close();
    mitk::IOUtil::SaveImage(relativImage, imagePath3);
    CPPUNIT_ASSERT_NO_THROW(mitk::IOUtil::LoadImage(imagePath3));
    std::remove(imagePath3.c_str());
  }

  void TestLoadAndSavePointSet()
  {
    mitk::PointSet::Pointer pointset = mitk::IOUtil::LoadPointSet(m_PointSetPath);
    CPPUNIT_ASSERT( pointset.IsNotNull());

    std::ofstream tmpStream;
    std::string pointSetPath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.mps");
    tmpStream.close();
    std::string pointSetPathWithDefaultExtension = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.mps");
    tmpStream.close();
    std::string pointSetPathWithoutDefaultExtension = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.xXx");
    tmpStream.close();

    // the cases where no exception should be thrown
    CPPUNIT_ASSERT(mitk::IOUtil::SavePointSet(pointset, pointSetPathWithDefaultExtension));

    // test if defaultextension is inserted if no extension is present
    CPPUNIT_ASSERT(mitk::IOUtil::SavePointSet(pointset, pointSetPathWithoutDefaultExtension.c_str()));

    //delete the files after the test is done
    std::remove(pointSetPath.c_str());
    std::remove(pointSetPathWithDefaultExtension.c_str());
    std::remove(pointSetPathWithoutDefaultExtension.c_str());
  }

  void TestLoadAndSaveSurface()
  {
    mitk::Surface::Pointer surface = mitk::IOUtil::LoadSurface(m_SurfacePath);
    CPPUNIT_ASSERT( surface.IsNotNull());

    std::ofstream tmpStream;
    std::string surfacePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "diffsurface-XXXXXX.stl");

    // the cases where no exception should be thrown
    CPPUNIT_ASSERT(mitk::IOUtil::SaveSurface(surface, surfacePath));

    // test if exception is thrown as expected on unknown extsension
    CPPUNIT_ASSERT_THROW(mitk::IOUtil::SaveSurface(surface,"testSurface.xXx"), mitk::Exception);

    //delete the files after the test is done
    std::remove(surfacePath.c_str());
  }

};

MITK_TEST_SUITE_REGISTRATION(mitkIOUtil)
<commit_msg>Use the getTestDataFilePath() method to get absolute paths to test data.<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkTestingMacros.h"
#include <mitkTestingConfig.h>
#include <mitkTestFixture.h>

#include <mitkIOUtil.h>
#include <mitkImageGenerator.h>

#include <itksys/SystemTools.hxx>

class mitkIOUtilTestSuite : public mitk::TestFixture
{

  CPPUNIT_TEST_SUITE(mitkIOUtilTestSuite);
  MITK_TEST(TestTempMethods);
  MITK_TEST(TestLoadAndSaveImage);
  MITK_TEST(TestLoadAndSavePointSet);
  MITK_TEST(TestLoadAndSaveSurface);
  CPPUNIT_TEST_SUITE_END();

private:

  std::string m_ImagePath;
  std::string m_SurfacePath;
  std::string m_PointSetPath;

public:

  void setUp()
  {
    m_ImagePath = getTestDataFilePath("Pic3D.nrrd");
    m_SurfacePath = getTestDataFilePath("binary.stl");
    m_PointSetPath = getTestDataFilePath("pointSet.mps");
  }

  void TestTempMethods()
  {
    std::string tmpPath = mitk::IOUtil::GetTempPath();
    CPPUNIT_ASSERT(!tmpPath.empty());

    std::ofstream tmpFile;
    std::string tmpFilePath = mitk::IOUtil::CreateTemporaryFile(tmpFile);
    CPPUNIT_ASSERT(tmpFile && tmpFile.is_open());
    CPPUNIT_ASSERT(tmpFilePath.size() > tmpPath.size());
    CPPUNIT_ASSERT(tmpFilePath.substr(0, tmpPath.size()) == tmpPath);

    tmpFile.close();
    CPPUNIT_ASSERT(std::remove(tmpFilePath.c_str()) == 0);

    std::string programPath = mitk::IOUtil::GetProgramPath();
    CPPUNIT_ASSERT(!programPath.empty());
    std::ofstream tmpFile2;
    std::string tmpFilePath2 = mitk::IOUtil::CreateTemporaryFile(tmpFile2, "my-XXXXXX", programPath);
    CPPUNIT_ASSERT(tmpFile2 && tmpFile2.is_open());
    CPPUNIT_ASSERT(tmpFilePath2.size() > programPath.size());
    CPPUNIT_ASSERT(tmpFilePath2.substr(0, programPath.size()) == programPath);
    tmpFile2.close();
    CPPUNIT_ASSERT(std::remove(tmpFilePath2.c_str()) == 0);

    std::ofstream tmpFile3;
    std::string tmpFilePath3 = mitk::IOUtil::CreateTemporaryFile(tmpFile3, std::ios_base::binary,
                                                                 "my-XXXXXX.TXT", programPath);
    CPPUNIT_ASSERT(tmpFile3 && tmpFile3.is_open());
    CPPUNIT_ASSERT(tmpFilePath3.size() > programPath.size());
    CPPUNIT_ASSERT(tmpFilePath3.substr(0, programPath.size()) == programPath);
    CPPUNIT_ASSERT(tmpFilePath3.substr(tmpFilePath3.size() - 13, 3) == "my-");
    CPPUNIT_ASSERT(tmpFilePath3.substr(tmpFilePath3.size() - 4) == ".TXT");
    tmpFile3.close();
    //CPPUNIT_ASSERT(std::remove(tmpFilePath3.c_str()) == 0)

    CPPUNIT_ASSERT_THROW(mitk::IOUtil::CreateTemporaryFile(tmpFile2, "XX"), mitk::Exception);

    std::string tmpDir = mitk::IOUtil::CreateTemporaryDirectory();
    CPPUNIT_ASSERT(tmpDir.size() > tmpPath.size());
    CPPUNIT_ASSERT(tmpDir.substr(0, tmpPath.size()) == tmpPath);
    CPPUNIT_ASSERT(itksys::SystemTools::RemoveADirectory(tmpDir.c_str()));

    std::string tmpDir2 = mitk::IOUtil::CreateTemporaryDirectory("my-XXXXXX", programPath);
    CPPUNIT_ASSERT(tmpDir2.size() > programPath.size());
    CPPUNIT_ASSERT(tmpDir2.substr(0, programPath.size()) == programPath);
    CPPUNIT_ASSERT(itksys::SystemTools::RemoveADirectory(tmpDir2.c_str()));
  }

  void TestLoadAndSaveImage()
  {
    mitk::Image::Pointer img1 = mitk::IOUtil::LoadImage(m_ImagePath);
    CPPUNIT_ASSERT( img1.IsNotNull());

    std::ofstream tmpStream;
    std::string imagePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "diffpic3d-XXXXXX.nrrd");
    tmpStream.close();
    std::string imagePath2 = mitk::IOUtil::CreateTemporaryFile(tmpStream, "diffpic3d-XXXXXX.nii.gz");
    tmpStream.close();

    // the cases where no exception should be thrown
    CPPUNIT_ASSERT(mitk::IOUtil::SaveImage(img1, imagePath));
    CPPUNIT_ASSERT(mitk::IOUtil::SaveBaseData(img1.GetPointer(), imagePath2));

    //load data which does not exist
    CPPUNIT_ASSERT_THROW(mitk::IOUtil::LoadImage("fileWhichDoesNotExist.nrrd"), mitk::Exception);

    //delete the files after the test is done
    std::remove(imagePath.c_str());
    std::remove(imagePath2.c_str());

    mitk::Image::Pointer relativImage = mitk::ImageGenerator::GenerateGradientImage<float>(4,4,4,1);
    std::string imagePath3 = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.nrrd");
    tmpStream.close();
    mitk::IOUtil::SaveImage(relativImage, imagePath3);
    CPPUNIT_ASSERT_NO_THROW(mitk::IOUtil::LoadImage(imagePath3));
    std::remove(imagePath3.c_str());
  }

  void TestLoadAndSavePointSet()
  {
    mitk::PointSet::Pointer pointset = mitk::IOUtil::LoadPointSet(m_PointSetPath);
    CPPUNIT_ASSERT( pointset.IsNotNull());

    std::ofstream tmpStream;
    std::string pointSetPath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.mps");
    tmpStream.close();
    std::string pointSetPathWithDefaultExtension = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.mps");
    tmpStream.close();
    std::string pointSetPathWithoutDefaultExtension = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.xXx");
    tmpStream.close();

    // the cases where no exception should be thrown
    CPPUNIT_ASSERT(mitk::IOUtil::SavePointSet(pointset, pointSetPathWithDefaultExtension));

    // test if defaultextension is inserted if no extension is present
    CPPUNIT_ASSERT(mitk::IOUtil::SavePointSet(pointset, pointSetPathWithoutDefaultExtension.c_str()));

    //delete the files after the test is done
    std::remove(pointSetPath.c_str());
    std::remove(pointSetPathWithDefaultExtension.c_str());
    std::remove(pointSetPathWithoutDefaultExtension.c_str());
  }

  void TestLoadAndSaveSurface()
  {
    mitk::Surface::Pointer surface = mitk::IOUtil::LoadSurface(m_SurfacePath);
    CPPUNIT_ASSERT( surface.IsNotNull());

    std::ofstream tmpStream;
    std::string surfacePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "diffsurface-XXXXXX.stl");

    // the cases where no exception should be thrown
    CPPUNIT_ASSERT(mitk::IOUtil::SaveSurface(surface, surfacePath));

    // test if exception is thrown as expected on unknown extsension
    CPPUNIT_ASSERT_THROW(mitk::IOUtil::SaveSurface(surface,"testSurface.xXx"), mitk::Exception);

    //delete the files after the test is done
    std::remove(surfacePath.c_str());
  }

};

MITK_TEST_SUITE_REGISTRATION(mitkIOUtil)
<|endoftext|>


<commit_before>// $Id$
// Main authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007

/**************************************************************************
 * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
 * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for          *
 * full copyright notice.                                                 *
 **************************************************************************/

TEveElementList* esd_spd_tracklets(Float_t radius=8, Width_t line_width=3,
				   Float_t dPhiWindow=0.080, Float_t dThetaWindow=0.025,
				   Float_t dPhiShift05T=0.0045)
{
  // radius - cylindrical radius to which the tracklets should be extrapolated

  AliESDEvent     *esd = AliEveEventManager::AssertESD();
  AliESDVertex    *pv  = esd->GetPrimaryVertexSPD();
  AliMultiplicity *mul = esd->GetMultiplicity();

  AliMagF *field = AliEveEventManager::AssertMagField();

  TEveElementList* cont = new TEveElementList("SPD Tracklets");
  gEve->AddElement(cont);

  TEveTrackList *tg = new TEveTrackList("Good");
  tg->SetMainColor(7);
  tg->SetLineWidth(line_width);
  cont->AddElement(tg);

  TEveTrackPropagator* pg = tg->GetPropagator();
  pg->SetMaxR(radius);

  TEveTrackList *tb = new TEveTrackList("Bad");
  tb->SetMainColor(7);
  tb->SetLineWidth(line_width);
  cont->AddElement(tb);

  TEveTrackPropagator* pb = tb->GetPropagator();
  pb->SetMaxR(radius);

  const Float_t  Bz = TMath::Abs(field->SolenoidField());

  const Double_t dPhiShift     = dPhiShift05T / 5.0 * Bz;
  const Double_t dPhiWindow2   = dPhiWindow * dPhiWindow;
  const Double_t dThetaWindow2 = dThetaWindow * dThetaWindow;

  for (Int_t i = 0; i < mul->GetNumberOfTracklets(); ++i)
  {
    Float_t theta  = mul->GetTheta(i);
    Float_t phi    = mul->GetPhi(i);
    Float_t dTheta = mul->GetDeltaTheta(i);
    Float_t dPhi   = mul->GetDeltaPhi(i) - dPhiShift;
    Float_t d      = dPhi*dPhi/dPhiWindow2 + dTheta*dTheta/dThetaWindow2;

    TEveTrackList* tl = (d < 1.0f) ? tg : tb;

    AliEveTracklet *t = new AliEveTracklet(i, pv, theta, phi, tl->GetPropagator());
    t->SetAttLineAttMarker(tl);
    t->SetElementName(Form("Tracklet %d", i));
    t->SetElementTitle(Form("Id = %d\nEta=%.3f, Theta=%.3f, dTheta=%.3f\nPhi=%.3f dPhi=%.3f",
			    i, mul->GetEta(i), theta, dTheta, phi, dPhi));

    tl->AddElement(t);
  }

  tg->MakeTracks();
  tg->SetTitle(Form("N=%d", tg->NumChildren()));

  tb->MakeTracks();
  tb->SetTitle(Form("N=%d", tb->NumChildren()));

  if (AliEveTrackCounter::IsActive())
  {
    AliEveTrackCounter::fgInstance->RegisterTracklets(tg, kTRUE);
    AliEveTrackCounter::fgInstance->RegisterTracklets(tb, kFALSE);
  }
  else
  {
    tb->SetLineStyle(6);
  }

  gEve->Redraw3D();

  return cont;
}
<commit_msg>SPD trackelts were too thick.<commit_after>// $Id$
// Main authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007

/**************************************************************************
 * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
 * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for          *
 * full copyright notice.                                                 *
 **************************************************************************/

TEveElementList* esd_spd_tracklets(Float_t radius=8, Width_t line_width=2,
				   Float_t dPhiWindow=0.080, Float_t dThetaWindow=0.025,
				   Float_t dPhiShift05T=0.0045)
{
  // radius - cylindrical radius to which the tracklets should be extrapolated

  AliESDEvent     *esd = AliEveEventManager::AssertESD();
  AliESDVertex    *pv  = esd->GetPrimaryVertexSPD();
  AliMultiplicity *mul = esd->GetMultiplicity();

  AliMagF *field = AliEveEventManager::AssertMagField();

  TEveElementList* cont = new TEveElementList("SPD Tracklets");
  gEve->AddElement(cont);

  TEveTrackList *tg = new TEveTrackList("Good");
  tg->SetMainColor(7);
  tg->SetLineWidth(line_width);
  cont->AddElement(tg);

  TEveTrackPropagator* pg = tg->GetPropagator();
  pg->SetMaxR(radius);

  TEveTrackList *tb = new TEveTrackList("Bad");
  tb->SetMainColor(7);
  tb->SetLineWidth(line_width);
  cont->AddElement(tb);

  TEveTrackPropagator* pb = tb->GetPropagator();
  pb->SetMaxR(radius);

  const Float_t  Bz = TMath::Abs(field->SolenoidField());

  const Double_t dPhiShift     = dPhiShift05T / 5.0 * Bz;
  const Double_t dPhiWindow2   = dPhiWindow * dPhiWindow;
  const Double_t dThetaWindow2 = dThetaWindow * dThetaWindow;

  for (Int_t i = 0; i < mul->GetNumberOfTracklets(); ++i)
  {
    Float_t theta  = mul->GetTheta(i);
    Float_t phi    = mul->GetPhi(i);
    Float_t dTheta = mul->GetDeltaTheta(i);
    Float_t dPhi   = mul->GetDeltaPhi(i) - dPhiShift;
    Float_t d      = dPhi*dPhi/dPhiWindow2 + dTheta*dTheta/dThetaWindow2;

    TEveTrackList* tl = (d < 1.0f) ? tg : tb;

    AliEveTracklet *t = new AliEveTracklet(i, pv, theta, phi, tl->GetPropagator());
    t->SetAttLineAttMarker(tl);
    t->SetElementName(Form("Tracklet %d", i));
    t->SetElementTitle(Form("Id = %d\nEta=%.3f, Theta=%.3f, dTheta=%.3f\nPhi=%.3f dPhi=%.3f",
			    i, mul->GetEta(i), theta, dTheta, phi, dPhi));

    tl->AddElement(t);
  }

  tg->MakeTracks();
  tg->SetTitle(Form("N=%d", tg->NumChildren()));

  tb->MakeTracks();
  tb->SetTitle(Form("N=%d", tb->NumChildren()));

  if (AliEveTrackCounter::IsActive())
  {
    AliEveTrackCounter::fgInstance->RegisterTracklets(tg, kTRUE);
    AliEveTrackCounter::fgInstance->RegisterTracklets(tb, kFALSE);
  }
  else
  {
    tb->SetLineStyle(6);
  }

  gEve->Redraw3D();

  return cont;
}
<|endoftext|>


<commit_before>//
// upb - a minimalist implementation of protocol buffers.
//
// Copyright (c) 2011 Google Inc.  See LICENSE for details.
// Author: Josh Haberman <jhaberman@gmail.com>
// Routines for reading and writing message data to an in-memory structure,
// similar to a C struct.
//
// upb does not define one single message object that everyone must use.
// Rather it defines an abstract interface for reading and writing members
// of a message object, and all of the parsers and serializers use this
// abstract interface.  This allows upb's parsers and serializers to be used
// regardless of what memory management scheme or synchronization model the
// application is using.
//
// A standard set of accessors is provided for doing simple reads and writes at
// a known offset into the message.  These accessors should be used when
// possible, because they are specially optimized -- for example, the JIT can
// recognize them and emit specialized code instead of having to call the
// function at all.  The application can substitute its own accessors when the
// standard accessors are not suitable.

#ifndef UPB_MSG_HPP
#define UPB_MSG_HPP

#include "upb/msg.h"
#include "upb/handlers.hpp"

namespace upb {

typedef upb_accessor_vtbl AccessorVTable;

// Registers handlers for writing into a message of the given type using
// whatever accessors it has defined.
inline MessageHandlers* RegisterWriteHandlers(upb::Handlers* handlers,
                                              const upb::MessageDef* md) {
  return MessageHandlers::Cast(
      upb_accessors_reghandlers(handlers, md));
}

template <typename T> static FieldHandlers::ValueHandler* GetValueHandler();

// A handy templated function that will retrieve a value handler for a given
// C++ type.
#define GET_VALUE_HANDLER(type, ctype) \
    template <> \
    FieldHandlers::ValueHandler* GetValueHandler<ctype>() { \
      return &upb_stdmsg_set ## type; \
    }

GET_VALUE_HANDLER(double, double);
GET_VALUE_HANDLER(float, float);
GET_VALUE_HANDLER(uint64, uint64_t);
GET_VALUE_HANDLER(uint32, uint32_t);
GET_VALUE_HANDLER(int64, int64_t);
GET_VALUE_HANDLER(int32, int32_t);
GET_VALUE_HANDLER(bool, bool);
#undef GET_VALUE_HANDLER

}  // namespace

#endif
<commit_msg>Fix duplicate symbol on OS X.<commit_after>//
// upb - a minimalist implementation of protocol buffers.
//
// Copyright (c) 2011 Google Inc.  See LICENSE for details.
// Author: Josh Haberman <jhaberman@gmail.com>
// Routines for reading and writing message data to an in-memory structure,
// similar to a C struct.
//
// upb does not define one single message object that everyone must use.
// Rather it defines an abstract interface for reading and writing members
// of a message object, and all of the parsers and serializers use this
// abstract interface.  This allows upb's parsers and serializers to be used
// regardless of what memory management scheme or synchronization model the
// application is using.
//
// A standard set of accessors is provided for doing simple reads and writes at
// a known offset into the message.  These accessors should be used when
// possible, because they are specially optimized -- for example, the JIT can
// recognize them and emit specialized code instead of having to call the
// function at all.  The application can substitute its own accessors when the
// standard accessors are not suitable.

#ifndef UPB_MSG_HPP
#define UPB_MSG_HPP

#include "upb/msg.h"
#include "upb/handlers.hpp"

namespace upb {

typedef upb_accessor_vtbl AccessorVTable;

// Registers handlers for writing into a message of the given type using
// whatever accessors it has defined.
inline MessageHandlers* RegisterWriteHandlers(upb::Handlers* handlers,
                                              const upb::MessageDef* md) {
  return MessageHandlers::Cast(
      upb_accessors_reghandlers(handlers, md));
}

template <typename T> static FieldHandlers::ValueHandler* GetValueHandler();

// A handy templated function that will retrieve a value handler for a given
// C++ type.
#define GET_VALUE_HANDLER(type, ctype) \
    template <> \
    inline FieldHandlers::ValueHandler* GetValueHandler<ctype>() { \
      return &upb_stdmsg_set ## type; \
    }

GET_VALUE_HANDLER(double, double);
GET_VALUE_HANDLER(float, float);
GET_VALUE_HANDLER(uint64, uint64_t);
GET_VALUE_HANDLER(uint32, uint32_t);
GET_VALUE_HANDLER(int64, int64_t);
GET_VALUE_HANDLER(int32, int32_t);
GET_VALUE_HANDLER(bool, bool);
#undef GET_VALUE_HANDLER

}  // namespace

#endif
<|endoftext|>


<commit_before>#include "directory.hh"
#include "../messages/filelist.hh"
#include "../messages/boost_impl.hh"
#include "../messages/factory.hh"
#include <boost/asio.hpp>
#include <iomanip>

using namespace std;
using namespace eclipse;
using namespace eclipse::messages;
using boost::asio::ip::tcp;
using vec_str = std::vector<std::string>;

boost::asio::io_service iosvc;

tcp::socket* connect (int index) {
  tcp::socket* socket = new tcp::socket (iosvc);
  Settings setted = Settings().load();

  int port      = setted.get<int> ("network.port_mapreduce");
  vec_str nodes = setted.get<vec_str> ("network.nodes");

  string host = nodes[ index ];

  tcp::resolver resolver (iosvc);
  tcp::resolver::query query (host, to_string(port));
  tcp::resolver::iterator it (resolver.resolve(query));
  auto ep = new tcp::endpoint (*it);
  socket->connect(*ep);
  return socket;
}

void send_message (tcp::socket* socket, eclipse::messages::Message* msg) {
  string out = save_message(msg);
  stringstream ss;
  ss << setfill('0') << setw(16) << out.length() << out;

  socket->send(boost::asio::buffer(ss.str()));
}

eclipse::messages::FileList* read_reply(tcp::socket* socket) {
  char header[16];
  socket->receive(boost::asio::buffer(header));
  size_t size_of_msg = atoi(header);
  char* body = new char[size_of_msg];
  socket->receive(boost::asio::buffer(body, size_of_msg));
  string recv_msg(body);
  eclipse::messages::Message* m = load_message(recv_msg);
  return dynamic_cast<eclipse::messages::FileList*>(m);
}

int main(int argc, char* argv[])
{
  Context con;
  const int NUM_SERVERS = con.settings.get<vector<string>>("network.nodes").size();
  vector<string> nodes = con.settings.get<vector<string>>("network.nodes");
  vector<string>::iterator nit = nodes.begin();

  for(int net_id=0; net_id<NUM_SERVERS; net_id++)
  {
    FileList file_list;
    tcp::socket* socket = connect(net_id);
    send_message(socket, &file_list);
    auto file_list_reply = read_reply(socket);
    socket->close();

    cout << *nit << endl;
      cout << setw(12) << "Hash Key"
      << setw(12) << "Size"
      << setw(12) << "NumBlocks"
      << setw(12) << "Replicas"
      << "\t" <<  "FileName" << endl;
    nit++;

    // client side
    for(vector<FileInfo>::iterator it=file_list_reply->data.begin(); it!=file_list_reply->data.end(); it++)
    {
      cout << setw(12) << it->file_hash_key
      << setw(12) << it->file_size
      << setw(12) << it->num_block
      << setw(12) << it->replica
      << "\t" << it->file_name << endl;
    }
    delete file_list_reply;
  }
  return 0;
}
<commit_msg>added pretty printing<commit_after>#include "directory.hh"
#include "../messages/filelist.hh"
#include "../messages/boost_impl.hh"
#include "../messages/factory.hh"
#include <boost/asio.hpp>
#include <iomanip>

using namespace std;
using namespace eclipse;
using namespace eclipse::messages;
using boost::asio::ip::tcp;
using vec_str = std::vector<std::string>;

boost::asio::io_service iosvc;

tcp::socket* connect (int index) {
  tcp::socket* socket = new tcp::socket (iosvc);
  Settings setted = Settings().load();

  int port      = setted.get<int> ("network.port_mapreduce");
  vec_str nodes = setted.get<vec_str> ("network.nodes");

  string host = nodes[ index ];

  tcp::resolver resolver (iosvc);
  tcp::resolver::query query (host, to_string(port));
  tcp::resolver::iterator it (resolver.resolve(query));
  auto ep = new tcp::endpoint (*it);
  socket->connect(*ep);
  return socket;
}

void send_message (tcp::socket* socket, eclipse::messages::Message* msg) {
  string out = save_message(msg);
  stringstream ss;
  ss << setfill('0') << setw(16) << out.length() << out;

  socket->send(boost::asio::buffer(ss.str()));
}

eclipse::messages::FileList* read_reply(tcp::socket* socket) {
  char header[16];
  socket->receive(boost::asio::buffer(header));
  size_t size_of_msg = atoi(header);
  char* body = new char[size_of_msg];
  socket->receive(boost::asio::buffer(body, size_of_msg));
  string recv_msg(body);
  eclipse::messages::Message* m = load_message(recv_msg);
  return dynamic_cast<eclipse::messages::FileList*>(m);
}

int main(int argc, char* argv[])
{
  Context con;
  const int NUM_SERVERS = con.settings.get<vector<string>>("network.nodes").size();
  vector<string> nodes = con.settings.get<vector<string>>("network.nodes");
  vector<FileInfo> total;

  for(int net_id=0; net_id<NUM_SERVERS; net_id++)
  {
    FileList file_list;
    tcp::socket* socket = connect(net_id);
    send_message(socket, &file_list);
    auto file_list_reply = read_reply(socket);
    socket->close();

    std::copy(file_list_reply->data.begin(), file_list_reply->data.end(), back_inserter(total));
    delete file_list_reply;
  }

  std::sort(total.begin(), total.end(), [] (const FileInfo& a, const FileInfo& b) {
      return (a.file_name < b.file_name);
      });
  cout
    << setw(14) << "FileName"
    << setw(14) << "Hash Key"
    << setw(14) << "Size"
    << setw(14) << "NumBlocks"
    << setw(14) << "Host"
    << setw(14) << "Replicas"
    << endl << string(14*6,'-') << endl;

  for (auto& fl: total) {
    cout
      << setw(14) << fl.file_name
      << setw(14) << fl.file_hash_key
      << setw(14) << fl.file_size
      << setw(14) << fl.num_block
      << setw(14) << nodes[h(fl.file_name) % NUM_SERVERS]
      << setw(14) << fl.replica
      << endl;
  }
  return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014 Endless Mobile
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 *
 * Written by:
 *     Jasper St. Pierre <jstpierre@mecheye.net>
 */

#include "function.h"
#include "value.h"
#include "gobject.h"

using namespace v8;

namespace GNodeJS {

struct FunctionInfo {
    GIFunctionInfo *info;
};

static Handle<Value> FunctionInvoker(const Arguments &args) {
    HandleScope scope;
    FunctionInfo *func = (FunctionInfo *) External::Unwrap (args.Data ());

    GIBaseInfo *info = func->info;
    GIFunctionInfo *function_info = (GIFunctionInfo *) info;
    GError *error = NULL;

    /* XXX: For now, only work on functions without any OUT args at all.
     * Just assume everything is an in arg. */
    int n_in_args = g_callable_info_get_n_args ((GICallableInfo *) info);
    int n_total_args = n_in_args;

    if (args.Length() < n_in_args) {
        ThrowException (Exception::TypeError (String::New ("Not enough arguments.")));
        return scope.Close (Undefined ());
    }

    gboolean is_method = ((g_function_info_get_flags (info) & GI_FUNCTION_IS_METHOD) != 0 &&
                          (g_function_info_get_flags (info) & GI_FUNCTION_IS_CONSTRUCTOR) == 0);
    if (is_method)
        n_total_args++;

    GIArgument total_args[n_total_args];
    GIArgument *in_args;

    if (is_method) {
        total_args[0].v_pointer = GObjectFromWrapper (args.This ());
        in_args = &total_args[1];
    } else {
        in_args = &total_args[0];
    }

    for (int i = 0; i < n_in_args; i++) {
        GIArgInfo *arg_info = g_callable_info_get_arg ((GICallableInfo *) info, i);
        GITypeInfo type_info;
        bool may_be_null = g_arg_info_may_be_null (arg_info);
        g_arg_info_load_type (arg_info, &type_info);
        V8ToGIArgument (&type_info, &in_args[i], args[i], may_be_null);
        g_base_info_unref ((GIBaseInfo *) arg_info);
    }

    GIArgument return_value;
    g_function_info_invoke (function_info,
                            total_args, n_total_args,
                            NULL, 0,
                            &return_value,
                            &error);

    for (int i = 0; i < n_in_args; i++) {
        GIArgInfo *arg_info = g_callable_info_get_arg ((GICallableInfo *) info, i);
        GITypeInfo type_info;
        g_arg_info_load_type (arg_info, &type_info);
        FreeGIArgument (&type_info, &in_args[i]);
        g_base_info_unref ((GIBaseInfo *) arg_info);
    }

    if (error) {
        ThrowException (Exception::TypeError (String::New (error->message)));
        return scope.Close (Undefined ());
    }

    GITypeInfo return_value_type;
    g_callable_info_load_return_type ((GICallableInfo *) info, &return_value_type);
    return scope.Close (GIArgumentToV8 (&return_value_type, &return_value));
}

static void FunctionDestroyed(Persistent<Value> object, void *data) {
    FunctionInfo *func = (FunctionInfo *) data;
    g_base_info_unref (func->info);
    g_free (func);
}

Handle<Function> MakeFunction(GIBaseInfo *info) {
    FunctionInfo *func = g_new0 (FunctionInfo, 1);
    func->info = g_base_info_ref (info);
    Persistent<FunctionTemplate> tpl = Persistent<FunctionTemplate>::New (FunctionTemplate::New (FunctionInvoker, External::Wrap (func)));
    tpl.MakeWeak (func, FunctionDestroyed);
    Local<Function> fn = tpl->GetFunction ();

    const char *function_name = g_base_info_get_name (info);
    fn->SetName (String::NewSymbol (function_name));

    return fn;
}

};
<commit_msg>function: Add more support for out pointers<commit_after>/*
 * Copyright (C) 2014 Endless Mobile
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 *
 * Written by:
 *     Jasper St. Pierre <jstpierre@mecheye.net>
 */

#include "function.h"
#include "value.h"
#include "gobject.h"

#include <girffi.h>

using namespace v8;

namespace GNodeJS {

struct FunctionInfo {
    GIFunctionInfo *info;
    GIFunctionInvoker invoker;
};

static Handle<Value> FunctionInvoker(const Arguments &args) {
    HandleScope scope;
    FunctionInfo *func = (FunctionInfo *) External::Unwrap (args.Data ());

    GIBaseInfo *info = func->info;
    GError *error = NULL;

    int n_callable_args = g_callable_info_get_n_args ((GICallableInfo *) info);
    int n_total_args = n_callable_args;
    int n_in_args = 0;

    for (int i = 0; i < n_callable_args; i++) {
        GIArgInfo arg_info;

        g_callable_info_load_arg ((GICallableInfo *) info, i, &arg_info);

        if (g_arg_info_get_direction (&arg_info) == GI_DIRECTION_IN ||
            g_arg_info_get_direction (&arg_info) == GI_DIRECTION_INOUT)
            n_in_args++;
    }

    if (args.Length() < n_in_args) {
        ThrowException (Exception::TypeError (String::New ("Not enough arguments.")));
        return scope.Close (Undefined ());
    }

    gboolean is_method = ((g_function_info_get_flags (info) & GI_FUNCTION_IS_METHOD) != 0 &&
                          (g_function_info_get_flags (info) & GI_FUNCTION_IS_CONSTRUCTOR) == 0);
    if (is_method)
        n_total_args++;

    GIArgument total_arg_values[n_total_args];
    GIArgument *callable_arg_values;

    if (is_method) {
        total_arg_values[0].v_pointer = GObjectFromWrapper (args.This ());
        callable_arg_values = &total_arg_values[1];
    } else {
        callable_arg_values = &total_arg_values[0];
    }

    for (int i = 0; i < n_callable_args; i++) {
        GIArgInfo arg_info = {};
        g_callable_info_load_arg ((GICallableInfo *) info, i, &arg_info);
        GIDirection direction = g_arg_info_get_direction (&arg_info);

        if (direction == GI_DIRECTION_OUT) {
            if (g_arg_info_is_caller_allocates (&arg_info)) {
                assert (0);
            } else {
                callable_arg_values[i].v_pointer = NULL;
            }
        } else {
            bool may_be_null = g_arg_info_may_be_null (&arg_info);
            GITypeInfo type_info;
            g_arg_info_load_type (&arg_info, &type_info);
            V8ToGIArgument (&type_info, &callable_arg_values[i], args[i], may_be_null);
        }
    }

    void *ffi_arg_pointers[n_total_args];
    for (int i = 0; i < n_total_args; i++)
        ffi_arg_pointers[i] = &total_arg_values[i];

    GIArgument return_value;
    ffi_call (&func->invoker.cif, FFI_FN (func->invoker.native_address),
              &return_value, ffi_arg_pointers);

    for (int i = 0; i < n_callable_args; i++) {
        GIArgInfo arg_info;
        g_callable_info_load_arg ((GICallableInfo *) info, i, &arg_info);
        GIDirection direction = g_arg_info_get_direction (&arg_info);
        if (direction == GI_DIRECTION_OUT) {
            /* XXX: Process out value. */
        } else {
            GITypeInfo type_info;
            g_arg_info_load_type (&arg_info, &type_info);
            FreeGIArgument (&type_info, &callable_arg_values[i]);
        }
    }

    if (error) {
        ThrowException (Exception::TypeError (String::New (error->message)));
        return scope.Close (Undefined ());
    }

    GITypeInfo return_value_type;
    g_callable_info_load_return_type ((GICallableInfo *) info, &return_value_type);
    return scope.Close (GIArgumentToV8 (&return_value_type, &return_value));
}

static void FunctionDestroyed(Persistent<Value> object, void *data) {
    FunctionInfo *func = (FunctionInfo *) data;
    g_base_info_unref (func->info);
    g_function_invoker_destroy(&func->invoker);
    g_free (func);
}

Handle<Function> MakeFunction(GIBaseInfo *info) {
    FunctionInfo *func = g_new0 (FunctionInfo, 1);
    func->info = g_base_info_ref (info);

    g_function_info_prep_invoker (func->info, &func->invoker, NULL);

    Persistent<FunctionTemplate> tpl = Persistent<FunctionTemplate>::New (FunctionTemplate::New (FunctionInvoker, External::Wrap (func)));
    tpl.MakeWeak (func, FunctionDestroyed);
    Local<Function> fn = tpl->GetFunction ();

    const char *function_name = g_base_info_get_name (info);
    fn->SetName (String::NewSymbol (function_name));

    return fn;
}

};
<|endoftext|>


<commit_before>/*** Copyright (c), The Regents of the University of California            ***
 *** For more infophybunation please refer to files in the COPYRIGHT directory ***/
/*
 * iphybun - The irods phybun utility
*/
#include "irods_client_api_table.hpp"
#include "irods_pack_table.hpp"
#include "rodsClient.hpp"
#include "parseCommandLine.hpp"
#include "rodsPath.hpp"
#include "phybunUtil.hpp"
void usage();

int
main( int argc, char **argv ) {
    int status;
    rodsEnv myEnv;
    rErrMsg_t errMsg;
    rcComm_t *conn;
    rodsArguments_t myRodsArgs;
    char *optStr;
    rodsPathInp_t rodsPathInp;

    optStr = "hD:N:KR:S:s:"; // JMC - backport 4528, 4658, 4771

    status = parseCmdLineOpt( argc, argv, optStr, 0, &myRodsArgs );
    if ( status < 0 ) {
        printf( "Use -h for help.\n" );
        exit( 1 );
    }
    if ( myRodsArgs.help == True ) {
        usage();
        exit( 0 );
    }

    if ( argc - optind <= 0 ) {
        rodsLog( LOG_ERROR, "iphybun: no input" );
        printf( "Use -h for help.\n" );
        exit( 2 );
    }

    status = getRodsEnv( &myEnv );

    if ( status < 0 ) {
        rodsLogError( LOG_ERROR, status, "main: getRodsEnv error. " );
        exit( 1 );
    }

    status = parseCmdLinePath( argc, argv, optind, &myEnv,
                               UNKNOWN_OBJ_T, NO_INPUT_T, 0, &rodsPathInp );

    if ( status < 0 ) {
        rodsLogError( LOG_ERROR, status, "main: parseCmdLinePath error. " );
        printf( "Use -h for help.\n" );
        exit( 1 );
    }

    // =-=-=-=-=-=-=-
    // initialize pluggable api table
    irods::api_entry_table&  api_tbl = irods::get_client_api_table();
    irods::pack_entry_table& pk_tbl  = irods::get_pack_table();
    init_api_table( api_tbl, pk_tbl );

    conn = rcConnect( myEnv.rodsHost, myEnv.rodsPort, myEnv.rodsUserName,
                      myEnv.rodsZone, 1, &errMsg );

    if ( conn == NULL ) {
        exit( 2 );
    }

    status = clientLogin( conn );
    if ( status != 0 ) {
        rcDisconnect( conn );
        exit( 7 );
    }

    status = phybunUtil( conn, &myEnv, &myRodsArgs, &rodsPathInp );

    printErrorStack( conn->rError );
    rcDisconnect( conn );

    if ( status < 0 ) {
        exit( 3 );
    }
    else {
        exit( 0 );
    }

}

void
usage() {
    char *msgs[] = {
        "Usage : iphybun [-hK] [-D dataType] [-S srcResource] [-R resource] [-s maxSize_in_GB] [-N numOfSubFiles] collection ... ",
        "iphybun allows system admin to physically bundle files in a collection into",
        "a number of tar files to make it more efficient to store these files on tape.",
        "The tar files are placed into the /myZone/bundle/.... collection with file",
        "names - collection.aRandomNumber. A new tar file will be created whenever",
        "the number of subfiles exceeds 5120 (default value or the value given by",
        "the -N option) or the total size of the subfiles exceeds 4 GBytes (default value or the value given by",
        "the -s option).",
        "A replica is registered for each bundled sub-files with",
        "a fictitious resource - 'bundleResc' and a physical file path pointing to",
        "the logical path of the tar bundle file. Whenever this copy of the subfile",
        "is accessed, the tar file is untarred and staged automatically to the ",
        "'cache' resource. Each extracted file is registered as a replica of its",
        "corresponding subfiles.",
        " ",
        "A tar bundle file can be replicated or trimmed independently from its",
        "corresponding subfiles. But it cannot be renamed or moved to trash.",
        "It can be removed with the 'irm -f' command. But this  will trigger the ",
        "staging of the subfiles before the tar file is removed.",
        "The -R flag specifies the resource of the bundle tar file. This input is",
        "mandatory. The input resource must be a 'cache' type resource."

        "Options are:",
        " -D  dataType - the target struct file dataType. Valid dataTypes are -",
        "     t|tar|'tar file' for tar file, g|gzip|gzipTar for gziped tar file,",
        "     b|bzip2|bzip2Tar for bzip2 file, and z|zip|zipFile for archive using",
        "     'zip'.  If -D is not specified, the default is a tar file type",
        " -N  numOfSubFiles - maximum number of subfiles that are contained in the",
        "     tar file. If this option is not given, the default value will be 5120.",
        "     Note that if this number is too high, it can cause some significant",
        "     overhead for operations like retrieving a single file within a tar file",
        "     (stage, untar and register in iRODS lots of files).",
        " -R  resource - The resource where the bundle file is located",
        " -S  srcResource - Only files in this resource will be bundled",
        " -K  compute and register checksum value for the bundled subfiles and the",
        "     bundle file.",
        " -s  maxSize_in_GB - maximum size for the tar bundle file. This is given ",
        "     in GB. If the option is not given, the default value will be 4 GBs.",
        " -h  this help",
        ""
    };
    int i;
    for ( i = 0;; i++ ) {
        if ( strlen( msgs[i] ) == 0 ) {
            break;
        }
        printf( "%s\n", msgs[i] );
    }
    printReleaseInfo( "iphybun" );
}

<commit_msg>[#2212] CID26065:<commit_after>/*** Copyright (c), The Regents of the University of California            ***
 *** For more infophybunation please refer to files in the COPYRIGHT directory ***/
/*
 * iphybun - The irods phybun utility
*/
#include "irods_client_api_table.hpp"
#include "irods_pack_table.hpp"
#include "rodsClient.hpp"
#include "parseCommandLine.hpp"
#include "rodsPath.hpp"
#include "phybunUtil.hpp"
void usage();

int
main( int argc, char **argv ) {
    int status;
    rodsEnv myEnv;
    rErrMsg_t errMsg;
    rcComm_t *conn;
    rodsArguments_t myRodsArgs;
    char *optStr;
    rodsPathInp_t rodsPathInp;

    optStr = "hD:N:KR:S:s:"; // JMC - backport 4528, 4658, 4771

    status = parseCmdLineOpt( argc, argv, optStr, 0, &myRodsArgs );
    if ( status < 0 ) {
        printf( "Use -h for help.\n" );
        exit( 1 );
    }
    if ( myRodsArgs.help == True ) {
        usage();
        exit( 0 );
    }

    if ( argc - optind <= 0 ) {
        rodsLog( LOG_ERROR, "iphybun: no input" );
        printf( "Use -h for help.\n" );
        exit( 2 );
    }

    status = getRodsEnv( &myEnv );

    if ( status < 0 ) {
        rodsLogError( LOG_ERROR, status, "main: getRodsEnv error. " );
        exit( 1 );
    }

    status = parseCmdLinePath( argc, argv, optind, &myEnv,
                               UNKNOWN_OBJ_T, NO_INPUT_T, 0, &rodsPathInp );

    if ( status < 0 ) {
        rodsLogError( LOG_ERROR, status, "main: parseCmdLinePath error. " );
        printf( "Use -h for help.\n" );
        exit( 1 );
    }

    // =-=-=-=-=-=-=-
    // initialize pluggable api table
    irods::api_entry_table&  api_tbl = irods::get_client_api_table();
    irods::pack_entry_table& pk_tbl  = irods::get_pack_table();
    init_api_table( api_tbl, pk_tbl );

    conn = rcConnect( myEnv.rodsHost, myEnv.rodsPort, myEnv.rodsUserName,
                      myEnv.rodsZone, 1, &errMsg );

    if ( conn == NULL ) {
        exit( 2 );
    }

    status = clientLogin( conn );
    if ( status != 0 ) {
        rcDisconnect( conn );
        exit( 7 );
    }

    status = phybunUtil( conn, &myEnv, &myRodsArgs, &rodsPathInp );

    printErrorStack( conn->rError );
    rcDisconnect( conn );

    if ( status < 0 ) {
        exit( 3 );
    }
    else {
        exit( 0 );
    }

}

void
usage() {
    char *msgs[] = {
        "Usage : iphybun [-hK] [-D dataType] [-S srcResource] [-R resource] [-s maxSize_in_GB] [-N numOfSubFiles] collection ... ",
        "iphybun allows system admin to physically bundle files in a collection into",
        "a number of tar files to make it more efficient to store these files on tape.",
        "The tar files are placed into the /myZone/bundle/.... collection with file",
        "names - collection.aRandomNumber. A new tar file will be created whenever",
        "the number of subfiles exceeds 5120 (default value or the value given by",
        "the -N option) or the total size of the subfiles exceeds 4 GBytes (default value or the value given by",
        "the -s option).",
        "A replica is registered for each bundled sub-files with",
        "a fictitious resource - 'bundleResc' and a physical file path pointing to",
        "the logical path of the tar bundle file. Whenever this copy of the subfile",
        "is accessed, the tar file is untarred and staged automatically to the ",
        "'cache' resource. Each extracted file is registered as a replica of its",
        "corresponding subfiles.",
        "",
        "A tar bundle file can be replicated or trimmed independently from its",
        "corresponding subfiles. But it cannot be renamed or moved to trash.",
        "It can be removed with the 'irm -f' command. But this  will trigger the ",
        "staging of the subfiles before the tar file is removed.",
        "The -R flag specifies the resource of the bundle tar file. This input is",
        "mandatory. The input resource must be a 'cache' type resource.",
        "",
        "Options are:",
        " -D  dataType - the target struct file dataType. Valid dataTypes are -",
        "     t|tar|'tar file' for tar file, g|gzip|gzipTar for gziped tar file,",
        "     b|bzip2|bzip2Tar for bzip2 file, and z|zip|zipFile for archive using",
        "     'zip'.  If -D is not specified, the default is a tar file type",
        " -N  numOfSubFiles - maximum number of subfiles that are contained in the",
        "     tar file. If this option is not given, the default value will be 5120.",
        "     Note that if this number is too high, it can cause some significant",
        "     overhead for operations like retrieving a single file within a tar file",
        "     (stage, untar and register in iRODS lots of files).",
        " -R  resource - The resource where the bundle file is located",
        " -S  srcResource - Only files in this resource will be bundled",
        " -K  compute and register checksum value for the bundled subfiles and the",
        "     bundle file.",
        " -s  maxSize_in_GB - maximum size for the tar bundle file. This is given ",
        "     in GB. If the option is not given, the default value will be 4 GBs.",
        " -h  this help",
        ""
    };
    int i;
    for ( i = 0;; i++ ) {
        if ( strlen( msgs[i] ) == 0 ) {
            break;
        }
        printf( "%s\n", msgs[i] );
    }
    printReleaseInfo( "iphybun" );
}

<|endoftext|>


<commit_before>#include "threads.h"
#include "assert.h"

#if defined(_MSC_VER)

ThreadID CreateThreadSimple(ThreadFunc func, void* arg){
	ThreadID id ={};
	id.handle = CreateThread(NULL, 0, func, arg, 0, &id.threadId);
	return id;
}

void JoinThread(ThreadID thread){
	WaitForSingleObject(thread.handle, INFINITE);
}

void CreateMutex(Mutex* mutx){
	mutx->handle = CreateMutex(NULL, false, NULL);
}

void LockMutex(Mutex* mutx){
	WaitForSingleObject(mutx->handle, INFINITE);
}

void UnlockMutex(Mutex* mutx){
	ReleaseMutex(mutx->handle);
}

void DestroyMutex(Mutex* mutx){
	CloseHandle(mutx->handle);
	mutx->handle = 0;
}

unsigned int IncrementAtomic32(volatile unsigned int* i){
	return InterlockedIncrement(i);
}

int AddAtomic32(volatile int* i, int val){
	return InterlockedAdd((volatile LONG*)i, val);
}

static_assert(sizeof(LONG) == sizeof(int), "MSVC, why...");

int CompareAndSwap32(volatile int* i, int oldVal, int newVal){
	return InterlockedCompareExchange((volatile LONG*)i, oldVal, newVal);
}

#elif defined(__APPLE__)
	// Apple specific stuff
#else

ThreadID CreateThreadSimple(ThreadFunc* func, void* arg){
	ThreadID tid = {};
    int err = pthread_create(&tid.id, NULL, func, arg);
	return tid;
}

void JoinThread(ThreadID thread){
	pthread_join(thread.id, NULL);
}

void CreateMutex(Mutex* mutx){
	pthread_mutex_init(&mutx->mutx, NULL);
}

void LockMutex(Mutex* mutx){
	pthread_mutex_lock(&mutx->mutx);
}

void UnlockMutex(Mutex* mutx){
	pthread_mutex_unlock(&mutx->mutx);
}

void DestroyMutex(Mutex* mutx){
	pthread_mutex_destroy(&mutx->mutx, NULL);
}

int IncrementAtomic32(volatile int* i){

}

int AddAtomic32(volatile int* i, int val){

}

int CompareAndSwap32(volatile int* i, int oldVal, int newVal){

}

#endif

#if defined(THREADS_TEST_MAIN)

int val1 = 0;
int val2 = 0;

THREAD_RET_TYPE ThreadFunc1(void* arg){
	int val = (int)arg;
	val1 = val;

	return 0;
}

THREAD_RET_TYPE ThreadFunc2(void* arg){
	int val = (int)arg;
	val2 = val;

	return 0;
}

static const int counterSize = 1024*32;
unsigned int counter = 0;

THREAD_RET_TYPE ThreadCounterFunc(void* arg){

	for (int i = 0; i < counterSize; i++){
		IncrementAtomic32(&counter);
	}

	return 0;
}

int main(){

	ASSERT(val1 == 0);
	ASSERT(val2 == 0);

	ThreadID id1 = CreateThreadSimple(ThreadFunc1, (void*)4);
	ThreadID id2 = CreateThreadSimple(ThreadFunc2, (void*)7);

	JoinThread(id1);
	JoinThread(id2);

	ASSERT(val1 == 4);
	ASSERT(val2 == 7);

	ASSERT(counter == 0);
	ThreadID tids[] =
	{
		CreateThreadSimple(ThreadCounterFunc, NULL),
		CreateThreadSimple(ThreadCounterFunc, NULL),
		CreateThreadSimple(ThreadCounterFunc, NULL),
		CreateThreadSimple(ThreadCounterFunc, NULL),
		CreateThreadSimple(ThreadCounterFunc, NULL),
		CreateThreadSimple(ThreadCounterFunc, NULL)
	};

	for (int i = 0; i < BNS_ARRAY_COUNT(tids); i++){
		JoinThread(tids[i]);
	}

	ASSERT(counter == counterSize * BNS_ARRAY_COUNT(tids));

	return 0;
}

#endif
<commit_msg>Threads in linux.<commit_after>#include "threads.h"
#include "assert.h"

#if defined(_MSC_VER)

ThreadID CreateThreadSimple(ThreadFunc func, void* arg){
	ThreadID id ={};
	id.handle = CreateThread(NULL, 0, func, arg, 0, &id.threadId);
	return id;
}

void JoinThread(ThreadID thread){
	WaitForSingleObject(thread.handle, INFINITE);
}

void CreateMutex(Mutex* mutx){
	mutx->handle = CreateMutex(NULL, false, NULL);
}

void LockMutex(Mutex* mutx){
	WaitForSingleObject(mutx->handle, INFINITE);
}

void UnlockMutex(Mutex* mutx){
	ReleaseMutex(mutx->handle);
}

void DestroyMutex(Mutex* mutx){
	CloseHandle(mutx->handle);
	mutx->handle = 0;
}

unsigned int IncrementAtomic32(volatile unsigned int* i){
	return InterlockedIncrement(i);
}

int AddAtomic32(volatile int* i, int val){
	return InterlockedAdd((volatile LONG*)i, val);
}

static_assert(sizeof(LONG) == sizeof(int), "MSVC, why...");

int CompareAndSwap32(volatile int* i, int oldVal, int newVal){
	return InterlockedCompareExchange((volatile LONG*)i, oldVal, newVal);
}

#elif defined(__APPLE__)
	// Apple specific stuff
#else

ThreadID CreateThreadSimple(ThreadFunc func, void* arg){
	ThreadID tid = {};
    int err = pthread_create(&tid.id, NULL, func, arg);
	return tid;
}

void JoinThread(ThreadID thread){
	pthread_join(thread.id, NULL);
}

void CreateMutex(Mutex* mutx){
	pthread_mutex_init(&mutx->mutx, NULL);
}

void LockMutex(Mutex* mutx){
	pthread_mutex_lock(&mutx->mutx);
}

void UnlockMutex(Mutex* mutx){
	pthread_mutex_unlock(&mutx->mutx);
}

void DestroyMutex(Mutex* mutx){
	pthread_mutex_destroy(&mutx->mutx);
}

unsigned int IncrementAtomic32(volatile unsigned int* i){
	return __sync_fetch_and_add(i, 1);
}

int AddAtomic32(volatile int* i, int val){
	return __sync_fetch_and_add(i, val);
}

int CompareAndSwap32(volatile int* i, int oldVal, int newVal){
	return __sync_val_compare_and_swap(i, oldVal, newVal);
}

#endif

#if defined(THREADS_TEST_MAIN)

int val1 = 0;
int val2 = 0;

THREAD_RET_TYPE ThreadFunc1(void* arg){
	int val = (int)(size_t)arg;
	val1 = val;

	return 0;
}

THREAD_RET_TYPE ThreadFunc2(void* arg){
	int val = (int)(size_t)arg;
	val2 = val;

	return 0;
}

static const int counterSize = 1024*32;
unsigned int counter = 0;

THREAD_RET_TYPE ThreadCounterFunc(void* arg){

	for (int i = 0; i < counterSize; i++){
		IncrementAtomic32(&counter);
	}

	return 0;
}

int main(){

	ASSERT(val1 == 0);
	ASSERT(val2 == 0);

	ThreadID id1 = CreateThreadSimple(ThreadFunc1, (void*)4);
	ThreadID id2 = CreateThreadSimple(ThreadFunc2, (void*)7);

	JoinThread(id1);
	JoinThread(id2);

	ASSERT(val1 == 4);
	ASSERT(val2 == 7);

	ASSERT(counter == 0);
	ThreadID tids[] =
	{
		CreateThreadSimple(ThreadCounterFunc, NULL),
		CreateThreadSimple(ThreadCounterFunc, NULL),
		CreateThreadSimple(ThreadCounterFunc, NULL),
		CreateThreadSimple(ThreadCounterFunc, NULL),
		CreateThreadSimple(ThreadCounterFunc, NULL),
		CreateThreadSimple(ThreadCounterFunc, NULL)
	};

	for (int i = 0; i < BNS_ARRAY_COUNT(tids); i++){
		JoinThread(tids[i]);
	}

	ASSERT(counter == counterSize * BNS_ARRAY_COUNT(tids));

	return 0;
}

#endif
<|endoftext|>