<commit_before>/*************************************************************************
 *
 *  $RCSfile: salvd.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: vg $ $Date: 2004-01-06 12:49:04 $
 *
 *  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_SALVD_HXX
    #include <salvd.hxx>
#endif

// =======================================================================

// =======================================================================

static BOOL InitVirtualDeviceGWorld ( SalVirDevDataPtr rSalVirDevData )
{
    BOOL  bVirtualDeviceGWorldInited = FALSE;

    if (    ( rSalVirDevData             != NULL )
         && ( rSalVirDevData->mpGraphics != NULL )
       )
    {
        Rect         aBoundsRect;
        short        nRectLeft   = 0;
        short        nRectTop    = 0;
        short        nRectRight  = rSalVirDevData->mnWidth;
        short        nRectBottom = rSalVirDevData->mnHeight;
        short        nPixelDepth = rSalVirDevData->mnBitCount;
        GWorldPtr    pGWorld     = NULL;
        CTabHandle   hCTable     = NULL;
        GDHandle     hGDevice    = NULL;
        GWorldFlags  nFlags      = 0; // [ed] 12/1/01 Allow offscreen gworlds
        OSStatus     nOSStatus   = noErr;

        // Set the dimensions of the GWorldPtr

        MacSetRect( &aBoundsRect, nRectLeft, nRectTop, nRectRight, nRectBottom );

        // Create the offscreen graphics context

        nOSStatus = NewGWorld( &pGWorld,
                                nPixelDepth,
                               &aBoundsRect,
                                hCTable,
                                hGDevice,
                                nFlags
                             );

        // If NewGWorld failed, try again with different flags

        if ( nOSStatus != noErr )
        {
            nFlags = noErr;

            nOSStatus = NewGWorld( &pGWorld,
                                    nPixelDepth,
                                   &aBoundsRect,
                                    hCTable,
                                    hGDevice,
                                    nFlags
                                 );
        } // if

        if (    ( nOSStatus == noErr )
             && ( pGWorld   != NULL  )
           )
        {
            // Lock the virtual GWorld's port bits

            rSalVirDevData->mpGraphics->maGraphicsData.mnOSStatus
                = LockPortBits( pGWorld );

            if ( rSalVirDevData->mpGraphics->maGraphicsData.mnOSStatus == noErr )
            {
                // Initialize the virtual graph port

                rSalVirDevData->mpGraphics->maGraphicsData.mpCGrafPort
                    = pGWorld;

                rSalVirDevData->mpGraphics->maGraphicsData.mpGWorld
                    = pGWorld;

                // Initialize virtual port's GWorld attributes

                rSalVirDevData->mpGraphics->maGraphicsData.mhGWorldPixMap
                    = GetGWorldPixMap( pGWorld );

                // Unlock virtual GWorld's port bits

                UnlockPortBits( pGWorld );
            } // if

            // Initialize virtual port's GWorld attributes

            rSalVirDevData->mpGraphics->maGraphicsData.mbGWorldPixelsLocked = FALSE;
            rSalVirDevData->mpGraphics->maGraphicsData.mbGWorldPixelsCopy   = FALSE;
            rSalVirDevData->mpGraphics->maGraphicsData.mbGWorldPixelsNew    = FALSE;
            rSalVirDevData->mpGraphics->maGraphicsData.mnGWorldFlags        = noErr;

            // Initialize the virtual port's brush attributes

            rSalVirDevData->mpGraphics->maGraphicsData.mbBrushTransparent = FALSE;
            rSalVirDevData->mpGraphics->maGraphicsData.maBrushColor       = GetBlackColor( );

            // Initialize the virtual port's font attributes

            rSalVirDevData->mpGraphics->maGraphicsData.maFontColor = GetBlackColor( );
            rSalVirDevData->mpGraphics->maGraphicsData.mnFontID    = kFontIDGeneva;
            rSalVirDevData->mpGraphics->maGraphicsData.mnFontSize  = 10;
            rSalVirDevData->mpGraphics->maGraphicsData.mnFontStyle = normal;

            // Initialize virtual port's clip regions

            rSalVirDevData->mpGraphics->maGraphicsData.mhClipRgn        = NULL;
            rSalVirDevData->mpGraphics->maGraphicsData.mbClipRgnChanged = FALSE;

            // Initilaize virtual port's status flags

            rSalVirDevData->mpGraphics->maGraphicsData.mbPrinter = FALSE;
            rSalVirDevData->mpGraphics->maGraphicsData.mbVirDev  = TRUE;
            rSalVirDevData->mpGraphics->maGraphicsData.mbWindow  = FALSE;
            rSalVirDevData->mpGraphics->maGraphicsData.mbScreen  = TRUE;

            bVirtualDeviceGWorldInited = TRUE;
        } // if
    } // if

    return bVirtualDeviceGWorldInited;
} //InitVirtualDeviceGWorld

// =======================================================================

// =======================================================================

SalVirtualDevice::SalVirtualDevice()
{
    maVirDevData.mpGraphics = NULL;
    maVirDevData.mnBitCount = 0;
    maVirDevData.mnWidth    = 0;
    maVirDevData.mnHeight   = 0;
    maVirDevData.mbGraphics = FALSE;
} // Constructor

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

SalVirtualDevice::~SalVirtualDevice()
{
    if ( maVirDevData.mpGraphics != NULL )
    {
        // Delete exisiting clip regions, offscreen graphic world,
        // and its associated colour graph port

        delete maVirDevData.mpGraphics;
    } // if
} // Destructor

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

SalGraphics* SalVirtualDevice::GetGraphics()
{
    if ( maVirDevData.mbGraphics )
    {
        return NULL;
    } // if

    if ( !maVirDevData.mpGraphics )
    {
        maVirDevData.mpGraphics = new SalGraphics;

        maVirDevData.mbGraphics = InitVirtualDeviceGWorld( &maVirDevData );

        if ( !maVirDevData.mbGraphics )
        {
            delete maVirDevData.mpGraphics;
            maVirDevData.mpGraphics = NULL;
        } // if
    } // if

    return maVirDevData.mpGraphics;
} // SalVirtualDevice::GetGraphics

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

void SalVirtualDevice::ReleaseGraphics( SalGraphics *pGraphics )
{
    maVirDevData.mbGraphics = FALSE;
} // SalVirtualDevice::ReleaseGraphics

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

BOOL SalVirtualDevice::SetSize( long nDX, long nDY )
{
    BOOL bSizeSet = FALSE;

    // If we have already created a graphics context, dispose of it,
    // by deleting exisiting clip regions, offscreen graphic worlds,
    // and its associated colour graph port

    if (    (    ( maVirDevData.mpGraphics->maGraphicsData.mbGWorldPixelsCopy == TRUE )
              || ( maVirDevData.mpGraphics->maGraphicsData.mbGWorldPixelsNew  == TRUE )
            )
         && ( maVirDevData.mpGraphics->maGraphicsData.mhGWorldPixMap != NULL )
           )
    {
        DisposePixMap( maVirDevData.mpGraphics->maGraphicsData.mhGWorldPixMap );
    } // if

    if ( maVirDevData.mpGraphics->maGraphicsData.mhClipRgn != NULL )
    {
        DisposeRgn( maVirDevData.mpGraphics->maGraphicsData.mhClipRgn );
    } // if

    if ( maVirDevData.mpGraphics->maGraphicsData.mpCGrafPort != NULL )
    {
        DisposeGWorld( maVirDevData.mpGraphics->maGraphicsData.mpCGrafPort );

        maVirDevData.mpGraphics->maGraphicsData.mpGWorld    = NULL;
        maVirDevData.mpGraphics->maGraphicsData.mpCGrafPort = NULL;
    } // if

    // Create the offscreen graphics context

    maVirDevData.mnWidth  = nDX;
    maVirDevData.mnHeight = nDY;

    bSizeSet = InitVirtualDeviceGWorld( &maVirDevData );

    return bSizeSet;
} // SalVirtualDevice::SetSize

// =======================================================================

// =======================================================================

<commit_msg>INTEGRATION: CWS ooo19126 (1.15.546); FILE MERGED 2005/09/05 14:43:43 rt 1.15.546.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: salvd.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 10:44:08 $
 *
 *  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_SALVD_HXX
    #include <salvd.hxx>
#endif

// =======================================================================

// =======================================================================

static BOOL InitVirtualDeviceGWorld ( SalVirDevDataPtr rSalVirDevData )
{
    BOOL  bVirtualDeviceGWorldInited = FALSE;

    if (    ( rSalVirDevData             != NULL )
         && ( rSalVirDevData->mpGraphics != NULL )
       )
    {
        Rect         aBoundsRect;
        short        nRectLeft   = 0;
        short        nRectTop    = 0;
        short        nRectRight  = rSalVirDevData->mnWidth;
        short        nRectBottom = rSalVirDevData->mnHeight;
        short        nPixelDepth = rSalVirDevData->mnBitCount;
        GWorldPtr    pGWorld     = NULL;
        CTabHandle   hCTable     = NULL;
        GDHandle     hGDevice    = NULL;
        GWorldFlags  nFlags      = 0; // [ed] 12/1/01 Allow offscreen gworlds
        OSStatus     nOSStatus   = noErr;

        // Set the dimensions of the GWorldPtr

        MacSetRect( &aBoundsRect, nRectLeft, nRectTop, nRectRight, nRectBottom );

        // Create the offscreen graphics context

        nOSStatus = NewGWorld( &pGWorld,
                                nPixelDepth,
                               &aBoundsRect,
                                hCTable,
                                hGDevice,
                                nFlags
                             );

        // If NewGWorld failed, try again with different flags

        if ( nOSStatus != noErr )
        {
            nFlags = noErr;

            nOSStatus = NewGWorld( &pGWorld,
                                    nPixelDepth,
                                   &aBoundsRect,
                                    hCTable,
                                    hGDevice,
                                    nFlags
                                 );
        } // if

        if (    ( nOSStatus == noErr )
             && ( pGWorld   != NULL  )
           )
        {
            // Lock the virtual GWorld's port bits

            rSalVirDevData->mpGraphics->maGraphicsData.mnOSStatus
                = LockPortBits( pGWorld );

            if ( rSalVirDevData->mpGraphics->maGraphicsData.mnOSStatus == noErr )
            {
                // Initialize the virtual graph port

                rSalVirDevData->mpGraphics->maGraphicsData.mpCGrafPort
                    = pGWorld;

                rSalVirDevData->mpGraphics->maGraphicsData.mpGWorld
                    = pGWorld;

                // Initialize virtual port's GWorld attributes

                rSalVirDevData->mpGraphics->maGraphicsData.mhGWorldPixMap
                    = GetGWorldPixMap( pGWorld );

                // Unlock virtual GWorld's port bits

                UnlockPortBits( pGWorld );
            } // if

            // Initialize virtual port's GWorld attributes

            rSalVirDevData->mpGraphics->maGraphicsData.mbGWorldPixelsLocked = FALSE;
            rSalVirDevData->mpGraphics->maGraphicsData.mbGWorldPixelsCopy   = FALSE;
            rSalVirDevData->mpGraphics->maGraphicsData.mbGWorldPixelsNew    = FALSE;
            rSalVirDevData->mpGraphics->maGraphicsData.mnGWorldFlags        = noErr;

            // Initialize the virtual port's brush attributes

            rSalVirDevData->mpGraphics->maGraphicsData.mbBrushTransparent = FALSE;
            rSalVirDevData->mpGraphics->maGraphicsData.maBrushColor       = GetBlackColor( );

            // Initialize the virtual port's font attributes

            rSalVirDevData->mpGraphics->maGraphicsData.maFontColor = GetBlackColor( );
            rSalVirDevData->mpGraphics->maGraphicsData.mnFontID    = kFontIDGeneva;
            rSalVirDevData->mpGraphics->maGraphicsData.mnFontSize  = 10;
            rSalVirDevData->mpGraphics->maGraphicsData.mnFontStyle = normal;

            // Initialize virtual port's clip regions

            rSalVirDevData->mpGraphics->maGraphicsData.mhClipRgn        = NULL;
            rSalVirDevData->mpGraphics->maGraphicsData.mbClipRgnChanged = FALSE;

            // Initilaize virtual port's status flags

            rSalVirDevData->mpGraphics->maGraphicsData.mbPrinter = FALSE;
            rSalVirDevData->mpGraphics->maGraphicsData.mbVirDev  = TRUE;
            rSalVirDevData->mpGraphics->maGraphicsData.mbWindow  = FALSE;
            rSalVirDevData->mpGraphics->maGraphicsData.mbScreen  = TRUE;

            bVirtualDeviceGWorldInited = TRUE;
        } // if
    } // if

    return bVirtualDeviceGWorldInited;
} //InitVirtualDeviceGWorld

// =======================================================================

// =======================================================================

SalVirtualDevice::SalVirtualDevice()
{
    maVirDevData.mpGraphics = NULL;
    maVirDevData.mnBitCount = 0;
    maVirDevData.mnWidth    = 0;
    maVirDevData.mnHeight   = 0;
    maVirDevData.mbGraphics = FALSE;
} // Constructor

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

SalVirtualDevice::~SalVirtualDevice()
{
    if ( maVirDevData.mpGraphics != NULL )
    {
        // Delete exisiting clip regions, offscreen graphic world,
        // and its associated colour graph port

        delete maVirDevData.mpGraphics;
    } // if
} // Destructor

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

SalGraphics* SalVirtualDevice::GetGraphics()
{
    if ( maVirDevData.mbGraphics )
    {
        return NULL;
    } // if

    if ( !maVirDevData.mpGraphics )
    {
        maVirDevData.mpGraphics = new SalGraphics;

        maVirDevData.mbGraphics = InitVirtualDeviceGWorld( &maVirDevData );

        if ( !maVirDevData.mbGraphics )
        {
            delete maVirDevData.mpGraphics;
            maVirDevData.mpGraphics = NULL;
        } // if
    } // if

    return maVirDevData.mpGraphics;
} // SalVirtualDevice::GetGraphics

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

void SalVirtualDevice::ReleaseGraphics( SalGraphics *pGraphics )
{
    maVirDevData.mbGraphics = FALSE;
} // SalVirtualDevice::ReleaseGraphics

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

BOOL SalVirtualDevice::SetSize( long nDX, long nDY )
{
    BOOL bSizeSet = FALSE;

    // If we have already created a graphics context, dispose of it,
    // by deleting exisiting clip regions, offscreen graphic worlds,
    // and its associated colour graph port

    if (    (    ( maVirDevData.mpGraphics->maGraphicsData.mbGWorldPixelsCopy == TRUE )
              || ( maVirDevData.mpGraphics->maGraphicsData.mbGWorldPixelsNew  == TRUE )
            )
         && ( maVirDevData.mpGraphics->maGraphicsData.mhGWorldPixMap != NULL )
           )
    {
        DisposePixMap( maVirDevData.mpGraphics->maGraphicsData.mhGWorldPixMap );
    } // if

    if ( maVirDevData.mpGraphics->maGraphicsData.mhClipRgn != NULL )
    {
        DisposeRgn( maVirDevData.mpGraphics->maGraphicsData.mhClipRgn );
    } // if

    if ( maVirDevData.mpGraphics->maGraphicsData.mpCGrafPort != NULL )
    {
        DisposeGWorld( maVirDevData.mpGraphics->maGraphicsData.mpCGrafPort );

        maVirDevData.mpGraphics->maGraphicsData.mpGWorld    = NULL;
        maVirDevData.mpGraphics->maGraphicsData.mpCGrafPort = NULL;
    } // if

    // Create the offscreen graphics context

    maVirDevData.mnWidth  = nDX;
    maVirDevData.mnHeight = nDY;

    bSizeSet = InitVirtualDeviceGWorld( &maVirDevData );

    return bSizeSet;
} // SalVirtualDevice::SetSize

// =======================================================================

// =======================================================================

<|endoftext|>


<commit_before><commit_msg>coverity#735655 avoid division by 0<commit_after><|endoftext|>


<commit_before><commit_msg>coverity#440938 Logically dead code<commit_after><|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <salunx.h>
#include <saldisp.hxx>
#include <cdeint.hxx>
#include <settings.hxx>

#include <tools/stream.hxx>
#include <tools/debug.hxx>

CDEIntegrator::CDEIntegrator()
{
    meType = DtCDE;
}

CDEIntegrator::~CDEIntegrator()
{
}

static int getHexDigit( const char c )
{
    if( c >= '0' && c <= '9' )
        return (int)(c-'0');
    else if( c >= 'a' && c <= 'f' )
        return (int)(c-'a'+10);
    else if( c >= 'A' && c <= 'F' )
        return (int)(c-'A'+10);
    return -1;
}

void CDEIntegrator::GetSystemLook( AllSettings& rSettings )
{
    static Color aColors[ 8 ];
    static sal_Bool bRead  = sal_False;
    static sal_Bool bValid = sal_False;

    if( ! bRead )
    {
        // get used palette from xrdb
        char **ppStringList = 0;
        int nStringCount;
        XTextProperty aTextProperty;
        aTextProperty.value = 0;
        int i;

        static Atom nResMgrAtom = XInternAtom( mpDisplay, "RESOURCE_MANAGER", False );

        if( XGetTextProperty( mpDisplay,
                              RootWindow( mpDisplay, 0 ),
                              &aTextProperty,
                              nResMgrAtom )
            && aTextProperty.value
            && XTextPropertyToStringList( &aTextProperty, &ppStringList, &nStringCount )
            )
        {
            // format of ColorPalette resource:
            // *n*ColorPalette: palettefile

            ByteString aLines;
            for( i=0; i < nStringCount; i++ )
                aLines += ppStringList[i];
            for( i = aLines.GetTokenCount( '\n' )-1; i >= 0; i-- )
            {
                ByteString aLine = aLines.GetToken( i, '\n' );
                int nIndex = aLine.Search( "ColorPalette" );
                if( nIndex != STRING_NOTFOUND )
                {
                    int nPos = nIndex;

                    nIndex+=12;
                    const char* pStr = aLine.GetBuffer() +nIndex;
                    while( *pStr && isspace( *pStr ) && *pStr != ':' )
                    {
                        pStr++;
                        nIndex++;
                    }
                    if( *pStr != ':' )
                        continue;
                    pStr++, nIndex++;
                    for( ; *pStr && isspace( *pStr ); pStr++, nIndex++ )
                        ;
                    if( ! *pStr )
                        continue;
                    int nIndex2 = nIndex;
                    for( ; *pStr && ! isspace( *pStr ); pStr++, nIndex2++ )
                        ;
                    ByteString aPaletteFile( aLine.Copy( nIndex, nIndex2 - nIndex ) );
                    // extract number before ColorPalette;
                    for( ; nPos >= 0 && aLine.GetChar( nPos ) != '*'; nPos-- )
                        ;
                    nPos--;
                    for( ; nPos >= 0 && aLine.GetChar( nPos ) != '*'; nPos-- )
                        ;
                    int nNumber = aLine.Copy( ++nPos ).ToInt32();

                    DBG_TRACE2( "found palette %d in resource \"%s\"", nNumber, aLine.GetBuffer() );

                    // found no documentation what this number actually means;
                    // might be the screen number. 0 seems to be the right one
                    // in most cases.
                    if( nNumber )
                        continue;

                    DBG_TRACE1( "Palette file is \"%s\".\n", aPaletteFile.GetBuffer() );

                    String aPath( aHomeDir );
                    aPath.AppendAscii( "/.dt/palettes/" );
                    aPath += String( aPaletteFile, gsl_getSystemTextEncoding() );

                    SvFileStream aStream( aPath, STREAM_READ );
                    if( ! aStream.IsOpen() )
                    {
                        aPath = String::CreateFromAscii( "/usr/dt/palettes/" );
                        aPath += String( aPaletteFile, gsl_getSystemTextEncoding() );
                        aStream.Open( aPath, STREAM_READ );
                        if( ! aStream.IsOpen() )
                            continue;
                    }

                    ByteString aBuffer;
                    for( nIndex = 0; nIndex < 8; nIndex++ )
                    {
                        aStream.ReadLine( aBuffer );
                        // format is "#RRRRGGGGBBBB"

                        DBG_TRACE1( "\t\"%s\".\n", aBuffer.GetBuffer() );

                        if( aBuffer.Len() )
                        {
                            const char* pArr = (const char*)aBuffer.GetBuffer()+1;
                            aColors[nIndex] = Color(
                                getHexDigit( pArr[1] )
                                | ( getHexDigit( pArr[0] ) << 4 ),
                                getHexDigit( pArr[5] )
                                | ( getHexDigit( pArr[4] ) << 4 ),
                                getHexDigit( pArr[9] )
                                | ( getHexDigit( pArr[8] ) << 4 )
                                );

                            DBG_TRACE1( "\t\t%lx\n", aColors[nIndex].GetColor() );
                        }
                    }

                    bValid = sal_True;
                    break;
                }
            }
        }

        if( ppStringList )
            XFreeStringList( ppStringList );
        if( aTextProperty.value )
            XFree( aTextProperty.value );
    }

    StyleSettings aStyleSettings = rSettings.GetStyleSettings();
    // #i48001# set a default blink rate
    aStyleSettings.SetCursorBlinkTime( 500 );
    if (bValid)
    {
        aStyleSettings.SetActiveColor( aColors[0] );
        aStyleSettings.SetActiveColor2( aColors[0] );
        aStyleSettings.SetActiveBorderColor( aColors[0] );

        aStyleSettings.SetDeactiveColor( aColors[0] );
        aStyleSettings.SetDeactiveColor2( aColors[0] );
        aStyleSettings.SetDeactiveBorderColor( aColors[0] );

        Color aActive =
            aColors[ 0 ].GetBlue() < 128        ||
            aColors[ 0 ].GetGreen() < 128       ||
            aColors[ 0 ].GetRed() < 128
            ? Color( COL_WHITE ) : Color( COL_BLACK );
        Color aDeactive =
            aColors[ 1 ].GetBlue() < 128        ||
            aColors[ 1 ].GetGreen() < 128       ||
            aColors[ 1 ].GetRed() < 128
            ? Color( COL_WHITE ) : Color( COL_BLACK );
        aStyleSettings.SetActiveTextColor( aActive );
        aStyleSettings.SetDeactiveTextColor( aDeactive );

        aStyleSettings.SetDialogTextColor( aDeactive );
        aStyleSettings.SetMenuTextColor( aDeactive );
        aStyleSettings.SetButtonTextColor( aDeactive );
        aStyleSettings.SetRadioCheckTextColor( aDeactive );
        aStyleSettings.SetGroupTextColor( aDeactive );
        aStyleSettings.SetLabelTextColor( aDeactive );
        aStyleSettings.SetInfoTextColor( aDeactive );

        aStyleSettings.Set3DColors( aColors[1] );
        aStyleSettings.SetFaceColor( aColors[1] );
        aStyleSettings.SetDialogColor( aColors[1] );
        aStyleSettings.SetMenuColor( aColors[1] );
        aStyleSettings.SetMenuBarColor( aColors[1] );
        if ( aStyleSettings.GetFaceColor() == COL_LIGHTGRAY )
            aStyleSettings.SetCheckedColor( Color( 0xCC, 0xCC, 0xCC ) );
        else
        {
            // calculate Checked color
            Color   aColor2 = aStyleSettings.GetLightColor();
            BYTE    nRed    = (BYTE)(((USHORT)aColors[1].GetRed()   + (USHORT)aColor2.GetRed())/2);
            BYTE    nGreen  = (BYTE)(((USHORT)aColors[1].GetGreen() + (USHORT)aColor2.GetGreen())/2);
            BYTE    nBlue   = (BYTE)(((USHORT)aColors[1].GetBlue()  + (USHORT)aColor2.GetBlue())/2);
            aStyleSettings.SetCheckedColor( Color( nRed, nGreen, nBlue ) );
        }
    }
    rSettings.SetStyleSettings( aStyleSettings );
}
<commit_msg>INTEGRATION: CWS vgbugs07 (1.13.212); FILE MERGED 2007/06/04 13:29:59 vg 1.13.212.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cdeint.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 20:48:27 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <salunx.h>
#include <saldisp.hxx>
#include <cdeint.hxx>
#include <vcl/settings.hxx>

#include <tools/stream.hxx>
#include <tools/debug.hxx>

CDEIntegrator::CDEIntegrator()
{
    meType = DtCDE;
}

CDEIntegrator::~CDEIntegrator()
{
}

static int getHexDigit( const char c )
{
    if( c >= '0' && c <= '9' )
        return (int)(c-'0');
    else if( c >= 'a' && c <= 'f' )
        return (int)(c-'a'+10);
    else if( c >= 'A' && c <= 'F' )
        return (int)(c-'A'+10);
    return -1;
}

void CDEIntegrator::GetSystemLook( AllSettings& rSettings )
{
    static Color aColors[ 8 ];
    static sal_Bool bRead  = sal_False;
    static sal_Bool bValid = sal_False;

    if( ! bRead )
    {
        // get used palette from xrdb
        char **ppStringList = 0;
        int nStringCount;
        XTextProperty aTextProperty;
        aTextProperty.value = 0;
        int i;

        static Atom nResMgrAtom = XInternAtom( mpDisplay, "RESOURCE_MANAGER", False );

        if( XGetTextProperty( mpDisplay,
                              RootWindow( mpDisplay, 0 ),
                              &aTextProperty,
                              nResMgrAtom )
            && aTextProperty.value
            && XTextPropertyToStringList( &aTextProperty, &ppStringList, &nStringCount )
            )
        {
            // format of ColorPalette resource:
            // *n*ColorPalette: palettefile

            ByteString aLines;
            for( i=0; i < nStringCount; i++ )
                aLines += ppStringList[i];
            for( i = aLines.GetTokenCount( '\n' )-1; i >= 0; i-- )
            {
                ByteString aLine = aLines.GetToken( i, '\n' );
                int nIndex = aLine.Search( "ColorPalette" );
                if( nIndex != STRING_NOTFOUND )
                {
                    int nPos = nIndex;

                    nIndex+=12;
                    const char* pStr = aLine.GetBuffer() +nIndex;
                    while( *pStr && isspace( *pStr ) && *pStr != ':' )
                    {
                        pStr++;
                        nIndex++;
                    }
                    if( *pStr != ':' )
                        continue;
                    pStr++, nIndex++;
                    for( ; *pStr && isspace( *pStr ); pStr++, nIndex++ )
                        ;
                    if( ! *pStr )
                        continue;
                    int nIndex2 = nIndex;
                    for( ; *pStr && ! isspace( *pStr ); pStr++, nIndex2++ )
                        ;
                    ByteString aPaletteFile( aLine.Copy( nIndex, nIndex2 - nIndex ) );
                    // extract number before ColorPalette;
                    for( ; nPos >= 0 && aLine.GetChar( nPos ) != '*'; nPos-- )
                        ;
                    nPos--;
                    for( ; nPos >= 0 && aLine.GetChar( nPos ) != '*'; nPos-- )
                        ;
                    int nNumber = aLine.Copy( ++nPos ).ToInt32();

                    DBG_TRACE2( "found palette %d in resource \"%s\"", nNumber, aLine.GetBuffer() );

                    // found no documentation what this number actually means;
                    // might be the screen number. 0 seems to be the right one
                    // in most cases.
                    if( nNumber )
                        continue;

                    DBG_TRACE1( "Palette file is \"%s\".\n", aPaletteFile.GetBuffer() );

                    String aPath( aHomeDir );
                    aPath.AppendAscii( "/.dt/palettes/" );
                    aPath += String( aPaletteFile, gsl_getSystemTextEncoding() );

                    SvFileStream aStream( aPath, STREAM_READ );
                    if( ! aStream.IsOpen() )
                    {
                        aPath = String::CreateFromAscii( "/usr/dt/palettes/" );
                        aPath += String( aPaletteFile, gsl_getSystemTextEncoding() );
                        aStream.Open( aPath, STREAM_READ );
                        if( ! aStream.IsOpen() )
                            continue;
                    }

                    ByteString aBuffer;
                    for( nIndex = 0; nIndex < 8; nIndex++ )
                    {
                        aStream.ReadLine( aBuffer );
                        // format is "#RRRRGGGGBBBB"

                        DBG_TRACE1( "\t\"%s\".\n", aBuffer.GetBuffer() );

                        if( aBuffer.Len() )
                        {
                            const char* pArr = (const char*)aBuffer.GetBuffer()+1;
                            aColors[nIndex] = Color(
                                getHexDigit( pArr[1] )
                                | ( getHexDigit( pArr[0] ) << 4 ),
                                getHexDigit( pArr[5] )
                                | ( getHexDigit( pArr[4] ) << 4 ),
                                getHexDigit( pArr[9] )
                                | ( getHexDigit( pArr[8] ) << 4 )
                                );

                            DBG_TRACE1( "\t\t%lx\n", aColors[nIndex].GetColor() );
                        }
                    }

                    bValid = sal_True;
                    break;
                }
            }
        }

        if( ppStringList )
            XFreeStringList( ppStringList );
        if( aTextProperty.value )
            XFree( aTextProperty.value );
    }

    StyleSettings aStyleSettings = rSettings.GetStyleSettings();
    // #i48001# set a default blink rate
    aStyleSettings.SetCursorBlinkTime( 500 );
    if (bValid)
    {
        aStyleSettings.SetActiveColor( aColors[0] );
        aStyleSettings.SetActiveColor2( aColors[0] );
        aStyleSettings.SetActiveBorderColor( aColors[0] );

        aStyleSettings.SetDeactiveColor( aColors[0] );
        aStyleSettings.SetDeactiveColor2( aColors[0] );
        aStyleSettings.SetDeactiveBorderColor( aColors[0] );

        Color aActive =
            aColors[ 0 ].GetBlue() < 128        ||
            aColors[ 0 ].GetGreen() < 128       ||
            aColors[ 0 ].GetRed() < 128
            ? Color( COL_WHITE ) : Color( COL_BLACK );
        Color aDeactive =
            aColors[ 1 ].GetBlue() < 128        ||
            aColors[ 1 ].GetGreen() < 128       ||
            aColors[ 1 ].GetRed() < 128
            ? Color( COL_WHITE ) : Color( COL_BLACK );
        aStyleSettings.SetActiveTextColor( aActive );
        aStyleSettings.SetDeactiveTextColor( aDeactive );

        aStyleSettings.SetDialogTextColor( aDeactive );
        aStyleSettings.SetMenuTextColor( aDeactive );
        aStyleSettings.SetButtonTextColor( aDeactive );
        aStyleSettings.SetRadioCheckTextColor( aDeactive );
        aStyleSettings.SetGroupTextColor( aDeactive );
        aStyleSettings.SetLabelTextColor( aDeactive );
        aStyleSettings.SetInfoTextColor( aDeactive );

        aStyleSettings.Set3DColors( aColors[1] );
        aStyleSettings.SetFaceColor( aColors[1] );
        aStyleSettings.SetDialogColor( aColors[1] );
        aStyleSettings.SetMenuColor( aColors[1] );
        aStyleSettings.SetMenuBarColor( aColors[1] );
        if ( aStyleSettings.GetFaceColor() == COL_LIGHTGRAY )
            aStyleSettings.SetCheckedColor( Color( 0xCC, 0xCC, 0xCC ) );
        else
        {
            // calculate Checked color
            Color   aColor2 = aStyleSettings.GetLightColor();
            BYTE    nRed    = (BYTE)(((USHORT)aColors[1].GetRed()   + (USHORT)aColor2.GetRed())/2);
            BYTE    nGreen  = (BYTE)(((USHORT)aColors[1].GetGreen() + (USHORT)aColor2.GetGreen())/2);
            BYTE    nBlue   = (BYTE)(((USHORT)aColors[1].GetBlue()  + (USHORT)aColor2.GetBlue())/2);
            aStyleSettings.SetCheckedColor( Color( nRed, nGreen, nBlue ) );
        }
    }
    rSettings.SetStyleSettings( aStyleSettings );
}
<|endoftext|>


<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>

#include "tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h"
#include "tensorflow/contrib/lite/toco/model.h"
#include "tensorflow/contrib/lite/toco/model_flags.pb.h"
#include "tensorflow/contrib/lite/toco/tooling_util.h"
#include "tensorflow/core/platform/logging.h"

namespace toco {

bool RemoveUnusedOp::Run(Model* model, std::size_t op_index) {
  const auto it = model->operators.begin() + op_index;
  const auto* op = it->get();

  // Bail if any output is used, and is not an input_array of
  // the model. We allow specifying an arbitrary input_array,
  // treating the part of the graph leading up to it as unused.
  for (const auto& output : op->outputs) {
    CHECK(model->HasArray(output));
    // If this output is provided as the model's input array,
    // then we don't need this operator to produce its contents.
    if (IsInputArray(*model, output)) {
      continue;
    }
    // If this output is provided as a RNN's state array,
    // then we don't need this operator to produce its contents.
    // So far this case has only been encountered with TensorFlow
    // Fill ops used to zero-initialize RNN states, which is
    // redundant for us as we zero-initialize RNN states anyway.
    bool found_output_as_rnn_state_array = false;
    for (const auto& rnn_state : model->flags.rnn_states()) {
      if (output == rnn_state.state_array()) {
        CHECK(op->type == OperatorType::kFill);
        found_output_as_rnn_state_array = true;
        break;
      }
    }
    if (found_output_as_rnn_state_array) {
      continue;
    }
    for (const string& output_array : model->flags.output_arrays()) {
      if (output == output_array) {
        return false;
      }
    }
    for (const auto& rnn_state : model->flags.rnn_states()) {
      if (output == rnn_state.back_edge_source_array()) {
        // The output is consumed by a RNN back-edge..
        if (!IsDiscardableArray(*model, rnn_state.back_edge_source_array()) ||
            !IsDiscardableArray(*model, rnn_state.state_array()) ||
            CountOpsWithInput(*model, rnn_state.state_array())) {
          return false;
        }
      }
    }
    if (CountOpsWithInput(*model, output)) {
      return false;
    }
  }

  if (op->unresolved_outputs) {
    AddMessageF("Not discarding %s because it has unresolved outputs.",
                LogName(*op));
    return false;
  }

  AddMessageF("Discarding %s because none of its outputs is used.",
              LogName(*op));

  // At that point we know that none of the outputs is used, so we will
  // definitely remove the node and all its outputs.

  // Remove any input array that is not used by anything else,
  // and that is not the output of some other operator.
  for (const auto& input : op->inputs) {
    if (IsDiscardableArray(*model, input) &&
        CountOpsWithInput(*model, input) == 1 &&
        !GetOpWithOutput(*model, input)) {
      model->EraseArray(input);
    }
  }

  // Remove the node and its now-unused output arrays.
  for (const auto& output : op->outputs) {
    // If the output array is the model's input array, don't remove that.
    // That's the case when cropping a model at a given --input_array.
    if (!IsDiscardableArray(*model, output)) {
      continue;
    }
    // Likewise, if the output array is a RNN state array, don't remove that.
    bool found_output_as_rnn_state_array = false;
    for (const auto& rnn_state : model->flags.rnn_states()) {
      if (output == rnn_state.state_array()) {
        found_output_as_rnn_state_array = true;
        break;
      }
    }
    if (found_output_as_rnn_state_array) {
      continue;
    }
    // Generic case: do delete this output array.
    model->EraseArray(output);
  }
  model->operators.erase(it);
  return true;
}

}  // namespace toco
<commit_msg>Add support for RNN state array of type tf.identity.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>

#include "tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h"
#include "tensorflow/contrib/lite/toco/model.h"
#include "tensorflow/contrib/lite/toco/model_flags.pb.h"
#include "tensorflow/contrib/lite/toco/tooling_util.h"
#include "tensorflow/core/platform/logging.h"

namespace toco {

bool RemoveUnusedOp::Run(Model* model, std::size_t op_index) {
  const auto it = model->operators.begin() + op_index;
  const auto* op = it->get();

  // Bail if any output is used, and is not an input_array of
  // the model. We allow specifying an arbitrary input_array,
  // treating the part of the graph leading up to it as unused.
  for (const auto& output : op->outputs) {
    CHECK(model->HasArray(output));
    // If this output is provided as the model's input array,
    // then we don't need this operator to produce its contents.
    if (IsInputArray(*model, output)) {
      continue;
    }
    // If this output is provided as a RNN's state array,
    // then we don't need this operator to produce its contents.
    // So far this case has only been encountered with TensorFlow
    // Fill ops used to zero-initialize RNN states, which is
    // redundant for us as we zero-initialize RNN states anyway.
    bool found_output_as_rnn_state_array = false;
    for (const auto& rnn_state : model->flags.rnn_states()) {
      if (output == rnn_state.state_array()) {
        CHECK(op->type == OperatorType::kFill ||
              op->type == OperatorType::kTensorFlowIdentity);
        found_output_as_rnn_state_array = true;
        break;
      }
    }
    if (found_output_as_rnn_state_array) {
      continue;
    }
    for (const string& output_array : model->flags.output_arrays()) {
      if (output == output_array) {
        return false;
      }
    }
    for (const auto& rnn_state : model->flags.rnn_states()) {
      if (output == rnn_state.back_edge_source_array()) {
        // The output is consumed by a RNN back-edge..
        if (!IsDiscardableArray(*model, rnn_state.back_edge_source_array()) ||
            !IsDiscardableArray(*model, rnn_state.state_array()) ||
            CountOpsWithInput(*model, rnn_state.state_array())) {
          return false;
        }
      }
    }
    if (CountOpsWithInput(*model, output)) {
      return false;
    }
  }

  if (op->unresolved_outputs) {
    AddMessageF("Not discarding %s because it has unresolved outputs.",
                LogName(*op));
    return false;
  }

  AddMessageF("Discarding %s because none of its outputs is used.",
              LogName(*op));

  // At that point we know that none of the outputs is used, so we will
  // definitely remove the node and all its outputs.

  // Remove any input array that is not used by anything else,
  // and that is not the output of some other operator.
  for (const auto& input : op->inputs) {
    if (IsDiscardableArray(*model, input) &&
        CountOpsWithInput(*model, input) == 1 &&
        !GetOpWithOutput(*model, input)) {
      model->EraseArray(input);
    }
  }

  // Remove the node and its now-unused output arrays.
  for (const auto& output : op->outputs) {
    // If the output array is the model's input array, don't remove that.
    // That's the case when cropping a model at a given --input_array.
    if (!IsDiscardableArray(*model, output)) {
      continue;
    }
    // Likewise, if the output array is a RNN state array, don't remove that.
    bool found_output_as_rnn_state_array = false;
    for (const auto& rnn_state : model->flags.rnn_states()) {
      if (output == rnn_state.state_array()) {
        found_output_as_rnn_state_array = true;
        break;
      }
    }
    if (found_output_as_rnn_state_array) {
      continue;
    }
    // Generic case: do delete this output array.
    model->EraseArray(output);
  }
  model->operators.erase(it);
  return true;
}

}  // namespace toco
<|endoftext|>


<commit_before><commit_msg>Fixed a inputq/outputq mismatch.<commit_after><|endoftext|>


<commit_before>#ifdef CETECH_TEST

/*******************************************************************************
**** Includes
*******************************************************************************/

