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

#ifndef _SV_IMPFONT_HXX
#define _SV_IMPFONT_HXX

#include <tools/gen.hxx>
#include <tools/string.hxx>
#include <i18npool/lang.h>
#include <tools/color.hxx>
#include <vcl/dllapi.h>
#include <vcl/vclenum.hxx>
#include <vcl/fntstyle.hxx>

// ------------
// - Impl_Font -
// ------------

class Impl_Font
{
public:
             Impl_Font();
             Impl_Font( const Impl_Font& );

    bool     operator==( const Impl_Font& ) const;

    FontPitch           GetPitch()      { if(mePitch==PITCH_DONTKNOW)    AskConfig(); return mePitch; }
    FontFamily          GetFamily()     { if(meFamily==FAMILY_DONTKNOW)  AskConfig(); return meFamily; }
    FontItalic          GetItalic()     { if(meItalic==ITALIC_DONTKNOW)  AskConfig(); return meItalic; }
    FontWeight          GetWeight()     { if(meWeight==WEIGHT_DONTKNOW)  AskConfig(); return meWeight; }
    FontWidth           GetWidthType()  { if(meWidthType==WIDTH_DONTKNOW)AskConfig(); return meWidthType; }

private:
    friend class Font;
    void                AskConfig();

    int                 mnRefCount;
    String              maFamilyName;
    String              maStyleName;
    Size                maSize;
    Color               maColor;        // compatibility, now on output device
    Color               maFillColor;    // compatibility, now on output device
    rtl_TextEncoding    meCharSet;
    LanguageType        meLanguage;
    LanguageType        meCJKLanguage;
    FontFamily          meFamily;
    FontPitch           mePitch;
    TextAlign           meAlign;
    FontWeight          meWeight;
    FontWidth           meWidthType;
    FontItalic          meItalic;
    FontUnderline       meUnderline;
    FontUnderline       meOverline;
    FontStrikeout       meStrikeout;
    FontRelief          meRelief;
    FontEmphasisMark    meEmphasisMark;
    FontType            meType;         // used by metrics only
    short               mnOrientation;
    FontKerning         mnKerning;
    BOOL                mbWordLine:1,
                        mbOutline:1,
                        mbConfigLookup:1,   // there was a config lookup
                        mbShadow:1,
                        mbVertical:1,
                        mbTransparent:1;    // compatibility, now on output device

    friend SvStream&    operator>>( SvStream& rIStm, Impl_Font& );
    friend SvStream&    operator<<( SvStream& rOStm, const Impl_Font& );
};

// ------------------
// - ImplFontMetric -
// ------------------

class ImplFontMetric
{
    friend class OutputDevice;

private:
    long    mnAscent;      // Ascent
    long    mnDescent;     // Descent
    long    mnIntLeading;  // Internal Leading
    long    mnExtLeading;  // External Leading
    long    mnLineHeight;  // Ascent+Descent+EmphasisMark
    long    mnSlant;       // Slant
    USHORT  mnMiscFlags;   // Misc Flags
    UINT32  mnRefCount;    // Reference Counter

    enum { DEVICE_FLAG=1, SCALABLE_FLAG=2, LATIN_FLAG=4, CJK_FLAG=8, CTL_FLAG=16 };

public:
            ImplFontMetric();
    void    AddReference();
    void    DeReference();

    long    GetAscent() const       { return mnAscent; }
    long    GetDescent() const      { return mnDescent; }
    long    GetIntLeading() const   { return mnIntLeading; }
    long    GetExtLeading() const   { return mnExtLeading; }
    long    GetLineHeight() const   { return mnLineHeight; }
    long    GetSlant() const        { return mnSlant; }

    bool    IsDeviceFont() const    { return ((mnMiscFlags & DEVICE_FLAG) != 0); }
    bool    IsScalable() const      { return ((mnMiscFlags & SCALABLE_FLAG) != 0); }
    bool    SupportsLatin() const   { return ((mnMiscFlags & LATIN_FLAG) != 0); }
    bool    SupportsCJK() const     { return ((mnMiscFlags & CJK_FLAG) != 0); }
    bool    SupportsCTL() const     { return ((mnMiscFlags & CTL_FLAG) != 0); }

    bool    operator==( const ImplFontMetric& ) const;
};

// ------------------
// - ImplFontHints -
// ------------------

class ImplFontOptions
{
public:
    FontEmbeddedBitmap meEmbeddedBitmap; // whether the embedded bitmaps should be used
    FontAntiAlias      meAntiAlias;      // whether the font should be antialiased
    FontAutoHint       meAutoHint;       // whether the font should be autohinted
    FontHinting        meHinting;        // whether the font should be hinted
    FontHintStyle      meHintStyle;      // type of font hinting to be used
public:
    ImplFontOptions() :
        meEmbeddedBitmap(EMBEDDEDBITMAP_DONTKNOW),
        meAntiAlias(ANTIALIAS_DONTKNOW),
        meAutoHint(AUTOHINT_DONTKNOW),
        meHinting(HINTING_DONTKNOW),
        meHintStyle(HINT_SLIGHT)
    {}
    ImplFontOptions( FontEmbeddedBitmap eEmbeddedBitmap, FontAntiAlias eAntiAlias,
        FontAutoHint eAutoHint, FontHinting eHinting, FontHintStyle eHintStyle) :
        meEmbeddedBitmap(eEmbeddedBitmap),
        meAntiAlias(eAntiAlias),
        meAutoHint(eAutoHint),
        meHinting(eHinting),
        meHintStyle(eHintStyle)
    {}
    FontAutoHint GetUseAutoHint() const { return meAutoHint; }
    FontHintStyle GetHintStyle() const { return meHintStyle; }
    bool DontUseEmbeddedBitmaps() const { return meEmbeddedBitmap == EMBEDDEDBITMAP_FALSE; }
    bool DontUseAntiAlias() const { return meAntiAlias == ANTIALIAS_FALSE; }
    bool DontUseHinting() const { return (meHinting == HINTING_FALSE) || (GetHintStyle() == HINT_NONE); }
};

// -------------------
// - ImplFontCharMap -
// -------------------

class CmapResult;

class VCL_DLLPUBLIC ImplFontCharMap
{
public:
   explicit             ImplFontCharMap( const CmapResult& );

    static ImplFontCharMap* GetDefaultMap( bool bSymbols=false);

    bool                IsDefaultMap() const;
    bool                HasChar( sal_uInt32 ) const;
    int                 CountCharsInRange( sal_uInt32 cMin, sal_uInt32 cMax ) const;
    int                 GetCharCount() const;

    sal_uInt32          GetFirstChar() const;
    sal_uInt32          GetLastChar() const;

    sal_uInt32          GetNextChar( sal_uInt32 ) const;
    sal_uInt32          GetPrevChar( sal_uInt32 ) const;

    int                 GetIndexFromChar( sal_uInt32 ) const;
    sal_uInt32          GetCharFromIndex( int ) const;

    void                AddReference();
    void                DeReference();

    int                 GetGlyphIndex( sal_uInt32 ) const;

private:
    /*virtual*/         ~ImplFontCharMap();
    int                 ImplFindRangeIndex( sal_uInt32 ) const;

    // prevent assignment and copy construction
    explicit            ImplFontCharMap( const ImplFontCharMap& );
    void                operator=( const ImplFontCharMap& );

private:
    const sal_uInt32*   mpRangeCodes;     // pairs of StartCode/(EndCode+1)
    const int*          mpStartGlyphs;    // range-specific mapper to glyphs
    const USHORT*       mpGlyphIds;       // individual glyphid mappings
    int                 mnRangeCount;
    int                 mnCharCount;
    int                 mnRefCount;
};

// CmapResult is a normalized version of the many CMAP formats
class
#ifdef UNX
    VCL_DLLPUBLIC // vcl-plugins need it
#endif // UNX
CmapResult
{
public:
    explicit    CmapResult( bool bSymbolic = false,
                    const sal_uInt32* pRangeCodes = NULL, int nRangeCount = 0,
                    const int* pStartGlyphs = 0, const USHORT* pGlyphIds = NULL );

    const sal_uInt32* mpRangeCodes;
    const int*        mpStartGlyphs;
    const USHORT*     mpGlyphIds;
    int               mnRangeCount;
    bool              mbSymbolic;
    bool              mbRecoded;
};

bool ParseCMAP( const unsigned char* pRawData, int nRawLength, CmapResult& );

#endif // _SV_IMPFONT_HXX

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

#ifndef _SV_IMPFONT_HXX
#define _SV_IMPFONT_HXX

#include <tools/gen.hxx>
#include <tools/string.hxx>
#include <i18npool/lang.h>
#include <tools/color.hxx>
#include <vcl/dllapi.h>
#include <vcl/vclenum.hxx>
#include <vcl/fntstyle.hxx>

// ------------
// - Impl_Font -
// ------------

class Impl_Font
{
public:
             Impl_Font();
             Impl_Font( const Impl_Font& );

    bool     operator==( const Impl_Font& ) const;

    FontPitch           GetPitch()      { if(mePitch==PITCH_DONTKNOW)    AskConfig(); return mePitch; }
    FontFamily          GetFamily()     { if(meFamily==FAMILY_DONTKNOW)  AskConfig(); return meFamily; }
    FontItalic          GetItalic()     { if(meItalic==ITALIC_DONTKNOW)  AskConfig(); return meItalic; }
    FontWeight          GetWeight()     { if(meWeight==WEIGHT_DONTKNOW)  AskConfig(); return meWeight; }
    FontWidth           GetWidthType()  { if(meWidthType==WIDTH_DONTKNOW)AskConfig(); return meWidthType; }

private:
    friend class Font;
    void                AskConfig();

    int                 mnRefCount;
    String              maFamilyName;
    String              maStyleName;
    Size                maSize;
    Color               maColor;        // compatibility, now on output device
    Color               maFillColor;    // compatibility, now on output device
    rtl_TextEncoding    meCharSet;
    LanguageType        meLanguage;
    LanguageType        meCJKLanguage;
    FontFamily          meFamily;
    FontPitch           mePitch;
    TextAlign           meAlign;
    FontWeight          meWeight;
    FontWidth           meWidthType;
    FontItalic          meItalic;
    FontUnderline       meUnderline;
    FontUnderline       meOverline;
    FontStrikeout       meStrikeout;
    FontRelief          meRelief;
    FontEmphasisMark    meEmphasisMark;
    FontType            meType;         // used by metrics only
    short               mnOrientation;
    FontKerning         mnKerning;
    BOOL                mbWordLine:1,
                        mbOutline:1,
                        mbConfigLookup:1,   // there was a config lookup
                        mbShadow:1,
                        mbVertical:1,
                        mbTransparent:1;    // compatibility, now on output device

    friend SvStream&    operator>>( SvStream& rIStm, Impl_Font& );
    friend SvStream&    operator<<( SvStream& rOStm, const Impl_Font& );
};

// ------------------
// - ImplFontMetric -
// ------------------