#include "include/catch/catch.hpp"

extern "C" {
    #include "../string.h"
    #include "../../memory/mallocator.h"
    #include "../../log/log.h"
    #include "../../log/handlers.h"
};

/*******************************************************************************
**** Test helpers
*******************************************************************************/

/*******************************************************************************
**** String duplicate
*******************************************************************************/
SCENARIO( "string duplicate", "[string]" ) {
    GIVEN( "string 'test string'" ) {
        ALLOCATOR_CREATE(allocator, mallocator);

        const char* test_string = "test_string";

        WHEN("duplicate sting") {
            char* duplicate_string = string_duplicate(test_string, allocator); // TODO: LEAK

            THEN("duplicate_string == 'test string'") {
                REQUIRE( string_compare(test_string, duplicate_string) == 0);
            }

            alloc_free(allocator, duplicate_string);
        }

        ALLOCATOR_DESTROY(allocator, mallocator);
    }
}

/*******************************************************************************
**** String compare
*******************************************************************************/
SCENARIO( "string compare", "[string]" ) {
    GIVEN( "string 'test string'" ) {
        const char* lstr = "test_string";
        const char* rstr_ok = "test_string";
        const char* rstr_dif = "test_s";

        WHEN( "compare, \"test_string\" and \"test_string\"") {
            int cmp = string_compare(lstr, rstr_ok);
            int cmp2 = string_compare(rstr_ok, lstr);

            THEN("are eqaul") {
                REQUIRE( cmp == 0);
                REQUIRE( cmp2 == 0);
            }

        } AND_WHEN( "compare, \"test_string\" and \"test_s\"") {
            int cmp = string_compare(lstr, rstr_dif);
            int cmp2 = string_compare(rstr_dif, lstr);

            THEN("are not equal") {
                REQUIRE( cmp  > 0 );
                REQUIRE( cmp2 < 0 );
            }
        }
    }
}

#endif
<commit_msg>string len test<commit_after>#if defined(CETECH_TEST)

/*******************************************************************************
**** Includes
*******************************************************************************/

#include "include/catch/catch.hpp"

extern "C" {
    #include "../string.h"
    #include "../../memory/mallocator.h"
};

/*******************************************************************************
**** Test helpers
*******************************************************************************/

/*******************************************************************************
**** String duplicate
*******************************************************************************/
SCENARIO( "string duplicate", "[string]" ) {
    GIVEN( "string 'test string'" ) {
        ALLOCATOR_CREATE(allocator, mallocator);

        const char* test_string = "test_string";

        WHEN("duplicate sting") {
            char* duplicate_string = string_duplicate(test_string, allocator); // TODO: LEAK

            THEN("duplicate_string == 'test string'") {
                REQUIRE( string_compare(test_string, duplicate_string) == 0);
            }

            alloc_free(allocator, duplicate_string);
        }

        ALLOCATOR_DESTROY(allocator, mallocator);
    }
}

/*******************************************************************************
**** String compare
*******************************************************************************/
SCENARIO( "string compare", "[string]" ) {
    GIVEN( "string 'test_string'" ) {
        const char* lstr = "test_string";
        const char* rstr_ok = "test_string";
        const char* rstr_dif = "test_s";

        WHEN( "compare, \"test_string\" and \"test_string\"") {
            int cmp = string_compare(lstr, rstr_ok);
            int cmp2 = string_compare(rstr_ok, lstr);

            THEN("are eqaul") {
                REQUIRE( cmp == 0);
                REQUIRE( cmp2 == 0);
            }

        } AND_WHEN( "compare, \"test_string\" and \"test_s\"") {
            int cmp = string_compare(lstr, rstr_dif);
            int cmp2 = string_compare(rstr_dif, lstr);

            THEN("are not equal") {
                REQUIRE( cmp  > 0 );
                REQUIRE( cmp2 < 0 );
            }
        }
    }
}