class ImplFontMetric
{
    friend class OutputDevice;

private:
    long    mnAscent;      // Ascent
    long    mnDescent;     // Descent
    long    mnIntLeading;  // Internal Leading
    long    mnExtLeading;  // External Leading
    long    mnLineHeight;  // Ascent+Descent+EmphasisMark
    long    mnSlant;       // Slant
    USHORT  mnMiscFlags;   // Misc Flags
    UINT32  mnRefCount;    // Reference Counter

    enum { DEVICE_FLAG=1, SCALABLE_FLAG=2, LATIN_FLAG=4, CJK_FLAG=8, CTL_FLAG=16 };

public:
            ImplFontMetric();
    void    AddReference();
    void    DeReference();

    long    GetAscent() const       { return mnAscent; }
    long    GetDescent() const      { return mnDescent; }
    long    GetIntLeading() const   { return mnIntLeading; }
    long    GetExtLeading() const   { return mnExtLeading; }
    long    GetLineHeight() const   { return mnLineHeight; }
    long    GetSlant() const        { return mnSlant; }

    bool    IsDeviceFont() const    { return ((mnMiscFlags & DEVICE_FLAG) != 0); }
    bool    IsScalable() const      { return ((mnMiscFlags & SCALABLE_FLAG) != 0); }
    bool    SupportsLatin() const   { return ((mnMiscFlags & LATIN_FLAG) != 0); }
    bool    SupportsCJK() const     { return ((mnMiscFlags & CJK_FLAG) != 0); }
    bool    SupportsCTL() const     { return ((mnMiscFlags & CTL_FLAG) != 0); }

    bool    operator==( const ImplFontMetric& ) const;
};

// ------------------
// - ImplFontHints -
// ------------------

class ImplFontOptions
{
public:
    FontEmbeddedBitmap meEmbeddedBitmap; // whether the embedded bitmaps should be used
    FontAntiAlias      meAntiAlias;      // whether the font should be antialiased
    FontAutoHint       meAutoHint;       // whether the font should be autohinted
    FontHinting        meHinting;        // whether the font should be hinted
    FontHintStyle      meHintStyle;      // type of font hinting to be used
public:
    ImplFontOptions() :
        meEmbeddedBitmap(EMBEDDEDBITMAP_DONTKNOW),
        meAntiAlias(ANTIALIAS_DONTKNOW),
        meAutoHint(AUTOHINT_DONTKNOW),
        meHinting(HINTING_DONTKNOW),
        meHintStyle(HINT_SLIGHT)
    {}
    ImplFontOptions( FontEmbeddedBitmap eEmbeddedBitmap, FontAntiAlias eAntiAlias,
        FontAutoHint eAutoHint, FontHinting eHinting, FontHintStyle eHintStyle) :
        meEmbeddedBitmap(eEmbeddedBitmap),
        meAntiAlias(eAntiAlias),
        meAutoHint(eAutoHint),
        meHinting(eHinting),
        meHintStyle(eHintStyle)
    {}
    FontAutoHint GetUseAutoHint() const { return meAutoHint; }
    FontHintStyle GetHintStyle() const { return meHintStyle; }
    bool DontUseEmbeddedBitmaps() const { return meEmbeddedBitmap == EMBEDDEDBITMAP_FALSE; }
    bool DontUseAntiAlias() const { return meAntiAlias == ANTIALIAS_FALSE; }
    bool DontUseHinting() const { return (meHinting == HINTING_FALSE) || (GetHintStyle() == HINT_NONE); }
};

// -------------------
// - ImplFontCharMap -
// -------------------

class CmapResult;

class VCL_DLLPUBLIC ImplFontCharMap
{
public:
    explicit             ImplFontCharMap( const CmapResult& );
    virtual              ~ImplFontCharMap();

    static ImplFontCharMap* GetDefaultMap( bool bSymbols=false);

    bool                IsDefaultMap() const;
    bool                HasChar( sal_uInt32 ) const;
    int                 CountCharsInRange( sal_uInt32 cMin, sal_uInt32 cMax ) const;
    int                 GetCharCount() const;

    sal_uInt32          GetFirstChar() const;
    sal_uInt32          GetLastChar() const;

    sal_uInt32          GetNextChar( sal_uInt32 ) const;
    sal_uInt32          GetPrevChar( sal_uInt32 ) const;

    int                 GetIndexFromChar( sal_uInt32 ) const;
    sal_uInt32          GetCharFromIndex( int ) const;

    void                AddReference();
    void                DeReference();

    int                 GetGlyphIndex( sal_uInt32 ) const;

private:
    int                 ImplFindRangeIndex( sal_uInt32 ) const;

    // prevent assignment and copy construction
    explicit            ImplFontCharMap( const ImplFontCharMap& );
    void                operator=( const ImplFontCharMap& );

private:
    const sal_uInt32*   mpRangeCodes;     // pairs of StartCode/(EndCode+1)
    const int*          mpStartGlyphs;    // range-specific mapper to glyphs
    const USHORT*       mpGlyphIds;       // individual glyphid mappings
    int                 mnRangeCount;
    int                 mnCharCount;
    int                 mnRefCount;
};

// CmapResult is a normalized version of the many CMAP formats
class
#ifdef UNX
    VCL_DLLPUBLIC // vcl-plugins need it
#endif // UNX
CmapResult
{
public:
    explicit    CmapResult( bool bSymbolic = false,
                    const sal_uInt32* pRangeCodes = NULL, int nRangeCount = 0,
                    const int* pStartGlyphs = 0, const USHORT* pGlyphIds = NULL );

    const sal_uInt32* mpRangeCodes;
    const int*        mpStartGlyphs;
    const USHORT*     mpGlyphIds;
    int               mnRangeCount;
    bool              mbSymbolic;
    bool              mbRecoded;
};

bool ParseCMAP( const unsigned char* pRawData, int nRawLength, CmapResult& );

#endif // _SV_IMPFONT_HXX

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: i18n_im.hxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 20:39:26 $
 *
 *  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 _SAL_I18N_INPUTMETHOD_HXX
#define _SAL_I18N_INPUTMETHOD_HXX

#ifndef _VCL_DLLAPI_H
#include <vcl/dllapi.h>
#endif

extern "C" char* GetMethodName( XIMStyle nStyle, char *pBuf, int nBufSize);

#define bUseInputMethodDefault True

class VCL_DLLPUBLIC SalI18N_InputMethod
{
    Bool        mbUseable;  // system supports locale as well as status
                            // and preedit style ?
    Bool        mbMultiLingual; // system supports iiimp
    XIM         maMethod;
    XIMCallback maDestroyCallback;
    XIMStyles  *mpStyles;

public:

    Bool        IsMultiLingual()        { return mbMultiLingual;    }
    Bool        PosixLocale();
    Bool        UseMethod()             { return mbUseable; }
    XIM         GetMethod()             { return maMethod;  }
    void        HandleDestroyIM();
    Bool        CreateMethod( Display *pDisplay );
    XIMStyles  *GetSupportedStyles()    { return mpStyles;  }
    Bool        SetLocale( const char* pLocale = "" );
    Bool        FilterEvent( XEvent *pEvent, XLIB_Window window );
    Bool        AddConnectionWatch (Display *pDisplay, void *pConnectionHandler);

    #ifdef _USE_PRINT_EXTENSION_
    void            Invalidate()                    { mbUseable = False; }
    #endif

    SalI18N_InputMethod();
    ~SalI18N_InputMethod();
};

#endif // _SAL_I18N_INPUTMETHOD_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.14.248); FILE MERGED 2008/04/01 13:01:53 thb 1.14.248.2: #i85898# Stripping all external header guards 2008/03/28 15:45:15 rt 1.14.248.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: i18n_im.hxx,v $
 * $Revision: 1.15 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SAL_I18N_INPUTMETHOD_HXX
#define _SAL_I18N_INPUTMETHOD_HXX

#include <vcl/dllapi.h>

extern "C" char* GetMethodName( XIMStyle nStyle, char *pBuf, int nBufSize);

#define bUseInputMethodDefault True

class VCL_DLLPUBLIC SalI18N_InputMethod
{
    Bool        mbUseable;  // system supports locale as well as status
                            // and preedit style ?
    Bool        mbMultiLingual; // system supports iiimp
    XIM         maMethod;
    XIMCallback maDestroyCallback;
    XIMStyles  *mpStyles;

public:

    Bool        IsMultiLingual()        { return mbMultiLingual;    }
    Bool        PosixLocale();
    Bool        UseMethod()             { return mbUseable; }
    XIM         GetMethod()             { return maMethod;  }
    void        HandleDestroyIM();
    Bool        CreateMethod( Display *pDisplay );
    XIMStyles  *GetSupportedStyles()    { return mpStyles;  }
    Bool        SetLocale( const char* pLocale = "" );
    Bool        FilterEvent( XEvent *pEvent, XLIB_Window window );
    Bool        AddConnectionWatch (Display *pDisplay, void *pConnectionHandler);

    #ifdef _USE_PRINT_EXTENSION_
    void            Invalidate()                    { mbUseable = False; }
    #endif

    SalI18N_InputMethod();
    ~SalI18N_InputMethod();
};

#endif // _SAL_I18N_INPUTMETHOD_HXX

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: saldata.hxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: rt $ $Date: 2005-03-29 13:00:24 $
 *
 *  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 _SV_SALDATA_HXX
#define _SV_SALDATA_HXX

// -=-= includes -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include <signal.h>

#ifndef _SALSTD_HXX
#include <salstd.hxx>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_SALWTYPE_HXX
#include <salwtype.hxx>
#endif
#ifndef _SV_SALINST_H
#include <salinst.h>
#endif
#ifndef _OSL_MODULE_H
#include <osl/module.h>
#endif

#ifndef _VCL_DLLAPI_H
#include <dllapi.h>
#endif

// -=-= forwards -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
class SalXLib;
class SalDisplay;
class SalFrame;
class SalPrinter;

// -=-= typedefs -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

DECLARE_LIST( SalDisplays, SalDisplay* )

#if defined SCO || defined LINUX || defined NETBSD || defined AIX || defined HPUX || defined FREEBSD || defined MACOSX
#include <pthread.h>
#else
typedef unsigned int pthread_t;
#endif

// -=-= SalData =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
class VCL_DLLPUBLIC SalData
{
protected:
            BOOL                bNoExceptions_;

            SalXLib            *pXLib_;

            SalDisplay         *m_pSalDisplay;

            pthread_t           hMainThread_;

public:
            SalInstance*        pInstance_;         // pointer to instance
            oslModule           m_pPlugin; // plugin library handle
public:
    SalData();
    virtual ~SalData();

    virtual void            Init();
    virtual void            initNWF();
    virtual void            deInitNWF();

    inline  void            XError( Display     *pDisplay, XErrorEvent *pEvent ) const;

    SalDisplay*             GetDisplay() const
    { return m_pSalDisplay; }
    void                    SetSalDisplay( SalDisplay* pDisplay )
    { m_pSalDisplay = pDisplay; }

    void                    DeleteDisplay(); // for shutdown

    inline  SalXLib*        GetLib() const { return pXLib_; }
    inline  pthread_t       GetMainThread() const { return hMainThread_; }