/*******************************************************************************
**** String length
*******************************************************************************/
SCENARIO( "string length", "[string]" ) {
    GIVEN( "string 'test_string'" ) {
        const char* lstr = "test_string";

        WHEN( "lenght \"test_string\" ") {
            size_t len = string_lenght(lstr);

            THEN("len == 11") {
                REQUIRE( len == 11);
            }
        }
    }
}

#endif
<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#ifndef SAL_CONVERTER_CACHE_HXX_
#include "salcvt.hxx"
#endif

SalConverterCache::SalConverterCache()
{
}

SalConverterCache*
SalConverterCache::GetInstance ()
{
    static SalConverterCache* pCvt = NULL;
    if (pCvt == NULL)
        pCvt = new SalConverterCache;

    return pCvt;
}

SalConverterCache::~SalConverterCache()
{
}

// ---> FIXME
#include <stdio.h>
// <---

rtl_UnicodeToTextConverter
SalConverterCache::GetU2TConverter( rtl_TextEncoding nEncoding )
{
    if( rtl_isOctetTextEncoding( nEncoding ) )
    {
        ConverterT& rConverter( m_aConverters[ nEncoding ] );
        if ( rConverter.mpU2T == NULL )
        {
            rConverter.mpU2T =
                rtl_createUnicodeToTextConverter( nEncoding );
// ---> FIXME
if ( rConverter.mpU2T == NULL )
    fprintf( stderr, "failed to create Unicode -> %i converter\n", nEncoding);
// <---
        }
        return rConverter.mpU2T;
    }
    return NULL;
}

rtl_TextToUnicodeConverter
SalConverterCache::GetT2UConverter( rtl_TextEncoding nEncoding )
{
    if( rtl_isOctetTextEncoding( nEncoding ) )
    {
        ConverterT& rConverter( m_aConverters[ nEncoding ] );
        if ( rConverter.mpT2U == NULL )
        {
            rConverter.mpT2U =
                rtl_createTextToUnicodeConverter( nEncoding );
// ---> FIXME
if ( rConverter.mpT2U == NULL )
    fprintf( stderr, "failed to create %i -> Unicode converter\n", nEncoding );
// <---
        }
        return rConverter.mpT2U;
    }
    return NULL;
}

Bool
SalConverterCache::IsSingleByteEncoding( rtl_TextEncoding nEncoding )
{
    if( rtl_isOctetTextEncoding( nEncoding ) )
    {
        ConverterT& rConverter( m_aConverters[ nEncoding ] );
        if ( ! rConverter.mbValid )
        {
            rConverter.mbValid = True;

            rtl_TextEncodingInfo aTextEncInfo;
            aTextEncInfo.StructSize = sizeof( aTextEncInfo );
            rtl_getTextEncodingInfo( nEncoding, &aTextEncInfo );

            if (   aTextEncInfo.MinimumCharSize == aTextEncInfo.MaximumCharSize
                && aTextEncInfo.MinimumCharSize == 1)
                rConverter.mbSingleByteEncoding = True;
            else
                rConverter.mbSingleByteEncoding = False;
        }

        return rConverter.mbSingleByteEncoding;
    }
    return False;
}

// check whether the character set nEncoding contains the unicode
// code point nChar. This list has been compiled from the according
// ttmap files in /usr/openwin/lib/X11/fonts/TrueType/ttmap/
Bool
SalConverterCache::EncodingHasChar( rtl_TextEncoding nEncoding,
        sal_Unicode nChar )
{
    Bool bMatch = False;

    switch ( nEncoding )
    {
        case RTL_TEXTENCODING_DONTKNOW:
            bMatch = False;
            break;

        case RTL_TEXTENCODING_MS_1252:
        case RTL_TEXTENCODING_ISO_8859_1:
        case RTL_TEXTENCODING_ISO_8859_15:
        // handle iso8859-15 and iso8859-1 the same (and both with euro)
        // handle them also like ms1252
        // this is due to the fact that so many X fonts say they are iso8859-1
        // but have the other glyphs anyway because they are really ms1252
            bMatch =    ( /*nChar >= 0x0000 &&*/ nChar <= 0x00ff )
                ||  ( nChar == 0x20ac )
                ||  ( nChar == 0x201a )
                ||  ( nChar == 0x0192 )
                ||  ( nChar == 0x201e )
                ||  ( nChar == 0x2026 )
                ||  ( nChar == 0x2020 )
                ||  ( nChar == 0x2021 )
                ||  ( nChar == 0x02c6 )
                ||  ( nChar == 0x2030 )
                ||  ( nChar == 0x0160 )
                ||  ( nChar == 0x2039 )
                ||  ( nChar == 0x0152 )
                ||  ( nChar == 0x017d )
                ||  ( nChar == 0x2018 )
                ||  ( nChar == 0x2019 )
                ||  ( nChar == 0x201c )
                ||  ( nChar == 0x201d )
                ||  ( nChar == 0x2022 )
                ||  ( nChar == 0x2013 )
                ||  ( nChar == 0x2014 )
                ||  ( nChar == 0x02dc )
                ||  ( nChar == 0x2122 )
                ||  ( nChar == 0x0161 )
                ||  ( nChar == 0x203a )
                ||  ( nChar == 0x0153 )
                ||  ( nChar == 0x017e )
                ||  ( nChar == 0x0178 )
                ;
            break;

        case RTL_TEXTENCODING_ISO_8859_2:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x00a0 && nChar <= 0x017e )
                    ||  ( nChar >= 0x02c7 && nChar <= 0x02dd );
            break;

        case RTL_TEXTENCODING_ISO_8859_4:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x00a0 && nChar <= 0x017e )
                    ||  ( nChar >= 0x02c7 && nChar <= 0x02db );
            break;

        case RTL_TEXTENCODING_ISO_8859_5:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x00a0 && nChar <= 0x00ad )
                    ||  ( nChar >= 0x0401 && nChar <= 0x045f )
                    ||  ( nChar == 0x2116 );
            break;

        case RTL_TEXTENCODING_ISO_8859_6:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x0600 && nChar <= 0x06ff )
                    ||  ( nChar >= 0xfb50 && nChar <= 0xfffe );
            break;

        case RTL_TEXTENCODING_ISO_8859_7:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x00a0 && nChar <= 0x00bd )
                    ||  ( nChar == 0x02bd )
                    ||  ( nChar >= 0x0384 && nChar <= 0x03ce )
                    ||  ( nChar >= 0x2014 && nChar <= 0x2019 );
            break;

        case RTL_TEXTENCODING_ISO_8859_8:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x00a0 && nChar <= 0x00f7 )
                    ||  ( nChar >= 0x05d0 && nChar <= 0x05ea )
                    ||  ( nChar == 0x2017 );
            break;

        case RTL_TEXTENCODING_ISO_8859_9:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x00a0 && nChar <= 0x015f );
             break;

        case RTL_TEXTENCODING_ISO_8859_13:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x00a0 && nChar <= 0x017e )
                    ||  ( nChar >= 0x2019 && nChar <= 0x201e );
            break;

        /* real case for RTL_TEXTENCODING_ISO_8859_15
        case RTL_TEXTENCODING_ISO_8859_15:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x00a0 && nChar <= 0x00ff )
                    ||  ( nChar >= 0x0152 && nChar <= 0x017e )
                    ||  ( nChar == 0x20ac );
            break;
        */

        case RTL_TEXTENCODING_JIS_X_0201:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0xff61 && nChar <= 0xff9f );
            break;

        case RTL_TEXTENCODING_MS_1251:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x00a0 && nChar <= 0x00bb )
                    ||  ( nChar >= 0x0401 && nChar <= 0x045f )
                    ||  ( nChar >= 0x0490 && nChar <= 0x0491 )
                    ||  ( nChar >= 0x2013 && nChar <= 0x203a )
                    ||  ( nChar >= 0x2116 && nChar <= 0x2122 );
            break;

        case RTL_TEXTENCODING_KOI8_R:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x00a0 && nChar <= 0x00b7 )
                    ||  ( nChar == 0x00f7 )
                    ||  ( nChar >= 0x0401 && nChar <= 0x0451 )
                    ||  ( nChar >= 0x2219 && nChar <= 0x221a )
                    ||  ( nChar >= 0x2248 && nChar <= 0x2265 )
                    ||  ( nChar >= 0x2320 && nChar <= 0x2321 )
                    ||  ( nChar >= 0x2500 && nChar <= 0x25a0 );
            break;

        case RTL_TEXTENCODING_UNICODE:
            bMatch = True;
            break;

        case RTL_TEXTENCODING_EUC_KR:
        case RTL_TEXTENCODING_BIG5:
        case RTL_TEXTENCODING_GBK:
        case RTL_TEXTENCODING_GB_2312:
        case RTL_TEXTENCODING_MS_1361:
        case RTL_TEXTENCODING_JIS_X_0208:

            // XXX Big5 and Korean EUC contain Ascii chars, but Solaris
            // *-big5-1 and *-ksc5601.1992-3 fonts dont, in general CJK fonts
            // are monospaced, so dont trust them for latin chars
            if (nChar <= 0xFF)
            {
                bMatch = False;
                break;
            }

        default:
            // XXX really convert the unicode char into the encoding
            // and check for conversion errors, this is expensive !
            rtl_UnicodeToTextConverter aConverter;
            rtl_UnicodeToTextContext   aContext;

            aConverter = GetU2TConverter(nEncoding);
            aContext   = rtl_createUnicodeToTextContext( aConverter );

            // ---> FIXME
            if ( aConverter == NULL )
                return False;
            // <---

            sal_Char   pConversionBuffer[ 32 ];
            sal_uInt32 nConversionInfo;
            sal_Size   nConvertedChars;
            sal_Size   nSize;

            nSize = rtl_convertUnicodeToText( aConverter, aContext,
                    &nChar, 1, pConversionBuffer, sizeof(pConversionBuffer),
                      RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR
                    | RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR,
                    &nConversionInfo, &nConvertedChars );

            rtl_destroyUnicodeToTextContext( aConverter, aContext );

            bMatch =    (nConvertedChars == 1)
                     && (nSize == 1 || nSize == 2) // XXX Fix me this is a hack
                     && ((nConversionInfo & RTL_UNICODETOTEXT_INFO_ERROR) == 0);
            break;
    }

    return bMatch;
}