    void                    StartTimer( ULONG nMS );
    inline  void            StopTimer();
    void                    Timeout() const;

    static int XErrorHdl( Display*, XErrorEvent* );
    static int XIOErrorHdl( Display* );

    // set helper functions to set class and res name in W_CLASS hint
    static const char* getFrameResName();
    static const char* getFrameClassName();

};

// -=-= inlines =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
inline void SetSalData( SalData* pData )
{ ImplGetSVData()->mpSalData = (void*)pData; }

inline SalData* GetSalData()
{ return (SalData*)ImplGetSVData()->mpSalData; }

#ifdef _SV_SALDISP_HXX
inline void SalData::XError( Display *pDisplay, XErrorEvent *pEvent ) const
{ pXLib_->XError( pDisplay, pEvent ); }
#endif

class YieldMutexReleaser
{
    ULONG               m_nYieldCount;
public:
    inline YieldMutexReleaser();
    inline ~YieldMutexReleaser();
};

inline YieldMutexReleaser::YieldMutexReleaser()
{
    m_nYieldCount = GetSalData()->pInstance_->ReleaseYieldMutex();
}

inline YieldMutexReleaser::~YieldMutexReleaser()
{
    GetSalData()->pInstance_->AcquireYieldMutex( m_nYieldCount );
}

#endif // _SV_SALDATA_HXX

<commit_msg>INTEGRATION: CWS ooo19126 (1.12.180); FILE MERGED 2005/09/05 14:45:28 rt 1.12.180.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: saldata.hxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 12:43:33 $
 *
 *  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 _SV_SALDATA_HXX
#define _SV_SALDATA_HXX

// -=-= includes -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include <signal.h>

#ifndef _SALSTD_HXX
#include <salstd.hxx>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_SALWTYPE_HXX
#include <salwtype.hxx>
#endif
#ifndef _SV_SALINST_H
#include <salinst.h>
#endif
#ifndef _OSL_MODULE_H
#include <osl/module.h>
#endif

#ifndef _VCL_DLLAPI_H
#include <dllapi.h>
#endif

// -=-= forwards -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
class SalXLib;
class SalDisplay;
class SalFrame;
class SalPrinter;

// -=-= typedefs -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

DECLARE_LIST( SalDisplays, SalDisplay* )

#if defined SCO || defined LINUX || defined NETBSD || defined AIX || defined HPUX || defined FREEBSD || defined MACOSX
#include <pthread.h>
#else
typedef unsigned int pthread_t;
#endif

// -=-= SalData =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
class VCL_DLLPUBLIC SalData
{
protected:
            BOOL                bNoExceptions_;

            SalXLib            *pXLib_;

            SalDisplay         *m_pSalDisplay;

            pthread_t           hMainThread_;

public:
            SalInstance*        pInstance_;         // pointer to instance
            oslModule           m_pPlugin; // plugin library handle
public:
    SalData();
    virtual ~SalData();

    virtual void            Init();
    virtual void            initNWF();
    virtual void            deInitNWF();

    inline  void            XError( Display     *pDisplay, XErrorEvent *pEvent ) const;

    SalDisplay*             GetDisplay() const
    { return m_pSalDisplay; }
    void                    SetSalDisplay( SalDisplay* pDisplay )
    { m_pSalDisplay = pDisplay; }

    void                    DeleteDisplay(); // for shutdown

    inline  SalXLib*        GetLib() const { return pXLib_; }
    inline  pthread_t       GetMainThread() const { return hMainThread_; }

    void                    StartTimer( ULONG nMS );
    inline  void            StopTimer();
    void                    Timeout() const;

    static int XErrorHdl( Display*, XErrorEvent* );
    static int XIOErrorHdl( Display* );

    // set helper functions to set class and res name in W_CLASS hint
    static const char* getFrameResName();
    static const char* getFrameClassName();

};

// -=-= inlines =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
inline void SetSalData( SalData* pData )
{ ImplGetSVData()->mpSalData = (void*)pData; }

inline SalData* GetSalData()
{ return (SalData*)ImplGetSVData()->mpSalData; }

#ifdef _SV_SALDISP_HXX
inline void SalData::XError( Display *pDisplay, XErrorEvent *pEvent ) const
{ pXLib_->XError( pDisplay, pEvent ); }
#endif

class YieldMutexReleaser
{
    ULONG               m_nYieldCount;
public:
    inline YieldMutexReleaser();
    inline ~YieldMutexReleaser();
};

inline YieldMutexReleaser::YieldMutexReleaser()
{
    m_nYieldCount = GetSalData()->pInstance_->ReleaseYieldMutex();
}

inline YieldMutexReleaser::~YieldMutexReleaser()
{
    GetSalData()->pInstance_->AcquireYieldMutex( m_nYieldCount );
}

#endif // _SV_SALDATA_HXX

<|endoftext|>


<commit_before>/*!
  \copyright (c) RDO-Team, 2003-2012
  \file      app/rdo_studio_mfc/src/model/model_view.cpp
  \author      (rdo@rk9.bmstu.ru)
  \date      20.02.2003
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
#include "app/rdo_studio_mfc/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
#include <boost/bind.hpp>
#include <QtGui/qevent.h>
#include <QtGui/qboxlayout.h>
// ----------------------------------------------------------------------- SYNOPSIS
#include "app/rdo_studio_mfc/src/model/model_view.h"
#include "app/rdo_studio_mfc/src/application.h"
#include "app/rdo_studio_mfc/src/main_windows_base.h"
#include "app/rdo_studio_mfc/edit_ctrls/rdofindedit.h"
#include "app/rdo_studio_mfc/rdo_edit/rdoeditortabctrl.h"
#include "app/rdo_studio_mfc/resource.h"
#include "app/rdo_studio_mfc/src/main_frm.h"
// --------------------------------------------------------------------------------

using namespace rdoEditor;

// --------------------------------------------------------------------------------
// -------------------- RDOStudioModelView
// --------------------------------------------------------------------------------
RDOStudioModelView::RDOStudioModelView(PTR(QWidget) pParent)
	: parent_type(pParent)
	, m_pModel     (NULL)
	, m_pTabCtrl   (NULL)
	, m_pFindDialog(NULL)
{
	m_pTabCtrl = new RDOEditorTabCtrl(this, this);

	PTR(QVBoxLayout) pLayout = new QVBoxLayout(this);
	pLayout->setSpacing(0);
	pLayout->setContentsMargins(0, 0, 0, 0);
	pLayout->addWidget(m_pTabCtrl);

	RDOStudioMainFrame* pMainWindow = studioApp.getMainWndUI();
	ASSERT(pMainWindow);
	pMainWindow->actSearchFindInModel->setEnabled(true);
	connect(pMainWindow->actSearchFindInModel, SIGNAL(triggered(bool)), this, SLOT(onSearchFindInModel()));
}

RDOStudioModelView::~RDOStudioModelView()
{
	RDOStudioMainFrame* pMainWindow = studioApp.getMainWndUI();
	ASSERT(pMainWindow);
	pMainWindow->actSearchFindInModel->setEnabled(false);
	disconnect(pMainWindow->actSearchFindInModel, SIGNAL(triggered(bool)), this, SLOT(onSearchFindInModel()));
}

void RDOStudioModelView::setModel(PTR(RDOStudioModel) pModel)
{
	ASSERT(m_pModel != pModel);
	m_pModel = pModel;
}

void RDOStudioModelView::closeEvent(PTR(QCloseEvent) event)
{
	if (m_pModel)
	{
		if (m_pModel->closeModel())
		{
			event->accept();
		}
		else
		{
			event->ignore();
		}
	}
}

REF(rdoEditor::RDOEditorTabCtrl) RDOStudioModelView::getTab()
{
	return *m_pTabCtrl;
}

void RDOStudioModelView::onSearchFindInModel()
{
	m_findSettings.what = m_pTabCtrl->getCurrentEdit()->getWordForFind();

	if (!m_pFindDialog)
	{
		m_pFindDialog = new FindDialog(
			this,
			boost::bind(&RDOStudioModelView::onFindDlgFind, this, _1),
			boost::bind(&RDOStudioModelView::onFindDlgClose, this)
		);
	}

	m_pFindDialog->setSettings(m_findSettings);
	m_pFindDialog->show();
	m_pFindDialog->raise();
	m_pFindDialog->activateWindow();
}

void RDOStudioModelView::onFindDlgFind(CREF(FindDialog::Settings) settings)
{
	m_findSettings = settings;
	onSearchFindAll();
}

void RDOStudioModelView::onFindDlgClose()
{
	m_pFindDialog = NULL;
}

void RDOStudioModelView::onSearchFindAll()
{
	studioApp.getIMainWnd()->getDockFind().clear();
	studioApp.getIMainWnd()->getDockFind().raise();
	tstring findStr       = m_findSettings.what;
	rbool bMatchCase      = m_findSettings.matchCase;
	rbool bMatchWholeWord = m_findSettings.matchWholeWord;
	studioApp.getIMainWnd()->getDockFind().getContext().setKeyword(findStr, bMatchCase);
	studioApp.getIMainWnd()->getDockFind().appendString(rdo::format(ID_FINDINMODEL_BEGINMSG, findStr.c_str()));
	int count = 0;
	for (int i = 0; i < m_pTabCtrl->count(); i++)
	{
		PTR(RDOEditorEdit) pEdit = m_pTabCtrl->getItemEdit(i);
		int pos  = 0;
		int line = 0;
		while (pos != -1)
		{
			pos = pEdit->findPos(findStr, line, bMatchCase, bMatchWholeWord);
			if (pos != -1)
			{
				line = pEdit->getLineFromPosition(pos);
				studioApp.getIMainWnd()->getDockFind().appendString(pEdit->getLine(line), m_pTabCtrl->indexToType(i), line, pos - pEdit->getPositionFromLine(line));
				line++;
				count++;
			}
		}
	}
	m_pFindDialog = NULL;
	tstring s = count
		? rdo::format(ID_FINDINMODEL_ENDMSG_COUNT,    count)
		: rdo::format(ID_FINDINMODEL_ENDMSG_NOTFOUND, findStr.c_str());
	studioApp.getIMainWnd()->getDockFind().appendString(s);
}<commit_msg> - исправлено позиционирование при поиске в модели<commit_after>/*!
  \copyright (c) RDO-Team, 2003-2012
  \file      app/rdo_studio_mfc/src/model/model_view.cpp
  \author      (rdo@rk9.bmstu.ru)
  \date      20.02.2003
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
#include "app/rdo_studio_mfc/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
#include <boost/bind.hpp>
#include <QtGui/qevent.h>
#include <QtGui/qboxlayout.h>
// ----------------------------------------------------------------------- SYNOPSIS
#include "app/rdo_studio_mfc/src/model/model_view.h"
#include "app/rdo_studio_mfc/src/application.h"
#include "app/rdo_studio_mfc/src/main_windows_base.h"
#include "app/rdo_studio_mfc/edit_ctrls/rdofindedit.h"
#include "app/rdo_studio_mfc/rdo_edit/rdoeditortabctrl.h"
#include "app/rdo_studio_mfc/resource.h"
#include "app/rdo_studio_mfc/src/main_frm.h"
// --------------------------------------------------------------------------------

using namespace rdoEditor;

// --------------------------------------------------------------------------------
// -------------------- RDOStudioModelView
// --------------------------------------------------------------------------------
RDOStudioModelView::RDOStudioModelView(PTR(QWidget) pParent)
	: parent_type(pParent)
	, m_pModel     (NULL)
	, m_pTabCtrl   (NULL)
	, m_pFindDialog(NULL)
{
	m_pTabCtrl = new RDOEditorTabCtrl(this, this);

	PTR(QVBoxLayout) pLayout = new QVBoxLayout(this);
	pLayout->setSpacing(0);
	pLayout->setContentsMargins(0, 0, 0, 0);
	pLayout->addWidget(m_pTabCtrl);

	RDOStudioMainFrame* pMainWindow = studioApp.getMainWndUI();
	ASSERT(pMainWindow);
	pMainWindow->actSearchFindInModel->setEnabled(true);
	connect(pMainWindow->actSearchFindInModel, SIGNAL(triggered(bool)), this, SLOT(onSearchFindInModel()));
}

RDOStudioModelView::~RDOStudioModelView()
{
	RDOStudioMainFrame* pMainWindow = studioApp.getMainWndUI();
	ASSERT(pMainWindow);
	pMainWindow->actSearchFindInModel->setEnabled(false);
	disconnect(pMainWindow->actSearchFindInModel, SIGNAL(triggered(bool)), this, SLOT(onSearchFindInModel()));
}

void RDOStudioModelView::setModel(PTR(RDOStudioModel) pModel)
{
	ASSERT(m_pModel != pModel);
	m_pModel = pModel;
}

void RDOStudioModelView::closeEvent(PTR(QCloseEvent) event)
{
	if (m_pModel)
	{
		if (m_pModel->closeModel())
		{
			event->accept();
		}
		else
		{
			event->ignore();
		}
	}
}

REF(rdoEditor::RDOEditorTabCtrl) RDOStudioModelView::getTab()
{
	return *m_pTabCtrl;
}

void RDOStudioModelView::onSearchFindInModel()
{
	m_findSettings.what = m_pTabCtrl->getCurrentEdit()->getWordForFind();

	if (!m_pFindDialog)
	{
		m_pFindDialog = new FindDialog(
			this,
			boost::bind(&RDOStudioModelView::onFindDlgFind, this, _1),
			boost::bind(&RDOStudioModelView::onFindDlgClose, this)
		);
	}

	m_pFindDialog->setSettings(m_findSettings);
	m_pFindDialog->show();
	m_pFindDialog->raise();
	m_pFindDialog->activateWindow();
}

void RDOStudioModelView::onFindDlgFind(CREF(FindDialog::Settings) settings)
{
	m_findSettings = settings;
	onSearchFindAll();
}

void RDOStudioModelView::onFindDlgClose()
{
	m_pFindDialog = NULL;
}

void RDOStudioModelView::onSearchFindAll()
{
	studioApp.getIMainWnd()->getDockFind().clear();
	studioApp.getIMainWnd()->getDockFind().raise();
	tstring findStr       = m_findSettings.what;
	rbool bMatchCase      = m_findSettings.matchCase;
	rbool bMatchWholeWord = m_findSettings.matchWholeWord;
	studioApp.getIMainWnd()->getDockFind().getContext().setKeyword(findStr, bMatchCase);
	studioApp.getIMainWnd()->getDockFind().appendString(rdo::format(ID_FINDINMODEL_BEGINMSG, findStr.c_str()));
	int count = 0;
	for (int i = 0; i < m_pTabCtrl->count(); i++)
	{
		PTR(RDOEditorEdit) pEdit = m_pTabCtrl->getItemEdit(i);
		int pos  = 0;
		int line = 0;
		while (pos != -1)
		{
			pos = pEdit->findPos(findStr, line, bMatchCase, bMatchWholeWord);
			if (pos != -1)
			{
				pEdit->setCurrentPos(pos);
				tstring newfindStr = pEdit->getCurrentWord();
				pos = pEdit->findPos(newfindStr, line, bMatchCase, bMatchWholeWord);
				line = pEdit->getLineFromPosition(pos);
				studioApp.getIMainWnd()->getDockFind().appendString(pEdit->getLine(line), m_pTabCtrl->indexToType(i), line, pos - pEdit->getPositionFromLine(line) + newfindStr.length());
				line++;
				count++;
			}
		}
	}
	m_pFindDialog = NULL;
	tstring s = count
		? rdo::format(ID_FINDINMODEL_ENDMSG_COUNT,    count)
		: rdo::format(ID_FINDINMODEL_ENDMSG_NOTFOUND, findStr.c_str());
	studioApp.getIMainWnd()->getDockFind().appendString(s);
}<|endoftext|>


<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.

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

Bohrium 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 Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.
*/