// wrapper for rtl_convertUnicodeToText that handles the usual cases for
// textconversion in drawtext and gettextwidth routines
sal_Size
SalConverterCache::ConvertStringUTF16( const sal_Unicode *pText, int nTextLen,
        sal_Char *pBuffer, sal_Size nBufferSize, rtl_TextEncoding nEncoding )
{
    rtl_UnicodeToTextConverter aConverter = GetU2TConverter(nEncoding);

    const sal_uInt32 nCvtFlags =
              RTL_UNICODETOTEXT_FLAGS_UNDEFINED_REPLACE
            | RTL_UNICODETOTEXT_FLAGS_UNDEFINED_QUESTIONMARK
            | RTL_UNICODETOTEXT_FLAGS_INVALID_QUESTIONMARK ;
    sal_uInt32  nCvtInfo;
    sal_Size    nCvtChars;

    rtl_UnicodeToTextContext aContext =
             rtl_createUnicodeToTextContext( aConverter );

    sal_Size nSize = rtl_convertUnicodeToText( aConverter, aContext,
                pText, nTextLen, pBuffer, nBufferSize,
                nCvtFlags, &nCvtInfo, &nCvtChars );

    rtl_destroyUnicodeToTextContext( aConverter, aContext );

    return nSize;
}

<commit_msg>INTEGRATION: CWS changefileheader (1.15.484); FILE MERGED 2008/04/01 13:02:00 thb 1.15.484.2: #i85898# Stripping all external header guards 2008/03/28 15:45:27 rt 1.15.484.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: salcvt.cxx,v $
 * $Revision: 1.16 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

SalConverterCache::SalConverterCache()
{
}

SalConverterCache*
SalConverterCache::GetInstance ()
{
    static SalConverterCache* pCvt = NULL;
    if (pCvt == NULL)
        pCvt = new SalConverterCache;

    return pCvt;
}

SalConverterCache::~SalConverterCache()
{
}

// ---> FIXME
#include <stdio.h>
// <---

rtl_UnicodeToTextConverter
SalConverterCache::GetU2TConverter( rtl_TextEncoding nEncoding )
{
    if( rtl_isOctetTextEncoding( nEncoding ) )
    {
        ConverterT& rConverter( m_aConverters[ nEncoding ] );
        if ( rConverter.mpU2T == NULL )
        {
            rConverter.mpU2T =
                rtl_createUnicodeToTextConverter( nEncoding );
// ---> FIXME
if ( rConverter.mpU2T == NULL )
    fprintf( stderr, "failed to create Unicode -> %i converter\n", nEncoding);
// <---
        }
        return rConverter.mpU2T;
    }
    return NULL;
}

rtl_TextToUnicodeConverter
SalConverterCache::GetT2UConverter( rtl_TextEncoding nEncoding )
{
    if( rtl_isOctetTextEncoding( nEncoding ) )
    {
        ConverterT& rConverter( m_aConverters[ nEncoding ] );
        if ( rConverter.mpT2U == NULL )
        {
            rConverter.mpT2U =
                rtl_createTextToUnicodeConverter( nEncoding );
// ---> FIXME
if ( rConverter.mpT2U == NULL )
    fprintf( stderr, "failed to create %i -> Unicode converter\n", nEncoding );
// <---
        }
        return rConverter.mpT2U;
    }
    return NULL;
}

Bool
SalConverterCache::IsSingleByteEncoding( rtl_TextEncoding nEncoding )
{
    if( rtl_isOctetTextEncoding( nEncoding ) )
    {
        ConverterT& rConverter( m_aConverters[ nEncoding ] );
        if ( ! rConverter.mbValid )
        {
            rConverter.mbValid = True;

            rtl_TextEncodingInfo aTextEncInfo;
            aTextEncInfo.StructSize = sizeof( aTextEncInfo );
            rtl_getTextEncodingInfo( nEncoding, &aTextEncInfo );

            if (   aTextEncInfo.MinimumCharSize == aTextEncInfo.MaximumCharSize
                && aTextEncInfo.MinimumCharSize == 1)
                rConverter.mbSingleByteEncoding = True;
            else
                rConverter.mbSingleByteEncoding = False;
        }

        return rConverter.mbSingleByteEncoding;
    }
    return False;
}

// check whether the character set nEncoding contains the unicode
// code point nChar. This list has been compiled from the according
// ttmap files in /usr/openwin/lib/X11/fonts/TrueType/ttmap/
Bool
SalConverterCache::EncodingHasChar( rtl_TextEncoding nEncoding,
        sal_Unicode nChar )
{
    Bool bMatch = False;

    switch ( nEncoding )
    {
        case RTL_TEXTENCODING_DONTKNOW:
            bMatch = False;
            break;

        case RTL_TEXTENCODING_MS_1252:
        case RTL_TEXTENCODING_ISO_8859_1:
        case RTL_TEXTENCODING_ISO_8859_15:
        // handle iso8859-15 and iso8859-1 the same (and both with euro)
        // handle them also like ms1252
        // this is due to the fact that so many X fonts say they are iso8859-1
        // but have the other glyphs anyway because they are really ms1252
            bMatch =    ( /*nChar >= 0x0000 &&*/ nChar <= 0x00ff )
                ||  ( nChar == 0x20ac )
                ||  ( nChar == 0x201a )
                ||  ( nChar == 0x0192 )
                ||  ( nChar == 0x201e )
                ||  ( nChar == 0x2026 )
                ||  ( nChar == 0x2020 )
                ||  ( nChar == 0x2021 )
                ||  ( nChar == 0x02c6 )
                ||  ( nChar == 0x2030 )
                ||  ( nChar == 0x0160 )
                ||  ( nChar == 0x2039 )
                ||  ( nChar == 0x0152 )
                ||  ( nChar == 0x017d )
                ||  ( nChar == 0x2018 )
                ||  ( nChar == 0x2019 )
                ||  ( nChar == 0x201c )
                ||  ( nChar == 0x201d )
                ||  ( nChar == 0x2022 )
                ||  ( nChar == 0x2013 )
                ||  ( nChar == 0x2014 )
                ||  ( nChar == 0x02dc )
                ||  ( nChar == 0x2122 )
                ||  ( nChar == 0x0161 )
                ||  ( nChar == 0x203a )
                ||  ( nChar == 0x0153 )
                ||  ( nChar == 0x017e )
                ||  ( nChar == 0x0178 )
                ;
            break;

        case RTL_TEXTENCODING_ISO_8859_2:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x00a0 && nChar <= 0x017e )
                    ||  ( nChar >= 0x02c7 && nChar <= 0x02dd );
            break;

        case RTL_TEXTENCODING_ISO_8859_4:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x00a0 && nChar <= 0x017e )
                    ||  ( nChar >= 0x02c7 && nChar <= 0x02db );
            break;

        case RTL_TEXTENCODING_ISO_8859_5:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x00a0 && nChar <= 0x00ad )
                    ||  ( nChar >= 0x0401 && nChar <= 0x045f )
                    ||  ( nChar == 0x2116 );
            break;

        case RTL_TEXTENCODING_ISO_8859_6:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x0600 && nChar <= 0x06ff )
                    ||  ( nChar >= 0xfb50 && nChar <= 0xfffe );
            break;

        case RTL_TEXTENCODING_ISO_8859_7:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x00a0 && nChar <= 0x00bd )
                    ||  ( nChar == 0x02bd )
                    ||  ( nChar >= 0x0384 && nChar <= 0x03ce )
                    ||  ( nChar >= 0x2014 && nChar <= 0x2019 );
            break;

        case RTL_TEXTENCODING_ISO_8859_8:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x00a0 && nChar <= 0x00f7 )
                    ||  ( nChar >= 0x05d0 && nChar <= 0x05ea )
                    ||  ( nChar == 0x2017 );
            break;

        case RTL_TEXTENCODING_ISO_8859_9:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x00a0 && nChar <= 0x015f );
             break;

        case RTL_TEXTENCODING_ISO_8859_13:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x00a0 && nChar <= 0x017e )
                    ||  ( nChar >= 0x2019 && nChar <= 0x201e );
            break;

        /* real case for RTL_TEXTENCODING_ISO_8859_15
        case RTL_TEXTENCODING_ISO_8859_15:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x00a0 && nChar <= 0x00ff )
                    ||  ( nChar >= 0x0152 && nChar <= 0x017e )
                    ||  ( nChar == 0x20ac );
            break;
        */

        case RTL_TEXTENCODING_JIS_X_0201:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0xff61 && nChar <= 0xff9f );
            break;

        case RTL_TEXTENCODING_MS_1251:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x00a0 && nChar <= 0x00bb )
                    ||  ( nChar >= 0x0401 && nChar <= 0x045f )
                    ||  ( nChar >= 0x0490 && nChar <= 0x0491 )
                    ||  ( nChar >= 0x2013 && nChar <= 0x203a )
                    ||  ( nChar >= 0x2116 && nChar <= 0x2122 );
            break;

        case RTL_TEXTENCODING_KOI8_R:
            bMatch =    ( nChar >= 0x0020 && nChar <= 0x007e )
                    ||  ( nChar >= 0x00a0 && nChar <= 0x00b7 )
                    ||  ( nChar == 0x00f7 )
                    ||  ( nChar >= 0x0401 && nChar <= 0x0451 )
                    ||  ( nChar >= 0x2219 && nChar <= 0x221a )
                    ||  ( nChar >= 0x2248 && nChar <= 0x2265 )
                    ||  ( nChar >= 0x2320 && nChar <= 0x2321 )
                    ||  ( nChar >= 0x2500 && nChar <= 0x25a0 );
            break;

        case RTL_TEXTENCODING_UNICODE:
            bMatch = True;
            break;

        case RTL_TEXTENCODING_EUC_KR:
        case RTL_TEXTENCODING_BIG5:
        case RTL_TEXTENCODING_GBK:
        case RTL_TEXTENCODING_GB_2312:
        case RTL_TEXTENCODING_MS_1361:
        case RTL_TEXTENCODING_JIS_X_0208:

            // XXX Big5 and Korean EUC contain Ascii chars, but Solaris
            // *-big5-1 and *-ksc5601.1992-3 fonts dont, in general CJK fonts
            // are monospaced, so dont trust them for latin chars
            if (nChar <= 0xFF)
            {
                bMatch = False;
                break;
            }

        default:
            // XXX really convert the unicode char into the encoding
            // and check for conversion errors, this is expensive !
            rtl_UnicodeToTextConverter aConverter;
            rtl_UnicodeToTextContext   aContext;

            aConverter = GetU2TConverter(nEncoding);
            aContext   = rtl_createUnicodeToTextContext( aConverter );

            // ---> FIXME
            if ( aConverter == NULL )
                return False;
            // <---

            sal_Char   pConversionBuffer[ 32 ];
            sal_uInt32 nConversionInfo;
            sal_Size   nConvertedChars;
            sal_Size   nSize;

            nSize = rtl_convertUnicodeToText( aConverter, aContext,
                    &nChar, 1, pConversionBuffer, sizeof(pConversionBuffer),
                      RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR
                    | RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR,
                    &nConversionInfo, &nConvertedChars );

            rtl_destroyUnicodeToTextContext( aConverter, aContext );

            bMatch =    (nConvertedChars == 1)
                     && (nSize == 1 || nSize == 2) // XXX Fix me this is a hack
                     && ((nConversionInfo & RTL_UNICODETOTEXT_INFO_ERROR) == 0);
            break;
    }

    return bMatch;
}