#include <vector>
#include <iostream>
#include <boost/functional/hash.hpp>
#include <iomanip>

#include <jitk/kernel.hpp>

#include "engine_cuda.hpp"

using namespace std;
namespace fs = boost::filesystem;

namespace bohrium {

static boost::hash<string> hasher;

EngineCUDA::EngineCUDA(const ConfigParser &config, jitk::Statistics &stat) :
                                    work_group_size_1dx(config.defaultGet<int>("work_group_size_1dx", 128)),
                                    work_group_size_2dx(config.defaultGet<int>("work_group_size_2dx", 32)),
                                    work_group_size_2dy(config.defaultGet<int>("work_group_size_2dy", 4)),
                                    work_group_size_3dx(config.defaultGet<int>("work_group_size_3dx", 32)),
                                    work_group_size_3dy(config.defaultGet<int>("work_group_size_3dy", 2)),
                                    work_group_size_3dz(config.defaultGet<int>("work_group_size_3dz", 2)),
                                    compile_flg(config.defaultGet<string>("compiler_flg", "")),
                                    default_device_type(config.defaultGet<string>("device_type", "auto")),
                                    platform_no(config.defaultGet<int>("platform_no", -1)),
                                    verbose(config.defaultGet<bool>("verbose", false)),
                                    stat(stat),
                                    prof(config.defaultGet<bool>("prof", false)),
                                    tmp_dir(fs::temp_directory_path() / fs::unique_path("bohrium_%%%%")),
                                    source_dir(tmp_dir / "src"),
                                    object_dir(tmp_dir / "obj"),
                                    compiler(config.defaultGet<string>("compiler_cmd", "nvcc"),
                                             config.defaultGet<string>("compiler_inc", ""),
                                             config.defaultGet<string>("compiler_lib", ""),
                                             config.defaultGet<string>("compiler_flg", ""),
                                             config.defaultGet<string>("compiler_ext", ""))
{
    size_t     totalGlobalMem;
    int deviceCount = 0;
    CUresult err = cuInit(0);
    int major = 0, minor = 0;

    if (err == CUDA_SUCCESS)
        checkCudaErrors(cuDeviceGetCount(&deviceCount));

    if (deviceCount == 0) {
        fprintf(stderr, "Error: no devices supporting CUDA\n");
        exit(-1);
    }

    // get first CUDA device
    checkCudaErrors(cuDeviceGet(&device, 0));
    char name[100];
    cuDeviceGetName(name, 100, device);
    printf("> Using device 0: %s\n", name);

    // get compute capabilities and the devicename
    checkCudaErrors( cuDeviceComputeCapability(&major, &minor, device) );
    printf("> GPU Device has SM %d.%d compute capability\n", major, minor);

    checkCudaErrors( cuDeviceTotalMem(&totalGlobalMem, device) );
    printf("  Total amount of global memory:   %llu bytes\n",
           (unsigned long long)totalGlobalMem);
    printf("  64-bit Memory Address:           %s\n",
           (totalGlobalMem > (unsigned long long)4*1024*1024*1024L)?
           "YES" : "NO");

    err = cuCtxCreate(&context, 0, device);
    if (err != CUDA_SUCCESS) {
        fprintf(stderr, "* Error initializing the CUDA context.\n");
        cuCtxDetach(context);
        exit(-1);
    }

    // Let's make sure that the directories exist
    fs::create_directories(source_dir);
    fs::create_directories(object_dir);
}

pair<tuple<uint32_t, uint32_t, uint32_t>, tuple<uint32_t, uint32_t, uint32_t> > EngineCUDA::NDRanges(const vector<const jitk::LoopB*> &threaded_blocks) const {
    const auto &b = threaded_blocks;
    switch (b.size()) {
        case 1: {
            const auto gsize_and_lsize = jitk::work_ranges(work_group_size_1dx, b[0]->size);
            return make_pair(make_tuple(gsize_and_lsize.first, 1, 1), make_tuple(gsize_and_lsize.second, 1, 1));
        }
        case 2: {
            const auto gsize_and_lsize_x = jitk::work_ranges(work_group_size_2dx, b[0]->size);
            const auto gsize_and_lsize_y = jitk::work_ranges(work_group_size_2dy, b[1]->size);
            return make_pair(make_tuple(gsize_and_lsize_x.first, gsize_and_lsize_y.first, 1),
                             make_tuple(gsize_and_lsize_x.second, gsize_and_lsize_y.second, 1));
        }
        case 3: {
            const auto gsize_and_lsize_x = jitk::work_ranges(work_group_size_3dx, b[0]->size);
            const auto gsize_and_lsize_y = jitk::work_ranges(work_group_size_3dy, b[1]->size);
            const auto gsize_and_lsize_z = jitk::work_ranges(work_group_size_3dz, b[2]->size);
            return make_pair(make_tuple(gsize_and_lsize_x.first, gsize_and_lsize_y.first, gsize_and_lsize_z.first),
                             make_tuple(gsize_and_lsize_x.second, gsize_and_lsize_y.second, gsize_and_lsize_z.second));
        }
        default:
            throw runtime_error("NDRanges: maximum of three dimensions!");
    }
}

void EngineCUDA::execute(const std::string &source, const jitk::Kernel &kernel,
                           const vector<const jitk::LoopB*> &threaded_blocks,
                           const vector<const bh_view*> &offset_strides,
                           const vector<const bh_instruction*> &constants) {
    size_t hash = hasher(source);
    ++stat.kernel_cache_lookups;
    CUfunction program;

    auto tcompile = chrono::steady_clock::now();

    // Do we have the program already?
    if (_programs.find(hash) != _programs.end()) {
        program = _programs.at(hash);
    } else {
        // Or do we have to compile it
        ++stat.kernel_cache_misses;

        // The object file path
        fs::path objfile = object_dir / jitk::hash_filename(hash, ".cubin");

        // Write the source file and compile it (reading from disk)
        // TODO: make nvcc read directly from stdin
        {
            fs::path srcfile = jitk::write_source2file(source, source_dir, hash, ".cu", verbose);
            compiler.compile(objfile.string(), srcfile.string());
        }
        /* else {
            // Pipe the source directly into the compiler thus no source file is written
            compiler.compile(objfile.string(), source.c_str(), source.size());
        }
       */

        CUmodule module;
        CUresult err = cuModuleLoad(&module, objfile.string().c_str());
        if (err != CUDA_SUCCESS) {
            cout << "Error loading the module " << objfile.string() << " CODE: " << err << endl;
            cuCtxDetach(context);
            throw runtime_error("cuModuleLoad() failed");
        }

        err = cuModuleGetFunction(&program, module, "execute");
        if (err != CUDA_SUCCESS) {
            cout << "Error getting kernel function 'execute' CODE: " << err << endl;
            cuCtxDetach(context);
            throw runtime_error("cuModuleGetFunction() failed");
        }
        _programs[hash] = program;
    }
    stat.time_compile += chrono::steady_clock::now() - tcompile;

    // Let's execute the CUDA kernel
    vector<void *> args;

    for (bh_base *base: kernel.getNonTemps()) { // NB: the iteration order matters!
        args.push_back(getBuffer(base));
    }

    for (const bh_view *view: offset_strides) {
        args.push_back((void*)&view->start);
        for (int j=0; j<view->ndim; ++j) {
            args.push_back((void*)&view->stride[j]);
        }
    }

    auto texec = chrono::steady_clock::now();

    tuple<uint32_t, uint32_t, uint32_t> blocks, threads;
    tie(blocks, threads) = NDRanges(threaded_blocks);

    checkCudaErrors(cuLaunchKernel(program,
                                   get<0>(blocks), get<1>(blocks), get<2>(blocks),  // NxNxN blocks
                                   get<0>(threads), get<1>(threads), get<2>(threads),  // NxNxN threads
                                   0, 0, &args[0], 0));

    stat.time_exec += chrono::steady_clock::now() - texec;
}

void EngineCUDA::set_constructor_flag(std::vector<bh_instruction*> &instr_list) {
    jitk::util_set_constructor_flag(instr_list, buffers);
}

std::string EngineCUDA::info() const {

    char device_name[1000];
    cuDeviceGetName(device_name, 1000, device);
    int major = 0, minor = 0;
    checkCudaErrors(cuDeviceComputeCapability(&major, &minor, device));
    size_t totalGlobalMem;
    checkCudaErrors(cuDeviceTotalMem(&totalGlobalMem, device));

    stringstream ss;
    ss << "----"                                                                        << "\n";
    ss << "CUDA:"                                                                       << "\n";
    ss << "  Device: \"" << device_name << " (SM " << major << "." << minor << " compute capability)\"\n";
    ss << "  Memory: \"" <<totalGlobalMem / 1024 / 1024 << " MB\"\n";
    return ss.str();
}

} // bohrium
<commit_msg>cuda: added some error messages<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.

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

Bohrium 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 Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.
*/

#include <vector>
#include <iostream>
#include <boost/functional/hash.hpp>
#include <iomanip>

#include <jitk/kernel.hpp>

#include "engine_cuda.hpp"

using namespace std;
namespace fs = boost::filesystem;

namespace bohrium {

static boost::hash<string> hasher;

EngineCUDA::EngineCUDA(const ConfigParser &config, jitk::Statistics &stat) :
                                    work_group_size_1dx(config.defaultGet<int>("work_group_size_1dx", 128)),
                                    work_group_size_2dx(config.defaultGet<int>("work_group_size_2dx", 32)),
                                    work_group_size_2dy(config.defaultGet<int>("work_group_size_2dy", 4)),
                                    work_group_size_3dx(config.defaultGet<int>("work_group_size_3dx", 32)),
                                    work_group_size_3dy(config.defaultGet<int>("work_group_size_3dy", 2)),
                                    work_group_size_3dz(config.defaultGet<int>("work_group_size_3dz", 2)),
                                    compile_flg(config.defaultGet<string>("compiler_flg", "")),
                                    default_device_type(config.defaultGet<string>("device_type", "auto")),
                                    platform_no(config.defaultGet<int>("platform_no", -1)),
                                    verbose(config.defaultGet<bool>("verbose", false)),
                                    stat(stat),
                                    prof(config.defaultGet<bool>("prof", false)),
                                    tmp_dir(fs::temp_directory_path() / fs::unique_path("bohrium_%%%%")),
                                    source_dir(tmp_dir / "src"),
                                    object_dir(tmp_dir / "obj"),
                                    compiler(config.defaultGet<string>("compiler_cmd", "nvcc"),
                                             config.defaultGet<string>("compiler_inc", ""),
                                             config.defaultGet<string>("compiler_lib", ""),
                                             config.defaultGet<string>("compiler_flg", ""),
                                             config.defaultGet<string>("compiler_ext", ""))
{
    size_t totalGlobalMem;
    int deviceCount = 0;
    CUresult err = cuInit(0);
    int major = 0, minor = 0;

    if (err == CUDA_SUCCESS)
        checkCudaErrors(cuDeviceGetCount(&deviceCount));

    if (deviceCount == 0) {
        fprintf(stderr, "Error: no devices supporting CUDA\n");
        exit(-1);
    }

    // get first CUDA device
    checkCudaErrors(cuDeviceGet(&device, 0));
    char name[100];
    cuDeviceGetName(name, 100, device);
    printf("> Using device 0: %s\n", name);

    // get compute capabilities and the device name
    checkCudaErrors(cuDeviceComputeCapability(&major, &minor, device));
    printf("> GPU Device has SM %d.%d compute capability\n", major, minor);

    checkCudaErrors(cuDeviceTotalMem(&totalGlobalMem, device));
    printf("  Total amount of global memory:   %llu bytes\n", (unsigned long long)totalGlobalMem);
    printf("  64-bit Memory Address:           %s\n",
           (totalGlobalMem > (unsigned long long)4*1024*1024*1024L)? "YES" : "NO");

    err = cuCtxCreate(&context, 0, device);
    if (err != CUDA_SUCCESS) {
        fprintf(stderr, "* Error initializing the CUDA context.\n");
        cuCtxDetach(context);
        exit(-1);
    }

    // Let's make sure that the directories exist
    fs::create_directories(source_dir);
    fs::create_directories(object_dir);
}

pair<tuple<uint32_t, uint32_t, uint32_t>, tuple<uint32_t, uint32_t, uint32_t> > EngineCUDA::NDRanges(const vector<const jitk::LoopB*> &threaded_blocks) const {
    const auto &b = threaded_blocks;
    switch (b.size()) {
        case 1: {
            const auto gsize_and_lsize = jitk::work_ranges(work_group_size_1dx, b[0]->size);
            return make_pair(make_tuple(gsize_and_lsize.first, 1, 1), make_tuple(gsize_and_lsize.second, 1, 1));
        }
        case 2: {
            const auto gsize_and_lsize_x = jitk::work_ranges(work_group_size_2dx, b[0]->size);
            const auto gsize_and_lsize_y = jitk::work_ranges(work_group_size_2dy, b[1]->size);
            return make_pair(make_tuple(gsize_and_lsize_x.first, gsize_and_lsize_y.first, 1),
                             make_tuple(gsize_and_lsize_x.second, gsize_and_lsize_y.second, 1));
        }
        case 3: {
            const auto gsize_and_lsize_x = jitk::work_ranges(work_group_size_3dx, b[0]->size);
            const auto gsize_and_lsize_y = jitk::work_ranges(work_group_size_3dy, b[1]->size);
            const auto gsize_and_lsize_z = jitk::work_ranges(work_group_size_3dz, b[2]->size);
            return make_pair(make_tuple(gsize_and_lsize_x.first, gsize_and_lsize_y.first, gsize_and_lsize_z.first),
                             make_tuple(gsize_and_lsize_x.second, gsize_and_lsize_y.second, gsize_and_lsize_z.second));
        }
        default:
            throw runtime_error("NDRanges: maximum of three dimensions!");
    }
}

void EngineCUDA::execute(const std::string &source, const jitk::Kernel &kernel,
                           const vector<const jitk::LoopB*> &threaded_blocks,
                           const vector<const bh_view*> &offset_strides,
                           const vector<const bh_instruction*> &constants) {
    size_t hash = hasher(source);
    ++stat.kernel_cache_lookups;
    CUfunction program;

    auto tcompile = chrono::steady_clock::now();

    // Do we have the program already?
    if (_programs.find(hash) != _programs.end()) {
        program = _programs.at(hash);
    } else {
        // Or do we have to compile it
        ++stat.kernel_cache_misses;

        // The object file path
        fs::path objfile = object_dir / jitk::hash_filename(hash, ".cubin");

        // Write the source file and compile it (reading from disk)
        // TODO: make nvcc read directly from stdin
        {
            fs::path srcfile = jitk::write_source2file(source, source_dir, hash, ".cu", verbose);
            compiler.compile(objfile.string(), srcfile.string());
        }
        /* else {
            // Pipe the source directly into the compiler thus no source file is written
            compiler.compile(objfile.string(), source.c_str(), source.size());
        }
       */

        CUmodule module;
        CUresult err = cuModuleLoad(&module, objfile.string().c_str());
        if (err != CUDA_SUCCESS) {
            const char *err_name, *err_desc;
            cuGetErrorName(err, &err_name);
            cuGetErrorString(err, &err_desc);
            cout << "Error loading the module \"" << objfile.string()
                 << "\", " << err_name << ": \"" << err_desc << "\"." << endl;
            cuCtxDetach(context);
            throw runtime_error("cuModuleLoad() failed");
        }

        err = cuModuleGetFunction(&program, module, "execute");
        if (err != CUDA_SUCCESS) {
            const char *err_name, *err_desc;
            cuGetErrorName(err, &err_name);
            cuGetErrorString(err, &err_desc);
            cout << "Error getting kernel function 'execute' \"" << objfile.string()
                 << "\", " << err_name << ": \"" << err_desc << "\"." << endl;
            throw runtime_error("cuModuleGetFunction() failed");
        }
        _programs[hash] = program;
    }
    stat.time_compile += chrono::steady_clock::now() - tcompile;

    // Let's execute the CUDA kernel
    vector<void *> args;

    for (bh_base *base: kernel.getNonTemps()) { // NB: the iteration order matters!
        args.push_back(getBuffer(base));
    }

    for (const bh_view *view: offset_strides) {
        args.push_back((void*)&view->start);
        for (int j=0; j<view->ndim; ++j) {
            args.push_back((void*)&view->stride[j]);
        }
    }

    auto texec = chrono::steady_clock::now();

    tuple<uint32_t, uint32_t, uint32_t> blocks, threads;
    tie(blocks, threads) = NDRanges(threaded_blocks);

    checkCudaErrors(cuLaunchKernel(program,
                                   get<0>(blocks), get<1>(blocks), get<2>(blocks),  // NxNxN blocks
                                   get<0>(threads), get<1>(threads), get<2>(threads),  // NxNxN threads
                                   0, 0, &args[0], 0));

    stat.time_exec += chrono::steady_clock::now() - texec;
}

void EngineCUDA::set_constructor_flag(std::vector<bh_instruction*> &instr_list) {
    jitk::util_set_constructor_flag(instr_list, buffers);
}

std::string EngineCUDA::info() const {

    char device_name[1000];
    cuDeviceGetName(device_name, 1000, device);
    int major = 0, minor = 0;
    checkCudaErrors(cuDeviceComputeCapability(&major, &minor, device));
    size_t totalGlobalMem;
    checkCudaErrors(cuDeviceTotalMem(&totalGlobalMem, device));

    stringstream ss;
    ss << "----"                                                                        << "\n";
    ss << "CUDA:"                                                                       << "\n";
    ss << "  Device: \"" << device_name << " (SM " << major << "." << minor << " compute capability)\"\n";
    ss << "  Memory: \"" <<totalGlobalMem / 1024 / 1024 << " MB\"\n";
    return ss.str();
}

} // bohrium
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <random>
#include <chrono>
#include <string>
#include <utility>