// wrapper for rtl_convertUnicodeToText that handles the usual cases for
// textconversion in drawtext and gettextwidth routines
sal_Size
SalConverterCache::ConvertStringUTF16( const sal_Unicode *pText, int nTextLen,
        sal_Char *pBuffer, sal_Size nBufferSize, rtl_TextEncoding nEncoding )
{
    rtl_UnicodeToTextConverter aConverter = GetU2TConverter(nEncoding);

    const sal_uInt32 nCvtFlags =
              RTL_UNICODETOTEXT_FLAGS_UNDEFINED_REPLACE
            | RTL_UNICODETOTEXT_FLAGS_UNDEFINED_QUESTIONMARK
            | RTL_UNICODETOTEXT_FLAGS_INVALID_QUESTIONMARK ;
    sal_uInt32  nCvtInfo;
    sal_Size    nCvtChars;

    rtl_UnicodeToTextContext aContext =
             rtl_createUnicodeToTextContext( aConverter );

    sal_Size nSize = rtl_convertUnicodeToText( aConverter, aContext,
                pText, nTextLen, pBuffer, nBufferSize,
                nCvtFlags, &nCvtInfo, &nCvtChars );

    rtl_destroyUnicodeToTextContext( aConverter, aContext );

    return nSize;
}

<|endoftext|>


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

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>

#ifndef _FOREIGN_WINDOW_SYSTEM_HXX
#include "FWS.hxx"
#endif

static Atom fwsIconAtom;

static Atom FWS_CLIENT;
static Atom FWS_COMM_WINDOW;
static Atom FWS_PROTOCOLS;
static Atom FWS_STACK_UNDER;
static Atom FWS_PARK_ICONS;
static Atom FWS_PASS_ALL_INPUT;
static Atom FWS_PASSES_INPUT;
static Atom FWS_HANDLES_FOCUS;

static Atom FWS_REGISTER_WINDOW;
static Atom FWS_STATE_CHANGE;
static Atom FWS_UNSEEN_STATE;
static Atom FWS_NORMAL_STATE;
static Atom WM_PROTOCOLS;
static Atom WM_CHANGE_STATE;

static Bool fwsStackUnder;
static Bool fwsParkIcons;
static Bool fwsPassesInput;
static Bool fwsHandlesFocus;

static Window fwsCommWindow;

/*************************************<->***********************************
 *
 * WMSupportsFWS() -
 *
 * Initialize our atoms and determine if the current window manager is
 * providing FWS extension support.
 *
 *************************************<->***********************************/

Bool
WMSupportsFWS (Display *display, int screen)
{
    unsigned int    i;
    Atom            protocol;
    Atom            propType;
    int             propFormat;
    unsigned long   propItems;
    unsigned long   propBytesAfter;
    unsigned char   *propData;
    char            propName[64];

    FWS_CLIENT         = XInternAtom(display, "_SUN_FWS_CLIENT",         False);
    FWS_COMM_WINDOW    = XInternAtom(display, "_SUN_FWS_COMM_WINDOW",    False);
    FWS_PROTOCOLS      = XInternAtom(display, "_SUN_FWS_PROTOCOLS",      False);
    FWS_STACK_UNDER    = XInternAtom(display, "_SUN_FWS_STACK_UNDER",    False);
    FWS_PARK_ICONS     = XInternAtom(display, "_SUN_FWS_PARK_ICONS",     False);
    FWS_PASS_ALL_INPUT = XInternAtom(display, "_SUN_FWS_PASS_ALL_INPUT", False);
    FWS_PASSES_INPUT   = XInternAtom(display, "_SUN_FWS_PASSES_INPUT",   False);
    FWS_HANDLES_FOCUS  = XInternAtom(display, "_SUN_FWS_HANDLES_FOCUS",  False);
    FWS_REGISTER_WINDOW= XInternAtom(display, "_SUN_FWS_REGISTER_WINDOW",False);
    FWS_STATE_CHANGE   = XInternAtom(display, "_SUN_FWS_STATE_CHANGE",   False);
    FWS_UNSEEN_STATE   = XInternAtom(display, "_SUN_FWS_UNSEEN_STATE",   False);
    FWS_NORMAL_STATE   = XInternAtom(display, "_SUN_FWS_NORMAL_STATE",   False);
    WM_PROTOCOLS       = XInternAtom(display, "WM_PROTOCOLS",            False);
    WM_CHANGE_STATE    = XInternAtom(display, "WM_CHANGE_STATE",         False);

    snprintf (propName, sizeof(propName), "_SUN_FWS_NEXT_ICON_%d", screen);
    fwsIconAtom        = XInternAtom(display, propName, False);

    if (XGetWindowProperty (display, DefaultRootWindow (display),
                FWS_COMM_WINDOW, 0, 1,
                False, AnyPropertyType, &propType,
                &propFormat, &propItems,
                &propBytesAfter, &propData) != Success)
        return False;

    if (propFormat != 32 ||
        propItems != 1 ||
        propBytesAfter != 0)
    {
        #if OSL_DEBUG_LEVEL > 1
        fprintf (stderr, "Bad FWS_COMM_WINDOW property on root window.\n");
        #endif
        XFree (propData);
        return False;
    }

    fwsCommWindow = *(Window *) propData;
    #if OSL_DEBUG_LEVEL > 1
    fprintf (stderr, "Using fwsCommWindow = 0x%lx.\n", fwsCommWindow);
    #endif
    XFree (propData);

    if (XGetWindowProperty (display, DefaultRootWindow (display),
            FWS_PROTOCOLS, 0, 10,
            False, AnyPropertyType, &propType,
            &propFormat, &propItems,
            &propBytesAfter, &propData) != Success)
    {
        return False;
    }

    if (propFormat     != 32 ||
        propBytesAfter != 0)
    {
        #if OSL_DEBUG_LEVEL > 1
        fprintf (stderr, "Bad FWS_PROTOCOLS property on root window.\n");
        #endif
        XFree (propData);
        return False;
    }

    for (i = 0; i < propItems; ++i)
    {
        protocol = ((Atom *) propData)[i];
        if (protocol == FWS_STACK_UNDER)
        {
            fwsStackUnder = True;
            #if OSL_DEBUG_LEVEL > 1
            fprintf (stderr, "Using fwsStackUnder.\n");
            #endif
        }
        else
        if (protocol == FWS_PARK_ICONS)
        {
            fwsParkIcons = True;
            #if OSL_DEBUG_LEVEL > 1
            fprintf (stderr, "Using fwsParkIcons.\n");
            #endif
        }
        else
        if (protocol == FWS_PASSES_INPUT)
        {
            fwsPassesInput = True;
            #if OSL_DEBUG_LEVEL > 1
            fprintf (stderr, "Using fwsPassesInput.\n");
            #endif
        }
        else
        if (protocol == FWS_HANDLES_FOCUS)
        {
            fwsHandlesFocus = True;
            #if OSL_DEBUG_LEVEL > 1
            fprintf (stderr, "Using fwsHandlesFocus.\n");
            #endif
        }
    }

    XFree (propData);
    return True;
}

/*************************************<->***********************************
 *
 * newHandler() -
 *
 * Handle X errors (temporarily) to record the occurance of BadWindow
 * errors without crashing.  Used to detect the FWS_COMM_WINDOW root window
 * property containing an old or obsolete window id.
 *
 *************************************<->***********************************/

extern "C" {

static Bool badWindowFound;
static int (* oldHandler) (Display *, XErrorEvent *);

static int
newHandler (Display *display, XErrorEvent *xerror)
{
    if (xerror->error_code != BadWindow)
        (*oldHandler)(display, xerror);
    else
        badWindowFound = True;

    return 0;
}

}

/*************************************<->***********************************
 *
 * RegisterFwsWindow() -
 *
 * Send a client message to the FWS_COMM_WINDOW indicating the existance
 * of a new FWS client window.  Be careful to avoid BadWindow errors on
 * the XSendEvent in case the FWS_COMM_WINDOW root window property had
 * old/obsolete junk in it.
 *
 *************************************<->***********************************/