#include "os/task_system_t.h"
#include "os/generator.h"
#include "lib/pinput.h"
#include "lib/io.h"
#include "lib/exception.h"
#include "lib/ansi.h"

template<typename O, typename U, typename N, typename P, typename V, typename S>
void fill_parameters(const O& options, U& u, N& n, P& p_min, P& p_max, V& s, S& file_name, bool& open){

	typename O::const_iterator it;

	if(((it = options.find("-u")) != options.end() || (it = options.find("--utilization")) != options.end()) && it->second.size() > 0){
		u = std::stod(it->second[0]);
	}
	else throw lib::exception("Cannot find -u option");

	if((it = options.find("-n")) != options.end() && it->second.size() > 0){
		n = std::stoul(it->second[0]);
	}
	else throw lib::exception("Cannot find -n option");

	if((it = options.find("-p")) != options.end() || (it = options.find("--period")) != options.end()){
		if(it->second.size() > 0){
			p_min = p_max = std::stoul(it->second[0]);
			if(it->second.size() > 1){
				p_max = std::stoul(it->second[1]);
			}
			if(p_min > p_max) std::swap(p_min, p_max);
		}
	}

	if(((it = options.find("-s")) != options.end() || (it = options.find("--seed")) != options.end()) && it->second.size() > 0){
		for(auto& x : it->second) s.push_back(std::stoll(x));
	}

	if((it = options.find("-o")) != options.end() || (it = options.find("--output")) != options.end()){
		if(it->second.size() > 0){
			file_name = it->second[0];
			open = true;
		}
	}

}

template<typename U, typename N, typename P>
void check_parameters(U& u, N& n, P& p_min, P& /*p_max*/){
	if(n > p_min) throw lib::exception("n > p_min");
	if(u * p_min < n) throw lib::exception("u < n/p_min");
}

void help(){
	std::cout << " - flags" << std::endl << std::endl;
	std::cout << "   " << "[-h | --help]" << std::endl;
	std::cout << "   " << "[-v | --verbose]" << std::endl << std::endl;
	std::cout << " - mandatory parameters" << std::endl << std::endl;
	std::cout << "   " << "[-u | --utilization] #0 (double >= 0)" << std::endl;
	std::cout << "   " << "-n #0 (int >= 0)" << std::endl << std::endl;
	std::cout << " - optional parameters" << std::endl << std::endl;
	std::cout << "   " << "[-p | --period] #0 [#1] (int[2], #1 >= #0)" << std::endl;
	std::cout << "   " << "[-s | --seed  ] #0 (uint)" << std::endl;
	std::cout << "   " << "[-o | --output] #0 (string)" << std::endl << std::endl;
}

int main(int argc, char* argv[]){

	try{

		std::vector<std::string> params;
		std::map<std::string, std::vector<std::string>> options;
		std::set<std::string> flags;
		std::set<std::string> option_set = {
			"-u", "--utilization",
			"-n",
			"-p", "--period",
			"-s", "--seed",
			"-o", "--output"
		};
		std::set<std::string> flag_set = {
			"-h", "--help",
			"-v", "--verbose",
			"--nocolor"
		};

		pinput::parse(argc, argv, params, options, flags, option_set, flag_set);

		const bool show_help = flags.count("-h") || flags.count("--help");
		if(show_help){
			help();
			return 0;
		}

		const bool verbose = flags.count("-v") || flags.count("--verbose");
		const bool nocolor = flags.count("--nocolor");

		const char* vcolor = (nocolor)? "" : ansi::blue;
		const char* rcolor = (nocolor)? "" : ansi::reset;

		double u;
		uint n;
		uint p_min = 50;
		uint p_max = 100;
		std::vector<long long> seed_v;

		std::string file_name;
		bool open = false;

		fill_parameters(options, u, n, p_min, p_max, seed_v, file_name, open);
		check_parameters(u, n, p_min, p_max);

		if(seed_v.size() == 0) seed_v.push_back(std::chrono::system_clock::now().time_since_epoch().count());

		os::task_system_t task_system;

		std::seed_seq seed(seed_v.begin(), seed_v.end());
		std::default_random_engine generator(seed);
		std::uniform_real_distribution<double> usage_distribution(0.0,1.0);
		std::uniform_int_distribution<uint> period_distribution(p_min,p_max);
		os::generate_task_system(generator, usage_distribution, period_distribution, u, n, task_system);

		//WRITE OUTPUT

		std::streambuf* buffer;
		std::ofstream ofstream;

		if(open){
			ofstream.open(file_name);
			buffer = ofstream.rdbuf();
		}
		else{
			buffer = std::cout.rdbuf();
		}

		std::ostream ostream(buffer);

		ostream << task_system;

		if(open) ofstream.close();

		if(verbose){
			double t = 0;
			for(auto task : task_system){
				t += (double)task.wcet/(double)task.period;
			}

			std::cout << vcolor << std::endl;
			std::cout << "u = " << t << std::endl;
			std::cout.precision(2);
			std::cout << std::fixed;
			std::cout << "abs error = " << (u - t)*100 << "%" << std::endl;
			std::cout << "rel error = " << (1 - t/u)*100 << "%" << std::endl;
			std::cout << "worst abs error that could happen = " << (100./p_min*n) << "%" << std::endl;
			std::cout << rcolor;
		}

	}
	catch(const std::exception& e){
		std::cout << "error -> " << e.what() << std::endl;
		return 1;
	}

	return 0;
}<commit_msg>taskGen ecolor<commit_after>#include <iostream>
#include <fstream>
#include <random>
#include <chrono>
#include <string>
#include <utility>

#include "os/task_system_t.h"
#include "os/generator.h"
#include "lib/pinput.h"
#include "lib/io.h"
#include "lib/exception.h"
#include "lib/ansi.h"

template<typename O, typename U, typename N, typename P, typename V, typename S>
void fill_parameters(const O& options, U& u, N& n, P& p_min, P& p_max, V& s, S& file_name, bool& open){

	typename O::const_iterator it;

	if(((it = options.find("-u")) != options.end() || (it = options.find("--utilization")) != options.end()) && it->second.size() > 0){
		u = std::stod(it->second[0]);
	}
	else throw lib::exception("Cannot find -u option");

	if((it = options.find("-n")) != options.end() && it->second.size() > 0){
		n = std::stoul(it->second[0]);
	}
	else throw lib::exception("Cannot find -n option");

	if((it = options.find("-p")) != options.end() || (it = options.find("--period")) != options.end()){
		if(it->second.size() > 0){
			p_min = p_max = std::stoul(it->second[0]);
			if(it->second.size() > 1){
				p_max = std::stoul(it->second[1]);
			}
			if(p_min > p_max) std::swap(p_min, p_max);
		}
	}

	if(((it = options.find("-s")) != options.end() || (it = options.find("--seed")) != options.end()) && it->second.size() > 0){
		for(auto& x : it->second) s.push_back(std::stoll(x));
	}

	if((it = options.find("-o")) != options.end() || (it = options.find("--output")) != options.end()){
		if(it->second.size() > 0){
			file_name = it->second[0];
			open = true;
		}
	}

}

template<typename U, typename N, typename P>
void check_parameters(U& u, N& n, P& p_min, P& /*p_max*/){
	if(n > p_min) throw lib::exception("n > p_min");
	if(u * p_min < n) throw lib::exception("u < n/p_min");
}

void help(){
	std::cout << " - flags" << std::endl << std::endl;
	std::cout << "   " << "[-h | --help]" << std::endl;
	std::cout << "   " << "[-v | --verbose]" << std::endl << std::endl;
	std::cout << " - mandatory parameters" << std::endl << std::endl;
	std::cout << "   " << "[-u | --utilization] #0 (double >= 0)" << std::endl;
	std::cout << "   " << "-n #0 (int >= 0)" << std::endl << std::endl;
	std::cout << " - optional parameters" << std::endl << std::endl;
	std::cout << "   " << "[-p | --period] #0 [#1] (int[2], #1 >= #0)" << std::endl;
	std::cout << "   " << "[-s | --seed  ] #0 (uint)" << std::endl;
	std::cout << "   " << "[-o | --output] #0 (string)" << std::endl << std::endl;
}

int main(int argc, char* argv[]){

	std::vector<std::string> params;
	std::map<std::string, std::vector<std::string>> options;
	std::set<std::string> flags;
	std::set<std::string> option_set = {
		"-u", "--utilization",
		"-n",
		"-p", "--period",
		"-s", "--seed",
		"-o", "--output"
	};
	std::set<std::string> flag_set = {
		"-h", "--help",
		"-v", "--verbose",
		"--nocolor"
	};

	pinput::parse(argc, argv, params, options, flags, option_set, flag_set);

	const bool nocolor = flags.count("--nocolor");

	const char* vcolor = (nocolor)? "" : ansi::blue;
	const char* ecolor = (nocolor)? "" : ansi::red;
	const char* rcolor = (nocolor)? "" : ansi::reset;

	const bool show_help = flags.count("-h") || flags.count("--help");
	if(show_help){
		help();
		return 0;
	}

	const bool verbose = flags.count("-v") || flags.count("--verbose");

	try{

		double u;
		uint n;
		uint p_min = 50;
		uint p_max = 100;
		std::vector<long long> seed_v;

		std::string file_name;
		bool open = false;

		fill_parameters(options, u, n, p_min, p_max, seed_v, file_name, open);
		check_parameters(u, n, p_min, p_max);

		if(seed_v.size() == 0) seed_v.push_back(std::chrono::system_clock::now().time_since_epoch().count());

		os::task_system_t task_system;

		std::seed_seq seed(seed_v.begin(), seed_v.end());
		std::default_random_engine generator(seed);
		std::uniform_real_distribution<double> usage_distribution(0.0,1.0);
		std::uniform_int_distribution<uint> period_distribution(p_min,p_max);
		os::generate_task_system(generator, usage_distribution, period_distribution, u, n, task_system);

		//WRITE OUTPUT

		std::streambuf* buffer;
		std::ofstream ofstream;

		if(open){
			ofstream.open(file_name);
			buffer = ofstream.rdbuf();
		}
		else{
			buffer = std::cout.rdbuf();
		}

		std::ostream ostream(buffer);

		ostream << task_system;

		if(open) ofstream.close();

		if(verbose){
			double t = 0;
			for(auto task : task_system){
				t += (double)task.wcet/(double)task.period;
			}

			std::cout << vcolor << std::endl;
			std::cout << "u = " << t << std::endl;
			std::cout.precision(2);
			std::cout << std::fixed;
			std::cout << "abs error = " << (u - t)*100 << "%" << std::endl;
			std::cout << "rel error = " << (1 - t/u)*100 << "%" << std::endl;
			std::cout << "worst abs error that could happen = " << (100./p_min*n) << "%" << std::endl;
			std::cout << rcolor;
		}

	}
	catch(const std::exception& e){
		std::cout << ecolor << "error -> " << e.what() << rcolor << std::endl;
		return 1;
	}

	return 0;
}<|endoftext|>


<commit_before>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "analysisresult.h"
#include <strigi/strigiconfig.h>
#include "indexwriter.h"
#include "analyzerconfiguration.h"
#include "streamanalyzer.h"
#include "streambase.h"
#include "textutils.h"
#include "strigi_thread.h"
#include <string>
#include <cstdlib>
#include <iconv.h>

#include <iostream>
#include <map>

#ifdef ICONV_SECOND_ARGUMENT_IS_CONST
     #define ICONV_CONST const
#else
     #define ICONV_CONST
#endif

using namespace Strigi;
using namespace std;

class Latin1Converter {
    iconv_t const conv;
    char* out;
    size_t outlen;
    STRIGI_MUTEX_DEFINE(mutex);

    int32_t _fromLatin1(char*& out, const char* data, size_t len);
    Latin1Converter() :conv(iconv_open("UTF-8", "ISO-8859-1")), outlen(0) {
        STRIGI_MUTEX_INIT(&mutex);
    }
    ~Latin1Converter() {
        iconv_close(conv);
        free(out);
        STRIGI_MUTEX_DESTROY(&mutex);
    }
    static Latin1Converter& converter() {
        static Latin1Converter l;
        return l;
    }
public:
    static int32_t fromLatin1(char*& out, const char* data, int32_t len) {
        return converter()._fromLatin1(out, data, len);
    }
    static void lock() {
        STRIGI_MUTEX_LOCK(&converter().mutex);
    }
    static void unlock() {
        STRIGI_MUTEX_UNLOCK(&converter().mutex);
    }
};
int32_t
Latin1Converter::_fromLatin1(char*& o, const char* data, size_t len) {
    size_t l = 3*len;
    if (outlen < l) {
        out = (char*)realloc(out, l);
        outlen = l;
    } else {
        l = outlen;
    }
    o = out;
    ICONV_CONST char* inp = (char*)data;
    char* outp = out;
    iconv(conv, &inp, &len, &outp, &l);
    return (len == 0) ?outlen-l :0;
}

class AnalysisResult::Private {
public:
    int64_t m_id;
    mutable void* m_writerData;
    const time_t m_mtime;
    std::string m_name;
    const std::string m_path;
    std::string m_encoding;
    std::string m_mimetype;
    IndexWriter& m_writer;
    const int m_depth;
    StreamAnalyzer& m_indexer;
    AnalyzerConfiguration& m_analyzerconfig;
    AnalysisResult* const m_parent;
    const StreamEndAnalyzer* m_endanalyzer;
    std::map<const Strigi::RegisteredField*, int> occurences;

    Private(const std::string& p, const char* name, time_t mt,
        AnalysisResult& parent);
    Private(const std::string& p, time_t mt, IndexWriter& w,
        StreamAnalyzer& indexer);

    bool checkCardinality(const RegisteredField* field);
};

AnalysisResult::Private::Private(const std::string& p, const char* name,
        time_t mt, AnalysisResult& parent)
            :m_writerData(0), m_mtime(mt), m_name(name), m_path(p),
             m_writer(parent.p->m_writer), m_depth(parent.depth()+1),
             m_indexer(parent.p->m_indexer),
             m_analyzerconfig(parent.p->m_analyzerconfig), m_parent(&parent),
             m_endanalyzer(0) {
}
AnalysisResult::AnalysisResult(const std::string& path, const char* name,
        time_t mt, AnalysisResult& parent)
        :p(new Private(path, name, mt, parent)) {
    p->m_writer.startAnalysis(this);
}
AnalysisResult::Private::Private(const std::string& p, time_t mt,
        IndexWriter& w, StreamAnalyzer& indexer)
            :m_writerData(0), m_mtime(mt), m_path(p), m_writer(w), m_depth(0),
             m_indexer(indexer), m_analyzerconfig(indexer.configuration()),
             m_parent(0), m_endanalyzer(0) {
    size_t pos = m_path.rfind('/');
    if (pos == std::string::npos) {
        m_name = m_path;
    } else {
        m_name = m_path.substr(pos+1);
    }
}
AnalysisResult::AnalysisResult(const std::string& path, time_t mt,
        IndexWriter& w, StreamAnalyzer& indexer)
            :p(new Private(path, mt, w, indexer)) {
    p->m_writer.startAnalysis(this);
}
AnalysisResult::~AnalysisResult() {
    p->m_writer.finishAnalysis(this);
    delete p;
}
const std::string& AnalysisResult::fileName() const { return p->m_name; }
const std::string& AnalysisResult::path() const { return p->m_path; }
time_t AnalysisResult::mTime() const { return p->m_mtime; }
char AnalysisResult::depth() const { return p->m_depth; }
int64_t AnalysisResult::id() const { return p->m_id; }
void AnalysisResult::setId(int64_t i) { p->m_id = i; }
void AnalysisResult::setEncoding(const char* enc) { p->m_encoding = enc; }
const std::string& AnalysisResult::encoding() const { return p->m_encoding; }
void* AnalysisResult::writerData() const { return p->m_writerData; }
void AnalysisResult::setWriterData(void* wd) const { p->m_writerData = wd; }
void AnalysisResult::setMimeType(const std::string& mt) { p->m_mimetype = mt; }
const std::string& AnalysisResult::mimeType() const { return p->m_mimetype; }
char
AnalysisResult::index(InputStream* file) {
    return p->m_indexer.analyze(*this, file);
}
char
AnalysisResult::indexChild(const std::string& name, time_t mt,
        InputStream* file) {
    std::string path(p->m_path);
    path.append("/");
    path.append(name);
    const char* n = path.c_str() + path.rfind('/') + 1;
    // check if we should index this file by applying the filename filters
    if (p->m_analyzerconfig.indexFile(path.c_str(), n)) {
        AnalysisResult i(path, n, mt, *this);
        return p->m_indexer.analyze(i, file);
    }
    return 0;
}
void
AnalysisResult::addText(const char* text, int32_t length) {
    if (checkUtf8(text, length)) {
        p->m_writer.addText(this, text, length);
    } else {
        Latin1Converter::lock();
        char* d;
        size_t len = Latin1Converter::fromLatin1(d, text, length);
        if (len && checkUtf8(d, len)) {
            p->m_writer.addText(this, d, len);
        } else {
            fprintf(stderr, "'%.*s' is not a UTF8 or latin1 string\n",
                length, text);
        }
        Latin1Converter::unlock();
    }
}
AnalyzerConfiguration&
AnalysisResult::config() const {
    return p->m_analyzerconfig;
}
AnalysisResult*
AnalysisResult::parent() {
    return p->m_parent;
}
const StreamEndAnalyzer*
AnalysisResult::endAnalyzer() const {
    return p->m_endanalyzer;
}
void
AnalysisResult::setEndAnalyzer(const StreamEndAnalyzer* ea) {
    p->m_endanalyzer = ea;
}
string
AnalysisResult::extension() const {
    string::size_type p1 = p->m_name.rfind('.');
    string::size_type p2 = p->m_name.rfind('/');
    if (p1 != string::npos && (p2 == string::npos || p1 > p2)) {
        return p->m_name.substr(p1+1);
    }
    return "";
}
void
AnalysisResult::addValue(const RegisteredField* field, const std::string& val) {
    if (!p->checkCardinality(field))
	return;
    if (checkUtf8(val)) {
        p->m_writer.addValue(this, field, val);
    } else {
        Latin1Converter::lock();
        char* d;
        size_t len = Latin1Converter::fromLatin1(d, val.c_str(), val.length());
        if (len && checkUtf8(d, len)) {
            p->m_writer.addValue(this, field, (const unsigned char*)d, len);
        } else {
            fprintf(stderr, "'%s' is not a UTF8 or latin1 string\n",
                val.c_str());
        }
        Latin1Converter::unlock();
    }
}
void
AnalysisResult::addValue(const RegisteredField* field,
        const char* data, uint32_t length) {
    if (!p->checkCardinality(field))
	return;
    if (checkUtf8(data, length)) {
        p->m_writer.addValue(this, field, (const unsigned char*)data, length);
    } else {
        Latin1Converter::lock();
        char* d;
        size_t len = Latin1Converter::fromLatin1(d, data, length);
        if (len && checkUtf8(d, len)) {
            p->m_writer.addValue(this, field, (const unsigned char*)d, len);
        } else {
            fprintf(stderr, "'%.*s' is not a UTF8 or latin1 string\n",
                length, data);
        }
        Latin1Converter::unlock();
    }
}
void
AnalysisResult::addValue(const RegisteredField* field, int32_t value) {
    if (!p->checkCardinality(field))
	return;
    p->m_writer.addValue(this, field, value);
}
void
AnalysisResult::addValue(const RegisteredField* field, uint32_t value) {
    if (!p->checkCardinality(field))
	return;
    p->m_writer.addValue(this, field, value);
}
void
AnalysisResult::addValue(const RegisteredField* field, double value) {
    if (!p->checkCardinality(field))
	return;
    p->m_writer.addValue(this, field, value);
}
bool
AnalysisResult::Private::checkCardinality(const RegisteredField* field) {
    std::map<const Strigi::RegisteredField*, int>::const_iterator i = occurences.find(field);
    if (i != occurences.end()) {
	if (i->second >= field->properties().maxCardinality() && field->properties().maxCardinality() >= 0) {
	    return false;
	} else {
	    occurences[field]++;
	}
    } else {
	occurences[field] = 1;
    }
    return true;
}

<commit_msg>maxCardinality limit check issues a warning if analyzer hits the limit. should be helpful to design debug XESAM ontology as well as debug current .fieldproperties<commit_after>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "analysisresult.h"
#include <strigi/strigiconfig.h>
#include "indexwriter.h"
#include "analyzerconfiguration.h"
#include "streamanalyzer.h"
#include "streambase.h"
#include "textutils.h"
#include "strigi_thread.h"
#include <string>
#include <cstdlib>
#include <iconv.h>

#include <iostream>
#include <map>

#ifdef ICONV_SECOND_ARGUMENT_IS_CONST
     #define ICONV_CONST const
#else
     #define ICONV_CONST
#endif

using namespace Strigi;
using namespace std;

class Latin1Converter {
    iconv_t const conv;
    char* out;
    size_t outlen;
    STRIGI_MUTEX_DEFINE(mutex);