Bool
RegisterFwsWindow (Display *display, Window window)
{
    XClientMessageEvent  msg;

    msg.type         = ClientMessage;
    msg.window       = fwsCommWindow;
    msg.message_type = FWS_REGISTER_WINDOW;
    msg.format       = 32;
    msg.data.l[0]    = window;

    XSync (display, False);
    badWindowFound = False;
    oldHandler = XSetErrorHandler (newHandler);

    XSendEvent (display, fwsCommWindow, False, NoEventMask,
            (XEvent *) &msg);
    XSync (display, False);

    XSetErrorHandler (oldHandler);
    #if OSL_DEBUG_LEVEL > 1
    if (badWindowFound)
        fprintf (stderr, "No FWS client window to register with.\n");
    #endif

    return !badWindowFound;
}

/*************************************<->***********************************
 *
 * AddFwsProtocols -
 *
 * Add the FWS protocol atoms to the WMProtocols property for the window.
 *
 *************************************<->***********************************/

void
AddFwsProtocols (Display *display, Window window)
{
    #define MAX_FWS_PROTOS 10

    Atom fwsProtocols[ MAX_FWS_PROTOS ];
    int  nProtos = 0;

    fwsProtocols[ nProtos++ ] = FWS_CLIENT;
    fwsProtocols[ nProtos++ ] = FWS_STACK_UNDER;
    fwsProtocols[ nProtos++ ] = FWS_STATE_CHANGE;
    fwsProtocols[ nProtos++ ] = FWS_PASS_ALL_INPUT;
    XChangeProperty (display, window, WM_PROTOCOLS,
            XA_ATOM, 32, PropModeAppend,
            (unsigned char *) fwsProtocols, nProtos);
}

<commit_msg>INTEGRATION: CWS changefileheader (1.6.484); FILE MERGED 2008/04/01 13:02:04 thb 1.6.484.2: #i85898# Stripping all external header guards 2008/03/28 15:45:43 rt 1.6.484.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: FWS.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include "FWS.hxx"

static Atom fwsIconAtom;

static Atom FWS_CLIENT;
static Atom FWS_COMM_WINDOW;
static Atom FWS_PROTOCOLS;
static Atom FWS_STACK_UNDER;
static Atom FWS_PARK_ICONS;
static Atom FWS_PASS_ALL_INPUT;
static Atom FWS_PASSES_INPUT;
static Atom FWS_HANDLES_FOCUS;

static Atom FWS_REGISTER_WINDOW;
static Atom FWS_STATE_CHANGE;
static Atom FWS_UNSEEN_STATE;
static Atom FWS_NORMAL_STATE;
static Atom WM_PROTOCOLS;
static Atom WM_CHANGE_STATE;

static Bool fwsStackUnder;
static Bool fwsParkIcons;
static Bool fwsPassesInput;
static Bool fwsHandlesFocus;

static Window fwsCommWindow;

/*************************************<->***********************************
 *
 * WMSupportsFWS() -
 *
 * Initialize our atoms and determine if the current window manager is
 * providing FWS extension support.
 *
 *************************************<->***********************************/

Bool
WMSupportsFWS (Display *display, int screen)
{
    unsigned int    i;
    Atom            protocol;
    Atom            propType;
    int             propFormat;
    unsigned long   propItems;
    unsigned long   propBytesAfter;
    unsigned char   *propData;
    char            propName[64];

    FWS_CLIENT         = XInternAtom(display, "_SUN_FWS_CLIENT",         False);
    FWS_COMM_WINDOW    = XInternAtom(display, "_SUN_FWS_COMM_WINDOW",    False);
    FWS_PROTOCOLS      = XInternAtom(display, "_SUN_FWS_PROTOCOLS",      False);
    FWS_STACK_UNDER    = XInternAtom(display, "_SUN_FWS_STACK_UNDER",    False);
    FWS_PARK_ICONS     = XInternAtom(display, "_SUN_FWS_PARK_ICONS",     False);
    FWS_PASS_ALL_INPUT = XInternAtom(display, "_SUN_FWS_PASS_ALL_INPUT", False);
    FWS_PASSES_INPUT   = XInternAtom(display, "_SUN_FWS_PASSES_INPUT",   False);
    FWS_HANDLES_FOCUS  = XInternAtom(display, "_SUN_FWS_HANDLES_FOCUS",  False);
    FWS_REGISTER_WINDOW= XInternAtom(display, "_SUN_FWS_REGISTER_WINDOW",False);
    FWS_STATE_CHANGE   = XInternAtom(display, "_SUN_FWS_STATE_CHANGE",   False);
    FWS_UNSEEN_STATE   = XInternAtom(display, "_SUN_FWS_UNSEEN_STATE",   False);
    FWS_NORMAL_STATE   = XInternAtom(display, "_SUN_FWS_NORMAL_STATE",   False);
    WM_PROTOCOLS       = XInternAtom(display, "WM_PROTOCOLS",            False);
    WM_CHANGE_STATE    = XInternAtom(display, "WM_CHANGE_STATE",         False);

    snprintf (propName, sizeof(propName), "_SUN_FWS_NEXT_ICON_%d", screen);
    fwsIconAtom        = XInternAtom(display, propName, False);

    if (XGetWindowProperty (display, DefaultRootWindow (display),
                FWS_COMM_WINDOW, 0, 1,
                False, AnyPropertyType, &propType,
                &propFormat, &propItems,
                &propBytesAfter, &propData) != Success)
        return False;

    if (propFormat != 32 ||
        propItems != 1 ||
        propBytesAfter != 0)
    {
        #if OSL_DEBUG_LEVEL > 1
        fprintf (stderr, "Bad FWS_COMM_WINDOW property on root window.\n");
        #endif
        XFree (propData);
        return False;
    }

    fwsCommWindow = *(Window *) propData;
    #if OSL_DEBUG_LEVEL > 1
    fprintf (stderr, "Using fwsCommWindow = 0x%lx.\n", fwsCommWindow);
    #endif
    XFree (propData);

    if (XGetWindowProperty (display, DefaultRootWindow (display),
            FWS_PROTOCOLS, 0, 10,
            False, AnyPropertyType, &propType,
            &propFormat, &propItems,
            &propBytesAfter, &propData) != Success)
    {
        return False;
    }

    if (propFormat     != 32 ||
        propBytesAfter != 0)
    {
        #if OSL_DEBUG_LEVEL > 1
        fprintf (stderr, "Bad FWS_PROTOCOLS property on root window.\n");
        #endif
        XFree (propData);
        return False;
    }

    for (i = 0; i < propItems; ++i)
    {
        protocol = ((Atom *) propData)[i];
        if (protocol == FWS_STACK_UNDER)
        {
            fwsStackUnder = True;
            #if OSL_DEBUG_LEVEL > 1
            fprintf (stderr, "Using fwsStackUnder.\n");
            #endif
        }
        else
        if (protocol == FWS_PARK_ICONS)
        {
            fwsParkIcons = True;
            #if OSL_DEBUG_LEVEL > 1
            fprintf (stderr, "Using fwsParkIcons.\n");
            #endif
        }
        else
        if (protocol == FWS_PASSES_INPUT)
        {
            fwsPassesInput = True;
            #if OSL_DEBUG_LEVEL > 1
            fprintf (stderr, "Using fwsPassesInput.\n");
            #endif
        }
        else
        if (protocol == FWS_HANDLES_FOCUS)
        {
            fwsHandlesFocus = True;
            #if OSL_DEBUG_LEVEL > 1
            fprintf (stderr, "Using fwsHandlesFocus.\n");
            #endif
        }
    }

    XFree (propData);
    return True;
}

/*************************************<->***********************************
 *
 * newHandler() -
 *
 * Handle X errors (temporarily) to record the occurance of BadWindow
 * errors without crashing.  Used to detect the FWS_COMM_WINDOW root window
 * property containing an old or obsolete window id.
 *
 *************************************<->***********************************/

extern "C" {

static Bool badWindowFound;
static int (* oldHandler) (Display *, XErrorEvent *);

static int
newHandler (Display *display, XErrorEvent *xerror)
{
    if (xerror->error_code != BadWindow)
        (*oldHandler)(display, xerror);
    else
        badWindowFound = True;

    return 0;
}

}

/*************************************<->***********************************
 *
 * RegisterFwsWindow() -
 *
 * Send a client message to the FWS_COMM_WINDOW indicating the existance
 * of a new FWS client window.  Be careful to avoid BadWindow errors on
 * the XSendEvent in case the FWS_COMM_WINDOW root window property had
 * old/obsolete junk in it.
 *
 *************************************<->***********************************/

Bool
RegisterFwsWindow (Display *display, Window window)
{
    XClientMessageEvent  msg;

    msg.type         = ClientMessage;
    msg.window       = fwsCommWindow;
    msg.message_type = FWS_REGISTER_WINDOW;
    msg.format       = 32;
    msg.data.l[0]    = window;

    XSync (display, False);
    badWindowFound = False;
    oldHandler = XSetErrorHandler (newHandler);

    XSendEvent (display, fwsCommWindow, False, NoEventMask,
            (XEvent *) &msg);
    XSync (display, False);

    XSetErrorHandler (oldHandler);
    #if OSL_DEBUG_LEVEL > 1
    if (badWindowFound)
        fprintf (stderr, "No FWS client window to register with.\n");
    #endif

    return !badWindowFound;
}

/*************************************<->***********************************
 *
 * AddFwsProtocols -
 *
 * Add the FWS protocol atoms to the WMProtocols property for the window.
 *
 *************************************<->***********************************/

void
AddFwsProtocols (Display *display, Window window)
{
    #define MAX_FWS_PROTOS 10

    Atom fwsProtocols[ MAX_FWS_PROTOS ];
    int  nProtos = 0;

    fwsProtocols[ nProtos++ ] = FWS_CLIENT;
    fwsProtocols[ nProtos++ ] = FWS_STACK_UNDER;
    fwsProtocols[ nProtos++ ] = FWS_STATE_CHANGE;
    fwsProtocols[ nProtos++ ] = FWS_PASS_ALL_INPUT;
    XChangeProperty (display, window, WM_PROTOCOLS,
            XA_ATOM, 32, PropModeAppend,
            (unsigned char *) fwsProtocols, nProtos);
}

<|endoftext|>