    int32_t _fromLatin1(char*& out, const char* data, size_t len);
    Latin1Converter() :conv(iconv_open("UTF-8", "ISO-8859-1")), outlen(0) {
        STRIGI_MUTEX_INIT(&mutex);
    }
    ~Latin1Converter() {
        iconv_close(conv);
        free(out);
        STRIGI_MUTEX_DESTROY(&mutex);
    }
    static Latin1Converter& converter() {
        static Latin1Converter l;
        return l;
    }
public:
    static int32_t fromLatin1(char*& out, const char* data, int32_t len) {
        return converter()._fromLatin1(out, data, len);
    }
    static void lock() {
        STRIGI_MUTEX_LOCK(&converter().mutex);
    }
    static void unlock() {
        STRIGI_MUTEX_UNLOCK(&converter().mutex);
    }
};
int32_t
Latin1Converter::_fromLatin1(char*& o, const char* data, size_t len) {
    size_t l = 3*len;
    if (outlen < l) {
        out = (char*)realloc(out, l);
        outlen = l;
    } else {
        l = outlen;
    }
    o = out;
    ICONV_CONST char* inp = (char*)data;
    char* outp = out;
    iconv(conv, &inp, &len, &outp, &l);
    return (len == 0) ?outlen-l :0;
}

class AnalysisResult::Private {
public:
    int64_t m_id;
    mutable void* m_writerData;
    const time_t m_mtime;
    std::string m_name;
    const std::string m_path;
    std::string m_encoding;
    std::string m_mimetype;
    IndexWriter& m_writer;
    const int m_depth;
    StreamAnalyzer& m_indexer;
    AnalyzerConfiguration& m_analyzerconfig;
    AnalysisResult* const m_parent;
    const StreamEndAnalyzer* m_endanalyzer;
    std::map<const Strigi::RegisteredField*, int> occurences;

    Private(const std::string& p, const char* name, time_t mt,
        AnalysisResult& parent);
    Private(const std::string& p, time_t mt, IndexWriter& w,
        StreamAnalyzer& indexer);

    bool checkCardinality(const RegisteredField* field);
};

AnalysisResult::Private::Private(const std::string& p, const char* name,
        time_t mt, AnalysisResult& parent)
            :m_writerData(0), m_mtime(mt), m_name(name), m_path(p),
             m_writer(parent.p->m_writer), m_depth(parent.depth()+1),
             m_indexer(parent.p->m_indexer),
             m_analyzerconfig(parent.p->m_analyzerconfig), m_parent(&parent),
             m_endanalyzer(0) {
}
AnalysisResult::AnalysisResult(const std::string& path, const char* name,
        time_t mt, AnalysisResult& parent)
        :p(new Private(path, name, mt, parent)) {
    p->m_writer.startAnalysis(this);
}
AnalysisResult::Private::Private(const std::string& p, time_t mt,
        IndexWriter& w, StreamAnalyzer& indexer)
            :m_writerData(0), m_mtime(mt), m_path(p), m_writer(w), m_depth(0),
             m_indexer(indexer), m_analyzerconfig(indexer.configuration()),
             m_parent(0), m_endanalyzer(0) {
    size_t pos = m_path.rfind('/');
    if (pos == std::string::npos) {
        m_name = m_path;
    } else {
        m_name = m_path.substr(pos+1);
    }
}
AnalysisResult::AnalysisResult(const std::string& path, time_t mt,
        IndexWriter& w, StreamAnalyzer& indexer)
            :p(new Private(path, mt, w, indexer)) {
    p->m_writer.startAnalysis(this);
}
AnalysisResult::~AnalysisResult() {
    p->m_writer.finishAnalysis(this);
    delete p;
}
const std::string& AnalysisResult::fileName() const { return p->m_name; }
const std::string& AnalysisResult::path() const { return p->m_path; }
time_t AnalysisResult::mTime() const { return p->m_mtime; }
char AnalysisResult::depth() const { return p->m_depth; }
int64_t AnalysisResult::id() const { return p->m_id; }
void AnalysisResult::setId(int64_t i) { p->m_id = i; }
void AnalysisResult::setEncoding(const char* enc) { p->m_encoding = enc; }
const std::string& AnalysisResult::encoding() const { return p->m_encoding; }
void* AnalysisResult::writerData() const { return p->m_writerData; }
void AnalysisResult::setWriterData(void* wd) const { p->m_writerData = wd; }
void AnalysisResult::setMimeType(const std::string& mt) { p->m_mimetype = mt; }
const std::string& AnalysisResult::mimeType() const { return p->m_mimetype; }
char
AnalysisResult::index(InputStream* file) {
    return p->m_indexer.analyze(*this, file);
}
char
AnalysisResult::indexChild(const std::string& name, time_t mt,
        InputStream* file) {
    std::string path(p->m_path);
    path.append("/");
    path.append(name);
    const char* n = path.c_str() + path.rfind('/') + 1;
    // check if we should index this file by applying the filename filters
    if (p->m_analyzerconfig.indexFile(path.c_str(), n)) {
        AnalysisResult i(path, n, mt, *this);
        return p->m_indexer.analyze(i, file);
    }
    return 0;
}
void
AnalysisResult::addText(const char* text, int32_t length) {
    if (checkUtf8(text, length)) {
        p->m_writer.addText(this, text, length);
    } else {
        Latin1Converter::lock();
        char* d;
        size_t len = Latin1Converter::fromLatin1(d, text, length);
        if (len && checkUtf8(d, len)) {
            p->m_writer.addText(this, d, len);
        } else {
            fprintf(stderr, "'%.*s' is not a UTF8 or latin1 string\n",
                length, text);
        }
        Latin1Converter::unlock();
    }
}
AnalyzerConfiguration&
AnalysisResult::config() const {
    return p->m_analyzerconfig;
}
AnalysisResult*
AnalysisResult::parent() {
    return p->m_parent;
}
const StreamEndAnalyzer*
AnalysisResult::endAnalyzer() const {
    return p->m_endanalyzer;
}
void
AnalysisResult::setEndAnalyzer(const StreamEndAnalyzer* ea) {
    p->m_endanalyzer = ea;
}
string
AnalysisResult::extension() const {
    string::size_type p1 = p->m_name.rfind('.');
    string::size_type p2 = p->m_name.rfind('/');
    if (p1 != string::npos && (p2 == string::npos || p1 > p2)) {
        return p->m_name.substr(p1+1);
    }
    return "";
}
void
AnalysisResult::addValue(const RegisteredField* field, const std::string& val) {
    if (!p->checkCardinality(field))
	return;
    if (checkUtf8(val)) {
        p->m_writer.addValue(this, field, val);
    } else {
        Latin1Converter::lock();
        char* d;
        size_t len = Latin1Converter::fromLatin1(d, val.c_str(), val.length());
        if (len && checkUtf8(d, len)) {
            p->m_writer.addValue(this, field, (const unsigned char*)d, len);
        } else {
            fprintf(stderr, "'%s' is not a UTF8 or latin1 string\n",
                val.c_str());
        }
        Latin1Converter::unlock();
    }
}
void
AnalysisResult::addValue(const RegisteredField* field,
        const char* data, uint32_t length) {
    if (!p->checkCardinality(field))
	return;
    if (checkUtf8(data, length)) {
        p->m_writer.addValue(this, field, (const unsigned char*)data, length);
    } else {
        Latin1Converter::lock();
        char* d;
        size_t len = Latin1Converter::fromLatin1(d, data, length);
        if (len && checkUtf8(d, len)) {
            p->m_writer.addValue(this, field, (const unsigned char*)d, len);
        } else {
            fprintf(stderr, "'%.*s' is not a UTF8 or latin1 string\n",
                length, data);
        }
        Latin1Converter::unlock();
    }
}
void
AnalysisResult::addValue(const RegisteredField* field, int32_t value) {
    if (!p->checkCardinality(field))
	return;
    p->m_writer.addValue(this, field, value);
}
void
AnalysisResult::addValue(const RegisteredField* field, uint32_t value) {
    if (!p->checkCardinality(field))
	return;
    p->m_writer.addValue(this, field, value);
}
void
AnalysisResult::addValue(const RegisteredField* field, double value) {
    if (!p->checkCardinality(field))
	return;
    p->m_writer.addValue(this, field, value);
}
bool
AnalysisResult::Private::checkCardinality(const RegisteredField* field) {
    std::map<const Strigi::RegisteredField*, int>::const_iterator i = occurences.find(field);
    if (i != occurences.end()) {
	if (i->second >= field->properties().maxCardinality() && field->properties().maxCardinality() >= 0) {
	    fprintf(stderr, "%s hit the maxCardinality limit (%d)\n",
		field->properties().name().c_str(), field->properties().maxCardinality());
	    return false;
	} else {
	    occurences[field]++;
	}
    } else {
	occurences[field] = 1;
    }
    return true;
}

<|endoftext|>


<commit_before>#include "findCollidingNames.h"
#include "symtab.h"
#include "stringutil.h"

/* Goal:
 * Find symbols that have names which already exist and munge those.
 * Strategy:
 * Keep track of all function symbols, type symbols and variable symbols in vector structures.
 * Search those structures for colliding names and change the cname to a unique name.
 * Initially all the cnames are the same as name; then we change them as needed.
 *
 */

void FindCollidingNames::processSymbol(Symbol* sym) {
  if (_adhoc_to_uniform_mangling) {
    if (FnSymbol* fnsym = dynamic_cast<FnSymbol*>(sym)) {
      fnsyms.add(fnsym);
    }
    if (TypeSymbol* typesym = dynamic_cast<TypeSymbol*>(sym)) {
      typesyms.add(typesym);
    }
    if (VarSymbol* varsym = dynamic_cast<VarSymbol*>(sym)) {
      if (varsym->parentScope->type == SCOPE_MODULE) {
        globalvars.add(varsym);
      }
    }
  }
}

/*void FindCollidingNames::run(ModuleList* moduleList) {
  SymtabTraversal::run(moduleList);
  //RED: for test purposes only
  fnsyms.quickSort(0, fnsyms.length()-1);
}*/

<commit_msg>Patch broken build.  To be reviewed by the author.<commit_after>#include "findCollidingNames.h"
#include "symtab.h"
#include "stringutil.h"

/* Goal:
 * Find symbols that have names which already exist and munge those.
 * Strategy:
 * Keep track of all function symbols, type symbols and variable symbols in vector structures.
 * Search those structures for colliding names and change the cname to a unique name.
 * Initially all the cnames are the same as name; then we change them as needed.
 *
 */

void FindCollidingNames::processSymbol(Symbol* sym) {
  if (_adhoc_to_uniform_mangling) {
    if (FnSymbol* fnsym = dynamic_cast<FnSymbol*>(sym)) {
      fnsyms.add(fnsym);
    }
    if (TypeSymbol* typesym = dynamic_cast<TypeSymbol*>(sym)) {
      typesyms.add(typesym);
    }
    if (VarSymbol* varsym = dynamic_cast<VarSymbol*>(sym)) {
      if (varsym->parentScope->type == SCOPE_MODULE) {
        globalvars.add(varsym);
      }
    }
  }
}

void FindCollidingNames::run(ModuleList* moduleList) {
/*
  SymtabTraversal::run(moduleList);
  //RED: for test purposes only
  fnsyms.quickSort(0, fnsyms.length()-1);
*/
}

<|endoftext|>