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

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msiquery.h>
#include <malloc.h>

#ifdef UNICODE
#define _UNICODE
#define _tstring    wstring
#else
#define _tstring    string
#endif
#include <tchar.h>
#include <string>
#include <stdio.h>

#ifdef _WIN32_WINNT
#error YES
#endif

#include <systools/win32/uwinapi.h>

#define WININIT_FILENAME    "wininit.ini"
#define RENAME_SECTION      "rename"

static BOOL MoveFileEx9x( LPCSTR lpExistingFileNameA, LPCSTR lpNewFileNameA, DWORD dwFlags )
{
    BOOL    fSuccess = FALSE;   // assume failure

    // Windows 9x has a special mechanism to move files after reboot

    if ( dwFlags & MOVEFILE_DELAY_UNTIL_REBOOT )
    {
        CHAR    szExistingFileNameA[MAX_PATH];
        CHAR    szNewFileNameA[MAX_PATH] = "NUL";

        // Path names in WININIT.INI must be in short path name form

        if (
            GetShortPathNameA( lpExistingFileNameA, szExistingFileNameA, MAX_PATH ) &&
            (!lpNewFileNameA || GetShortPathNameA( lpNewFileNameA, szNewFileNameA, MAX_PATH ))
            )
        {
            CHAR    szBuffer[32767];    // The buffer size must not exceed 32K
            DWORD   dwBufLen = GetPrivateProfileSectionA( RENAME_SECTION, szBuffer, elementsof(szBuffer), WININIT_FILENAME );

            CHAR    szRename[MAX_PATH]; // This is enough for at most to times 67 chracters
            strcpy( szRename, szNewFileNameA );
            strcat( szRename, "=" );
            strcat( szRename, szExistingFileNameA );
            size_t  lnRename = strlen(szRename);

            if ( dwBufLen + lnRename + 2 <= elementsof(szBuffer) )
            {
                CopyMemory( &szBuffer[dwBufLen], szRename, lnRename );
                szBuffer[dwBufLen + lnRename ] = 0;
                szBuffer[dwBufLen + lnRename + 1 ] = 0;

                fSuccess = WritePrivateProfileSectionA( RENAME_SECTION, szBuffer, WININIT_FILENAME );
            }
            else
                SetLastError( ERROR_BUFFER_OVERFLOW );
        }
    }
    else
    {

        fSuccess = MoveFileA( lpExistingFileNameA, lpNewFileNameA );

        if ( !fSuccess && 0 != (dwFlags & (MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING)) )
        {
            BOOL    bFailIfExist = 0 == (dwFlags & MOVEFILE_REPLACE_EXISTING);

            fSuccess = CopyFileA( lpExistingFileNameA, lpNewFileNameA, bFailIfExist );

            // In case of successfull copy do not return FALSE if delete fails.
            // Error detection is done by GetLastError()

            if ( fSuccess )
            {
                SetLastError( NO_ERROR );
                DeleteFileA( lpExistingFileNameA );
            }
        }

    }

    return fSuccess;
}

static BOOL MoveFileExImpl( LPCSTR lpExistingFileNameA, LPCSTR lpNewFileNameA, DWORD dwFlags )
{
    if ( 0 > ((LONG)GetVersion())) // High order bit indicates Win 9x
        return MoveFileEx9x( lpExistingFileNameA, lpNewFileNameA, dwFlags );
    else
        return MoveFileExA( lpExistingFileNameA, lpNewFileNameA, dwFlags );
}

static std::_tstring GetMsiProperty( MSIHANDLE handle, const std::_tstring& sProperty )
{
    std::_tstring   result;
    TCHAR   szDummy[1] = TEXT("");
    DWORD   nChars = 0;

    if ( MsiGetProperty( handle, sProperty.c_str(), szDummy, &nChars ) == ERROR_MORE_DATA )
    {
        DWORD nBytes = ++nChars * sizeof(TCHAR);
        LPTSTR buffer = reinterpret_cast<LPTSTR>(_alloca(nBytes));
        ZeroMemory( buffer, nBytes );
        MsiGetProperty(handle, sProperty.c_str(), buffer, &nChars);
        result = buffer;
    }

    return  result;
}

static bool SwapFiles( const std::_tstring& sFileName1, const std::_tstring& sFileName2 )
{
    std::_tstring   sTempFileName = sFileName1 + TEXT(".tmp");

    bool fSuccess = true;

    //Try to move the original file to a temp file
    fSuccess = MoveFileExImpl( sFileName1.c_str(), sTempFileName.c_str(),
                           MOVEFILE_REPLACE_EXISTING  );

    std::_tstring   mystr;

    if ( fSuccess )
    {
        fSuccess = MoveFileExImpl( sFileName2.c_str(), sFileName1.c_str(), MOVEFILE_REPLACE_EXISTING );

        if ( fSuccess )
        {
            fSuccess = MoveFileExImpl( sTempFileName.c_str(), sFileName2.c_str(),
                                       MOVEFILE_REPLACE_EXISTING );
            if ( !fSuccess )
            {
                MoveFileExImpl( sFileName1.c_str(), sFileName2.c_str(), MOVEFILE_REPLACE_EXISTING );
            }
        }
        else
        {
            MoveFileExImpl( sTempFileName.c_str(), sFileName1.c_str(), MOVEFILE_REPLACE_EXISTING  );
        }
    }
    else
    {
        //It could be that there is no original file and therefore copying the original to a temp
        // file failed. Examine if there is no original and if so then move file2 to file1

        WIN32_FIND_DATA data;
        HANDLE hdl = FindFirstFile(sFileName1.c_str(), &data);
        if (hdl == INVALID_HANDLE_VALUE)
        {
            fSuccess = MoveFileExImpl( sFileName2.c_str(), sFileName1.c_str(), MOVEFILE_REPLACE_EXISTING );

            // if ( fSuccess )
            // {
            //  mystr = "Success";
            //  MessageBox( NULL, mystr.c_str(), "Titel", MB_OK );
            // }
            // else
            // {
            //  char buff[256];
            //  wsprintf(buff, "Failure %d", GetLastError());
            //  MessageBox( NULL, buff, "Titel", MB_OK );
            // }
        }
        else
        {
            FindClose(hdl);
        }
    }

    return fSuccess;
}

static std::_tstring strip( const std::_tstring& s, _TCHAR c )
{
    std::_tstring   result = s;

    std::_tstring::size_type f;

    do
    {
        f = result.find( c );
        if ( f != std::_tstring::npos )
            result.erase( f, 1 );
    } while ( f != std::_tstring::npos );

    return result;
}

extern "C" UINT __stdcall InstallPatchedFiles( MSIHANDLE handle )
{
    std::_tstring   sInstDir = GetMsiProperty( handle, TEXT("INSTALLLOCATION") );
    std::_tstring   sProgramDir = sInstDir + TEXT("program\\");
    std::_tstring   sPatchFile = sProgramDir + TEXT("patchlist.txt");

    TCHAR   szSectionNames[32767];
    TCHAR   szKeyNames[32767];

    // std::_tstring    mystr;
    // mystr = "Patchfile: " + sPatchFile;
    // MessageBox( NULL, mystr.c_str(), "Titel", MB_OK );

    if ( GetPrivateProfileString( NULL, NULL, TEXT(""), szSectionNames, elementsof(szSectionNames), sPatchFile.c_str() ) )
    {
        TCHAR   *pSectionName = szSectionNames;

        while ( *pSectionName )
        {
            std::_tstring   sSectionName = pSectionName;
            if ( std::_tstring(TEXT("_root")) == sSectionName ) { sSectionName = TEXT(""); }
            // mystr = "Section: " + sSectionName;
            // MessageBox( NULL, mystr.c_str(), "Titel", MB_OK );

            if ( GetPrivateProfileString( pSectionName, NULL, TEXT(""), szKeyNames, elementsof(szKeyNames), sPatchFile.c_str() ) )
            {
                TCHAR   *pKeyName = szKeyNames;

                while ( *pKeyName )
                {
                    TCHAR   szValue[4096];

                    if ( GetPrivateProfileString( pSectionName, pKeyName, TEXT(""), szValue, elementsof(szValue), sPatchFile.c_str() ) )
                    {
                        std::_tstring   sFileName1 = pKeyName;
                        std::_tstring   sExtension = szValue;
                        std::_tstring   sFileName2;

                        sFileName1 = strip( sFileName1, '\"' );
                        sExtension = strip( sExtension, '\"' );

                        sFileName1 = sInstDir + sSectionName + sFileName1;
                        sFileName2 = sFileName1 + sExtension;

                        // mystr = "Convert: " + sFileName1 + " to " + sFileName2;
                        // MessageBox( NULL, mystr.c_str(), "Titel", MB_OK );

                        SwapFiles( sFileName1, sFileName2 );
                    }

                    pKeyName += _tcslen(pKeyName) + 1;
                }
            }

            pSectionName += _tcslen(pSectionName) + 1;
        }
    }

    return ERROR_SUCCESS;
}

extern "C" UINT __stdcall UninstallPatchedFiles( MSIHANDLE handle )
{
    TCHAR   szValue[8192];
    DWORD   nValueSize = sizeof(szValue);
    HKEY    hKey;

    std::_tstring   sInstDir;

    std::_tstring   sProductKey = GetMsiProperty( handle, TEXT("FINDPRODUCT") );

    if ( ERROR_SUCCESS == RegOpenKey( HKEY_CURRENT_USER,  sProductKey.c_str(), &hKey ) )
    {
        if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("INSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
        {
            sInstDir = szValue;
        }
        RegCloseKey( hKey );
    }
    else if ( ERROR_SUCCESS == RegOpenKey( HKEY_LOCAL_MACHINE,  sProductKey.c_str(), &hKey ) )
    {
        if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("INSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
        {
            sInstDir = szValue;
        }
        RegCloseKey( hKey );
    }
    else
        return ERROR_SUCCESS;

    std::_tstring   sProgramDir = sInstDir + TEXT("program\\");
    std::_tstring   sPatchFile = sProgramDir + TEXT("patchlist.txt");

    TCHAR   szSectionNames[32767];
    TCHAR   szKeyNames[32767];

    // std::_tstring    mystr;
    // mystr = "Patchfile: " + sPatchFile;
    // MessageBox( NULL, mystr.c_str(), "Titel", MB_OK );

    if ( GetPrivateProfileString( NULL, NULL, TEXT(""), szSectionNames, elementsof(szSectionNames), sPatchFile.c_str() ) )
    {
        TCHAR   *pSectionName = szSectionNames;

        while ( *pSectionName )
        {
            std::_tstring   sSectionName = pSectionName;
            if ( std::_tstring(TEXT("_root")) == sSectionName ) { sSectionName = TEXT(""); }
            // mystr = "Section: " + sSectionName;
            // MessageBox( NULL, mystr.c_str(), "Titel", MB_OK );

            if ( GetPrivateProfileString( pSectionName, NULL, TEXT(""), szKeyNames, elementsof(szKeyNames), sPatchFile.c_str() ) )
            {
                TCHAR   *pKeyName = szKeyNames;

                while ( *pKeyName )
                {
                    TCHAR   szValue[4096];

                    if ( GetPrivateProfileString( pSectionName, pKeyName, TEXT(""), szValue, elementsof(szValue), sPatchFile.c_str() ) )
                    {
                        std::_tstring   sFileName1 = pKeyName;
                        std::_tstring   sExtension = szValue;
                        std::_tstring   sFileName2;

                        sFileName1 = strip( sFileName1, '\"' );
                        sExtension = strip( sExtension, '\"' );

                        sFileName1 = sInstDir + sSectionName + sFileName1;
                        sFileName2 = sFileName1 + sExtension;

                        // mystr = "Convert: " + sFileName1 + " to " + sFileName2;
                        // MessageBox( NULL, mystr.c_str(), "Titel", MB_OK );

                        SwapFiles( sFileName2, sFileName1 );
                    }

                    pKeyName += _tcslen(pKeyName) + 1;
                }
            }

            pSectionName += _tcslen(pSectionName) + 1;
        }
    }

    return ERROR_SUCCESS;
}

<commit_msg>INTEGRATION: CWS hro03 (1.7.10); FILE MERGED 2006/02/14 16:02:13 hro 1.7.10.3: #b6369183# Fix Win9x MoveFileEx Emulation 2006/02/13 13:47:09 hro 1.7.10.2: #b6369183# Test wether office process is running by trying to rename vcl resource files 2006/02/13 13:10:17 hro 1.7.10.1: #b6369183# Test wether office process is running by trying to rename vcl resource files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: swappatchfiles.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2006-02-17 13:28:18 $
 *
 *  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
 *
 ************************************************************************/

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msiquery.h>
#include <malloc.h>

#ifdef UNICODE
#define _UNICODE
#define _tstring    wstring
#else
#define _tstring    string
#endif
#include <tchar.h>
#include <string>
#include <stdio.h>

#ifdef _WIN32_WINNT
#error YES
#endif

#include <systools/win32/uwinapi.h>

#define WININIT_FILENAME    "wininit.ini"
#define RENAME_SECTION      "rename"

static BOOL MoveFileEx9x( LPCSTR lpExistingFileNameA, LPCSTR lpNewFileNameA, DWORD dwFlags )
{
    BOOL    fSuccess = FALSE;   // assume failure

    // Windows 9x has a special mechanism to move files after reboot

    if ( dwFlags & MOVEFILE_DELAY_UNTIL_REBOOT )
    {
        CHAR    szExistingFileNameA[MAX_PATH];
        CHAR    szNewFileNameA[MAX_PATH] = "NUL";

        // Path names in WININIT.INI must be in short path name form

        if (
            GetShortPathNameA( lpExistingFileNameA, szExistingFileNameA, MAX_PATH ) &&
            (!lpNewFileNameA || GetShortPathNameA( lpNewFileNameA, szNewFileNameA, MAX_PATH ))
            )
        {
            CHAR    szBuffer[32767];    // The buffer size must not exceed 32K
            DWORD   dwBufLen = GetPrivateProfileSectionA( RENAME_SECTION, szBuffer, elementsof(szBuffer), WININIT_FILENAME );

            CHAR    szRename[MAX_PATH]; // This is enough for at most to times 67 chracters
            strcpy( szRename, szNewFileNameA );
            strcat( szRename, "=" );
            strcat( szRename, szExistingFileNameA );
            size_t  lnRename = strlen(szRename);

            if ( dwBufLen + lnRename + 2 <= elementsof(szBuffer) )
            {
                CopyMemory( &szBuffer[dwBufLen], szRename, lnRename );
                szBuffer[dwBufLen + lnRename ] = 0;
                szBuffer[dwBufLen + lnRename + 1 ] = 0;

                fSuccess = WritePrivateProfileSectionA( RENAME_SECTION, szBuffer, WININIT_FILENAME );
            }
            else
                SetLastError( ERROR_BUFFER_OVERFLOW );
        }
    }
    else
    {

        fSuccess = MoveFileA( lpExistingFileNameA, lpNewFileNameA );

        if ( !fSuccess && GetLastError() != ERROR_ACCESS_DENIED &&
            0 != (dwFlags & (MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING)) )
        {
            BOOL    bFailIfExist = 0 == (dwFlags & MOVEFILE_REPLACE_EXISTING);

            fSuccess = CopyFileA( lpExistingFileNameA, lpNewFileNameA, bFailIfExist );

            if ( fSuccess )
                fSuccess = DeleteFileA( lpExistingFileNameA );
        }

    }

    return fSuccess;
}

static BOOL MoveFileExImpl( LPCSTR lpExistingFileNameA, LPCSTR lpNewFileNameA, DWORD dwFlags )
{
    if ( 0 > ((LONG)GetVersion())) // High order bit indicates Win 9x
        return MoveFileEx9x( lpExistingFileNameA, lpNewFileNameA, dwFlags );
    else
        return MoveFileExA( lpExistingFileNameA, lpNewFileNameA, dwFlags );
}

static std::_tstring GetMsiProperty( MSIHANDLE handle, const std::_tstring& sProperty )
{
    std::_tstring   result;
    TCHAR   szDummy[1] = TEXT("");
    DWORD   nChars = 0;

    if ( MsiGetProperty( handle, sProperty.c_str(), szDummy, &nChars ) == ERROR_MORE_DATA )
    {
        DWORD nBytes = ++nChars * sizeof(TCHAR);
        LPTSTR buffer = reinterpret_cast<LPTSTR>(_alloca(nBytes));
        ZeroMemory( buffer, nBytes );
        MsiGetProperty(handle, sProperty.c_str(), buffer, &nChars);
        result = buffer;
    }

    return  result;
}

static bool SwapFiles( const std::_tstring& sFileName1, const std::_tstring& sFileName2 )
{
    std::_tstring   sTempFileName = sFileName1 + TEXT(".tmp");

    bool fSuccess = true;

    //Try to move the original file to a temp file
    fSuccess = MoveFileExImpl( sFileName1.c_str(), sTempFileName.c_str(),
                           MOVEFILE_REPLACE_EXISTING  );

    std::_tstring   mystr;

    if ( fSuccess )
    {
        fSuccess = MoveFileExImpl( sFileName2.c_str(), sFileName1.c_str(), MOVEFILE_REPLACE_EXISTING );

        if ( fSuccess )
        {
            fSuccess = MoveFileExImpl( sTempFileName.c_str(), sFileName2.c_str(),
                                       MOVEFILE_REPLACE_EXISTING );
            if ( !fSuccess )
            {
                MoveFileExImpl( sFileName1.c_str(), sFileName2.c_str(), MOVEFILE_REPLACE_EXISTING );
            }
        }
        else
        {
            MoveFileExImpl( sTempFileName.c_str(), sFileName1.c_str(), MOVEFILE_REPLACE_EXISTING  );
        }
    }
    else
    {
        //It could be that there is no original file and therefore copying the original to a temp
        // file failed. Examine if there is no original and if so then move file2 to file1

        WIN32_FIND_DATA data;
        HANDLE hdl = FindFirstFile(sFileName1.c_str(), &data);
        if (hdl == INVALID_HANDLE_VALUE)
        {
            fSuccess = MoveFileExImpl( sFileName2.c_str(), sFileName1.c_str(), MOVEFILE_REPLACE_EXISTING );

            // if ( fSuccess )
            // {
            //  mystr = "Success";
            //  MessageBox( NULL, mystr.c_str(), "Titel", MB_OK );
            // }
            // else
            // {
            //  char buff[256];
            //  wsprintf(buff, "Failure %d", GetLastError());
            //  MessageBox( NULL, buff, "Titel", MB_OK );
            // }
        }
        else
        {
            FindClose(hdl);
        }
    }

    return fSuccess;
}

static std::_tstring strip( const std::_tstring& s, _TCHAR c )
{
    std::_tstring   result = s;

    std::_tstring::size_type f;

    do
    {
        f = result.find( c );
        if ( f != std::_tstring::npos )
            result.erase( f, 1 );
    } while ( f != std::_tstring::npos );

    return result;
}

extern "C" UINT __stdcall InstallPatchedFiles( MSIHANDLE handle )
{
    std::_tstring   sInstDir = GetMsiProperty( handle, TEXT("INSTALLLOCATION") );
    std::_tstring   sProgramDir = sInstDir + TEXT("program\\");
    std::_tstring   sPatchFile = sProgramDir + TEXT("patchlist.txt");

    TCHAR   szSectionNames[32767];
    TCHAR   szKeyNames[32767];

    // std::_tstring    mystr;
    // mystr = "Patchfile: " + sPatchFile;
    // MessageBox( NULL, mystr.c_str(), "Titel", MB_OK );

    if ( GetPrivateProfileString( NULL, NULL, TEXT(""), szSectionNames, elementsof(szSectionNames), sPatchFile.c_str() ) )
    {
        TCHAR   *pSectionName = szSectionNames;

        while ( *pSectionName )
        {
            std::_tstring   sSectionName = pSectionName;
            if ( std::_tstring(TEXT("_root")) == sSectionName ) { sSectionName = TEXT(""); }
            // mystr = "Section: " + sSectionName;
            // MessageBox( NULL, mystr.c_str(), "Titel", MB_OK );

            if ( GetPrivateProfileString( pSectionName, NULL, TEXT(""), szKeyNames, elementsof(szKeyNames), sPatchFile.c_str() ) )
            {
                TCHAR   *pKeyName = szKeyNames;

                while ( *pKeyName )
                {
                    TCHAR   szValue[4096];

                    if ( GetPrivateProfileString( pSectionName, pKeyName, TEXT(""), szValue, elementsof(szValue), sPatchFile.c_str() ) )
                    {
                        std::_tstring   sFileName1 = pKeyName;
                        std::_tstring   sExtension = szValue;
                        std::_tstring   sFileName2;

                        sFileName1 = strip( sFileName1, '\"' );
                        sExtension = strip( sExtension, '\"' );

                        sFileName1 = sInstDir + sSectionName + sFileName1;
                        sFileName2 = sFileName1 + sExtension;

                        // mystr = "Convert: " + sFileName1 + " to " + sFileName2;
                        // MessageBox( NULL, mystr.c_str(), "Titel", MB_OK );

                        SwapFiles( sFileName1, sFileName2 );
                    }

                    pKeyName += _tcslen(pKeyName) + 1;
                }
            }

            pSectionName += _tcslen(pSectionName) + 1;
        }
    }

    return ERROR_SUCCESS;
}

extern "C" UINT __stdcall UninstallPatchedFiles( MSIHANDLE handle )
{
    TCHAR   szValue[8192];
    DWORD   nValueSize = sizeof(szValue);
    HKEY    hKey;

    std::_tstring   sInstDir;

    std::_tstring   sProductKey = GetMsiProperty( handle, TEXT("FINDPRODUCT") );

    if ( ERROR_SUCCESS == RegOpenKey( HKEY_CURRENT_USER,  sProductKey.c_str(), &hKey ) )
    {
        if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("INSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
        {
            sInstDir = szValue;
        }
        RegCloseKey( hKey );
    }
    else if ( ERROR_SUCCESS == RegOpenKey( HKEY_LOCAL_MACHINE,  sProductKey.c_str(), &hKey ) )
    {
        if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("INSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
        {
            sInstDir = szValue;
        }
        RegCloseKey( hKey );
    }
    else
        return ERROR_SUCCESS;

    std::_tstring   sProgramDir = sInstDir + TEXT("program\\");
    std::_tstring   sPatchFile = sProgramDir + TEXT("patchlist.txt");

    TCHAR   szSectionNames[32767];
    TCHAR   szKeyNames[32767];

    // std::_tstring    mystr;
    // mystr = "Patchfile: " + sPatchFile;
    // MessageBox( NULL, mystr.c_str(), "Titel", MB_OK );

    if ( GetPrivateProfileString( NULL, NULL, TEXT(""), szSectionNames, elementsof(szSectionNames), sPatchFile.c_str() ) )
    {
        TCHAR   *pSectionName = szSectionNames;

        while ( *pSectionName )
        {
            std::_tstring   sSectionName = pSectionName;
            if ( std::_tstring(TEXT("_root")) == sSectionName ) { sSectionName = TEXT(""); }
            // mystr = "Section: " + sSectionName;
            // MessageBox( NULL, mystr.c_str(), "Titel", MB_OK );

            if ( GetPrivateProfileString( pSectionName, NULL, TEXT(""), szKeyNames, elementsof(szKeyNames), sPatchFile.c_str() ) )
            {
                TCHAR   *pKeyName = szKeyNames;

                while ( *pKeyName )
                {
                    TCHAR   szValue[4096];

                    if ( GetPrivateProfileString( pSectionName, pKeyName, TEXT(""), szValue, elementsof(szValue), sPatchFile.c_str() ) )
                    {
                        std::_tstring   sFileName1 = pKeyName;
                        std::_tstring   sExtension = szValue;
                        std::_tstring   sFileName2;

                        sFileName1 = strip( sFileName1, '\"' );
                        sExtension = strip( sExtension, '\"' );

                        sFileName1 = sInstDir + sSectionName + sFileName1;
                        sFileName2 = sFileName1 + sExtension;

                        // mystr = "Convert: " + sFileName1 + " to " + sFileName2;
                        // MessageBox( NULL, mystr.c_str(), "Titel", MB_OK );

                        SwapFiles( sFileName2, sFileName1 );
                    }

                    pKeyName += _tcslen(pKeyName) + 1;
                }
            }

            pSectionName += _tcslen(pSectionName) + 1;
        }
    }

    return ERROR_SUCCESS;
}

extern "C" UINT __stdcall IsOfficeRunning( MSIHANDLE handle )
{
    std::_tstring   sInstDir = GetMsiProperty( handle, TEXT("INSTALLLOCATION") );
    std::_tstring   sResourceDir = sInstDir + TEXT("program\\resource\\");
    std::_tstring   sPattern = sResourceDir + TEXT("vcl*.res");

    WIN32_FIND_DATA aFindFileData;
    HANDLE  hFind = FindFirstFile( sPattern.c_str(), &aFindFileData );

    if ( IsValidHandle(hFind) )
    {
        BOOL    fSuccess;
        bool    fRenameSucceeded;

        do
        {
            std::_tstring   sResourceFile = sResourceDir + aFindFileData.cFileName;
            std::_tstring   sIntermediate = sResourceFile + TEXT(".tmp");

            fRenameSucceeded = MoveFileExImpl( sResourceFile.c_str(), sIntermediate.c_str(), MOVEFILE_REPLACE_EXISTING );
            if ( fRenameSucceeded )
            {
                MoveFileExImpl( sIntermediate.c_str(), sResourceFile.c_str(), 0 );
                fSuccess = FindNextFile( hFind, &aFindFileData );
            }
        } while ( fSuccess && fRenameSucceeded );

        if ( !fRenameSucceeded )
            MsiSetProperty(handle, TEXT("OFFICERUNS"), TEXT("1"));

        FindClose( hFind );
    }

    return ERROR_SUCCESS;
}

<|endoftext|>


<commit_before>#pragma once

#include "cl/tags.hxx"
#include "cl/boolean_argument.hxx"
#include "cl/integer_argument.hxx"
#include "cl/positional_argument.hxx"
#include "cl/free_argument.hxx"
#include "cl/string_argument.hxx"
#include "cl/handler.hxx"
#include "cl/enum_argument.hxx"

<commit_msg>Added missing header files to top level include file.<commit_after>#pragma once

#include "cl/tags.hxx"
#include "cl/boolean_argument.hxx"
#include "cl/integer_argument.hxx"
#include "cl/positional_argument.hxx"
#include "cl/free_argument.hxx"
#include "cl/string_argument.hxx"
#include "cl/handler.hxx"
#include "cl/enum_argument.hxx"
#include "cl/custom_argument.hxx"
#include "cl/switch_argument.hxx"
#include "cl/floating_argument.hxx"
<|endoftext|>


<commit_before>// Example of macro illustrating how to write a TClonesArray to a TTree
// the following tests can be run
//    Interactive tests
// Root > .x tcl.C        //no-split interpreted
// Root > .x tcl.C(1)     //split    interpreted
// Root > .x tcl.C++      //no-split compiled
// Root > .x tcl.C++(1)   //split    compiled
//    batch tests: same as above but with no graphics
// root -b -q tcl.C
// root -b -q tcl.C++
// root -b -q "tcl.C(1)"
// root -b -q "tcl.C++(1)"

#include "TFile.h"
#include "TClonesArray.h"
#include "TH2.h"
#include "TLine.h"
#include "TTree.h"
#include "TBenchmark.h"
#include "TRandom.h"

void tclwrite(Int_t split)
{
// Generate a Tree with a TClonesArray
// The array can be split or not
   TFile f("tcl.root","recreate");
   f.SetCompressionLevel(1); //try level 2 also
   TTree T("T","test tcl");
   TClonesArray *arr = new TClonesArray("TLine");
   TClonesArray &ar = *arr;
   T.Branch("tcl",&arr,256000,split);
   for (Int_t ev=0;ev<10000;ev++) {
      ar.Clear();
      Int_t nlines = Int_t(gRandom->Gaus(50,10));
      if(nlines < 0) nlines = 1;
      for (Int_t i=0;i<nlines;i++) {
         Float_t x1 = gRandom->Rndm();
         Float_t y1 = gRandom->Rndm();
         Float_t x2 = gRandom->Rndm();
         Float_t y2 = gRandom->Rndm();
         new(ar[i]) TLine(x1,y1,x2,y2);
      }
      T.Fill();
   }
   T.Print();
   T.Write();
}

void tclread()
{
// read file generated by tclwrite
// loop on all entries.
// histogram center of lines
   TFile *f = new TFile("tcl.root");
   TTree *T = (TTree*)f->Get("T");
   TH2F *h2 = new TH2F("h2","center of lines",40,0,1,40,0,1);

   TClonesArray *arr = 0;
   T->GetBranch("tcl")->SetAutoDelete(kFALSE);
   T->SetBranchAddress("tcl",&arr);
   Int_t nentries = (Int_t)(T->GetEntries());
   for (Int_t ev=0;ev<nentries;ev++) {
      arr->Clear();
      T->GetEntry(ev);
      Int_t nlines = arr->GetEntriesFast();
      for (Int_t i=0;i<nlines;i++) {
         TLine *line = (TLine*)arr->At(i);
         h2->Fill(0.5*(line->GetX1()+line->GetX2()), 0.5*(line->GetY1()+line->GetY2()));
      }
   }
   h2->Draw("lego");
}

void tcl(Int_t split=0)
{
   gBenchmark->Start("tcl");
   tclwrite(split);
   tclread();
   gBenchmark->Show("tcl");
}
<commit_msg>Add comments explaining what BypassStreamer is doing.<commit_after>// Example of macro illustrating how to write a TClonesArray to a TTree
// the following tests can be run
//    Interactive tests
// Root > .x tcl.C        //no-split interpreted
// Root > .x tcl.C(1)     //split    interpreted
// Root > .x tcl.C++      //no-split compiled
// Root > .x tcl.C++(1)   //split    compiled
//    batch tests: same as above but with no graphics
// root -b -q tcl.C
// root -b -q tcl.C++
// root -b -q "tcl.C(1)"
// root -b -q "tcl.C++(1)"

#include "TFile.h"
#include "TClonesArray.h"
#include "TH2.h"
#include "TLine.h"
#include "TTree.h"
#include "TBenchmark.h"
#include "TRandom.h"

void tclwrite(Int_t split)
{
// Generate a Tree with a TClonesArray
// The array can be split or not
   TFile f("tcl.root","recreate");
   f.SetCompressionLevel(1); //try level 2 also
   TTree T("T","test tcl");
   TClonesArray *arr = new TClonesArray("TLine");
   TClonesArray &ar = *arr;
   T.Branch("tcl",&arr,256000,split);
   //By default a TClonesArray is created with its BypassStreamer bit set.
   //However, because TLine has a custom Streamer, this bit was reset
   //by TTree::Branch above. We set again this bit because the current
   //version of TLine uses the automatic Streamer.
   //BypassingStreamer saves space and time.
   arr->BypassStreamer();
   for (Int_t ev=0;ev<10000;ev++) {
      ar.Clear();
      Int_t nlines = Int_t(gRandom->Gaus(50,10));
      if(nlines < 0) nlines = 1;
      for (Int_t i=0;i<nlines;i++) {
         Float_t x1 = gRandom->Rndm();
         Float_t y1 = gRandom->Rndm();
         Float_t x2 = gRandom->Rndm();
         Float_t y2 = gRandom->Rndm();
         new(ar[i]) TLine(x1,y1,x2,y2);
      }
      T.Fill();
   }
   T.Print();
   T.Write();
}

void tclread()
{
// read file generated by tclwrite
// loop on all entries.
// histogram center of lines
   TFile *f = new TFile("tcl.root");
   TTree *T = (TTree*)f->Get("T");
   TH2F *h2 = new TH2F("h2","center of lines",40,0,1,40,0,1);

   TClonesArray *arr = 0;
   T->GetBranch("tcl")->SetAutoDelete(kFALSE);
   T->SetBranchAddress("tcl",&arr);
   Int_t nentries = (Int_t)(T->GetEntries());
   for (Int_t ev=0;ev<nentries;ev++) {
      arr->Clear();
      T->GetEntry(ev);
      Int_t nlines = arr->GetEntriesFast();
      for (Int_t i=0;i<nlines;i++) {
         TLine *line = (TLine*)arr->At(i);
         h2->Fill(0.5*(line->GetX1()+line->GetX2()), 0.5*(line->GetY1()+line->GetY2()));
      }
   }
   h2->Draw("lego");
}

void tcl(Int_t split=0)
{
   gBenchmark->Start("tcl");
   tclwrite(split);
   tclread();
   gBenchmark->Show("tcl");
}
<|endoftext|>


<commit_before>#include "Client.hpp"
#include "Server.hpp"
#include <stdio.h>

/* Try#1 */
/*
typedef char False;
typedef struct { char data[100]; } True;

template<class T> True is_polymorphic(T * ptr, void const * retVal = dynamic_cast<void const*>(ptr));
False is_polymorphic(...);
*/

/* Try #2 */
template<class T> class PolymorphicTestHelper : T
{
	virtual ~PolymorphicTestHelper() {}
};

template<class T> inline bool isPolymorphic()
{
	return sizeof(PolymorphicTestHelper<T>) == sizeof(T);
}

int main()
{
	int const size_of_Client = sizeof(Client);
	int const size_of_PolymorphicTestHelper = sizeof(PolymorphicTestHelper<Client>);

	if(isPolymorphic<Client>())
		printf("Client - polymorphic\n");
	else
		printf("Client - non-polymorphic\n");

	if(isPolymorphic<Server>())
		printf("Server - polymorphic\n");
	else
		printf("Server - non-polymorphic\n");

	Server * server1 = new Server("Server1");
	Server * server2 = new Server("Server2");

	{
		Client client;
		client.setServer(server1);
		printf("{1}\n");
		client.test();
	}

	static float const data1[] = {1.1111f, 2.2222f };
	static float const data2[] = {3.3333f, 4.4444f };
	static float const data3[] = {5.5555f, 6.6666f };

	server1->processData(2, data1);

	{
		Client client;

		server1->dataArrived().connect(&client, &Client::registerData, server1);
		server2->dataArrived().connect(&client, &Client::registerData, server2);

		printf("{2}\n");
		server1->processData(2, data2);
		server2->processData(2, data3);
		printf("{3}\n");
		client.test();
		printf("{4}\n");
		client.setServer(server1);
		server1->processData(2, data2);
		server2->processData(2, data3);
		printf("{5}\n");
		client.setServer(server2);
		server1->processData(2, data2);
		server2->processData(2, data3);
		printf("{6}\n");
		client.setServer(0);
		server1->processData(2, data2);
		server2->processData(2, data3);
		printf("{7}\n");

		server2->dataArrived().disconnectFrom(&client);
		server1->dataArrived().disconnectFrom(&client);
	}

	server1->processData(2, data2);
	server2->processData(2, data3);

	printf("{8}\n");

	delete server1; delete server2;
	return 0;
}<commit_msg>-: src/Cpp/Events/main.cpp deleted (rubbish)<commit_after><|endoftext|>


<commit_before>#include "NotificationLoader.h"

CNotificationLoader::CNotificationLoader()
{
	m_hNotificationDLL			= NULL;
	lpfn_Notify_FindClose		= NULL;
	lpfn_Notify_FindFirst		= NULL;
	lpfn_Notify_FindNext		= NULL;
	lpfn_Notify_SetCycleInfo	= NULL;
	lpfn_Notify_GetCycleInfo	= NULL;
	lpfn_Notify_SetState		= NULL;
	lpfn_Notify_GetState		= NULL;
	int m_iBeeperIndex			= -1;
	int m_iVibrateIndex			= -1;
}

CNotificationLoader::~CNotificationLoader()
{
	UnloadNotificationDLL();
}

//  Loading Notification DLL dynamically
BOOL CNotificationLoader::LoadNotificationDLL()
{
	m_hNotificationDLL = LoadLibrary(NOTIFY_DLL);
	if (!m_hNotificationDLL)
	{
		return FALSE;
	}
	//  Map the function pointers to functions exported from the DLL
	lpfn_Notify_FindClose = (LPFN_NOTIFY_FINDCLOSE_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_FindClose");
	lpfn_Notify_FindNext = (LPFN_NOTIFY_FINDNEXT_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_FindNext");
	lpfn_Notify_FindFirst = (LPFN_NOTIFY_FINDFIRST_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_FindFirst");
	lpfn_Notify_SetCycleInfo = (LPFN_NOTIFY_SETCYCLEINFO_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_SetCycleInfo");
	lpfn_Notify_GetCycleInfo = (LPFN_NOTIFY_GETCYCLEINFO_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_GetCycleInfo");
	lpfn_Notify_SetState = (LPFN_NOTIFY_SETSTATE_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_SetState");
	lpfn_Notify_GetState = (LPFN_NOTIFY_GETSTATE_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_GetState");

	if (lpfn_Notify_FindClose	== NULL ||
		lpfn_Notify_FindNext	== NULL ||
		lpfn_Notify_FindFirst	== NULL ||
		lpfn_Notify_SetCycleInfo== NULL ||
		lpfn_Notify_GetCycleInfo== NULL ||
		lpfn_Notify_SetState	== NULL ||
		lpfn_Notify_GetState	== NULL)
	{
		m_hNotificationDLL = NULL;
		return FALSE;
	}
	else
	{
		//  Set the indices of the beeper and vibrate index
		NOTIFY_FINDINFO notifyObject;
		HANDLE	hFindHandle = NULL;
		SI_ALLOC_ALL(&notifyObject);
		notifyObject.StructInfo.dwUsed = 0;
		if(lpfn_Notify_FindFirst(&notifyObject, &hFindHandle) == E_NTFY_SUCCESS)
		{
			int iObCount = 0;
			do
			{
				if(notifyObject.dwObjectType == NOTIFY_TYPE_BEEPER)
				{
					//  Found the Beeper
					m_iBeeperIndex = iObCount;
					continue;
				}
				else if (notifyObject.dwObjectType == NOTIFY_TYPE_VIBRATOR)
				{
					m_iVibrateIndex = iObCount;
				}
				iObCount++;
				SI_ALLOC_ALL(&notifyObject);
				notifyObject.StructInfo.dwUsed = 0;
			} while(lpfn_Notify_FindNext(&notifyObject, hFindHandle) == E_NTFY_SUCCESS);
		}
		lpfn_Notify_FindClose(hFindHandle);
		return TRUE;
	}
}

BOOL CNotificationLoader::UnloadNotificationDLL()
{
	if (m_hNotificationDLL)
	{
		FreeLibrary(m_hNotificationDLL);
		m_hNotificationDLL		= NULL;
		lpfn_Notify_FindClose	= NULL;
		lpfn_Notify_FindNext	= NULL;
		lpfn_Notify_FindFirst	= NULL;
		lpfn_Notify_SetCycleInfo= NULL;
		lpfn_Notify_GetCycleInfo= NULL;
		lpfn_Notify_SetState	= NULL;
		lpfn_Notify_GetState	= NULL;
	}
	return TRUE;
}

BOOL CNotificationLoader::Beep(int iFrequency, int iVolume, int iDuration)
{
	if (m_iBeeperIndex < 0)
		return FALSE;

	CYCLE_INFO cycleInfo;
	SI_INIT(&cycleInfo);
	DWORD dwResult = lpfn_Notify_GetCycleInfo(m_iBeeperIndex, &cycleInfo);
	if(dwResult != E_NTFY_SUCCESS)
		return FALSE;
	cycleInfo.ObjectTypeSpecific.BeeperSpecific.dwFrequency = iFrequency;
	cycleInfo.ObjectTypeSpecific.BeeperSpecific.dwVolume = iVolume;
	cycleInfo.ObjectTypeSpecific.BeeperSpecific.dwDuration = iDuration;
	dwResult = lpfn_Notify_SetCycleInfo(m_iBeeperIndex, &cycleInfo);
	dwResult = lpfn_Notify_SetState(m_iBeeperIndex, NOTIFY_STATE_CYCLE);

	return TRUE;
}

BOOL CNotificationLoader::Vibrate(int iDuration)
{
	if (m_iVibrateIndex < 0)
		return FALSE;

	CYCLE_INFO cycleInfo;
	SI_INIT(&cycleInfo);
	DWORD dwResult = lpfn_Notify_GetCycleInfo(m_iVibrateIndex, &cycleInfo);
	if(dwResult != E_NTFY_SUCCESS)
		return FALSE;
	cycleInfo.ObjectTypeSpecific.VibratorSpecific.dwDuration = iDuration;
	dwResult = lpfn_Notify_SetCycleInfo(m_iVibrateIndex, &cycleInfo);
	dwResult = lpfn_Notify_SetState(m_iVibrateIndex, NOTIFY_STATE_CYCLE);
	return dwResult == E_NTFY_SUCCESS;
}
<commit_msg>Resolving EMBPD00156651 on the master branch<commit_after>#include "NotificationLoader.h"

CNotificationLoader::CNotificationLoader()
{
	m_hNotificationDLL			= NULL;
	lpfn_Notify_FindClose		= NULL;
	lpfn_Notify_FindFirst		= NULL;
	lpfn_Notify_FindNext		= NULL;
	lpfn_Notify_SetCycleInfo	= NULL;
	lpfn_Notify_GetCycleInfo	= NULL;
	lpfn_Notify_SetState		= NULL;
	lpfn_Notify_GetState		= NULL;
	m_iBeeperIndex			= -1;
	m_iVibrateIndex			= -1;
}

CNotificationLoader::~CNotificationLoader()
{
	UnloadNotificationDLL();
}

//  Loading Notification DLL dynamically
BOOL CNotificationLoader::LoadNotificationDLL()
{
	m_hNotificationDLL = LoadLibrary(NOTIFY_DLL);
	if (!m_hNotificationDLL)
	{
		return FALSE;
	}
	//  Map the function pointers to functions exported from the DLL
	lpfn_Notify_FindClose = (LPFN_NOTIFY_FINDCLOSE_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_FindClose");
	lpfn_Notify_FindNext = (LPFN_NOTIFY_FINDNEXT_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_FindNext");
	lpfn_Notify_FindFirst = (LPFN_NOTIFY_FINDFIRST_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_FindFirst");
	lpfn_Notify_SetCycleInfo = (LPFN_NOTIFY_SETCYCLEINFO_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_SetCycleInfo");
	lpfn_Notify_GetCycleInfo = (LPFN_NOTIFY_GETCYCLEINFO_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_GetCycleInfo");
	lpfn_Notify_SetState = (LPFN_NOTIFY_SETSTATE_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_SetState");
	lpfn_Notify_GetState = (LPFN_NOTIFY_GETSTATE_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_GetState");

	if (lpfn_Notify_FindClose	== NULL ||
		lpfn_Notify_FindNext	== NULL ||
		lpfn_Notify_FindFirst	== NULL ||
		lpfn_Notify_SetCycleInfo== NULL ||
		lpfn_Notify_GetCycleInfo== NULL ||
		lpfn_Notify_SetState	== NULL ||
		lpfn_Notify_GetState	== NULL)
	{
		m_hNotificationDLL = NULL;
		return FALSE;
	}
	else
	{
		//  Set the indices of the beeper and vibrate index
		NOTIFY_FINDINFO notifyObject;
		HANDLE	hFindHandle = NULL;
		SI_ALLOC_ALL(&notifyObject);
		notifyObject.StructInfo.dwUsed = 0;
		if(lpfn_Notify_FindFirst(&notifyObject, &hFindHandle) == E_NTFY_SUCCESS)
		{
			int iObCount = 0;
			do
			{
				if(notifyObject.dwObjectType == NOTIFY_TYPE_BEEPER)
				{
					//  Found the Beeper
					m_iBeeperIndex = iObCount;
					continue;
				}
				else if (notifyObject.dwObjectType == NOTIFY_TYPE_VIBRATOR)
				{
					m_iVibrateIndex = iObCount;
				}
				iObCount++;
				SI_ALLOC_ALL(&notifyObject);
				notifyObject.StructInfo.dwUsed = 0;
			} while(lpfn_Notify_FindNext(&notifyObject, hFindHandle) == E_NTFY_SUCCESS);
		}
		lpfn_Notify_FindClose(hFindHandle);
		return TRUE;
	}
}

BOOL CNotificationLoader::UnloadNotificationDLL()
{
	if (m_hNotificationDLL)
	{
		FreeLibrary(m_hNotificationDLL);
		m_hNotificationDLL		= NULL;
		lpfn_Notify_FindClose	= NULL;
		lpfn_Notify_FindNext	= NULL;
		lpfn_Notify_FindFirst	= NULL;
		lpfn_Notify_SetCycleInfo= NULL;
		lpfn_Notify_GetCycleInfo= NULL;
		lpfn_Notify_SetState	= NULL;
		lpfn_Notify_GetState	= NULL;
	}
	return TRUE;
}

BOOL CNotificationLoader::Beep(int iFrequency, int iVolume, int iDuration)
{
	if (m_iBeeperIndex < 0)
		return FALSE;

	CYCLE_INFO cycleInfo;
	SI_INIT(&cycleInfo);
	DWORD dwResult = lpfn_Notify_GetCycleInfo(m_iBeeperIndex, &cycleInfo);
	if(dwResult != E_NTFY_SUCCESS)
		return FALSE;
	cycleInfo.ObjectTypeSpecific.BeeperSpecific.dwFrequency = iFrequency;
	cycleInfo.ObjectTypeSpecific.BeeperSpecific.dwVolume = iVolume;
	cycleInfo.ObjectTypeSpecific.BeeperSpecific.dwDuration = iDuration;
	dwResult = lpfn_Notify_SetCycleInfo(m_iBeeperIndex, &cycleInfo);
	dwResult = lpfn_Notify_SetState(m_iBeeperIndex, NOTIFY_STATE_CYCLE);

	return TRUE;
}

BOOL CNotificationLoader::Vibrate(int iDuration)
{
	if (m_iVibrateIndex < 0)
		return FALSE;

	CYCLE_INFO cycleInfo;
	SI_INIT(&cycleInfo);
	DWORD dwResult = lpfn_Notify_GetCycleInfo(m_iVibrateIndex, &cycleInfo);
	if(dwResult != E_NTFY_SUCCESS)
		return FALSE;
	cycleInfo.ObjectTypeSpecific.VibratorSpecific.dwDuration = iDuration;
	dwResult = lpfn_Notify_SetCycleInfo(m_iVibrateIndex, &cycleInfo);
	dwResult = lpfn_Notify_SetState(m_iVibrateIndex, NOTIFY_STATE_CYCLE);
	return dwResult == E_NTFY_SUCCESS;
}
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

// UNSUPPORTED: libcpp-has-no-threads

// This test verifies behavior specified by [atomics.types.operations.req]/21:
//
//     When only one memory_order argument is supplied, the value of success is
//     order, and the value of failure is order except that a value of
//     memory_order_acq_rel shall be replaced by the value memory_order_acquire
//     and a value of memory_order_release shall be replaced by the value
//     memory_order_relaxed.
//
// Clang's atomic intrinsics do this for us, but GCC's do not. We don't actually
// have visibility to see what these memory orders are lowered to, but we can at
// least check that they are lowered at all (otherwise there is a compile
// failure with GCC).

#include <atomic>

#include "test_macros.h"

int main(int, char**) {
    std::atomic<int> i;
    volatile std::atomic<int> v;
    int exp = 0;

    i.compare_exchange_weak(exp, 0, std::memory_order_acq_rel);
    i.compare_exchange_weak(exp, 0, std::memory_order_release);
    i.compare_exchange_strong(exp, 0, std::memory_order_acq_rel);
    i.compare_exchange_strong(exp, 0, std::memory_order_release);

    v.compare_exchange_weak(exp, 0, std::memory_order_acq_rel);
    v.compare_exchange_weak(exp, 0, std::memory_order_release);
    v.compare_exchange_strong(exp, 0, std::memory_order_acq_rel);
    v.compare_exchange_strong(exp, 0, std::memory_order_release);

    return 0;
}
<commit_msg>[libcxx] [test] Add void cast to result of compare_exchange_weak to suppress [[nodiscard]].<commit_after>//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

// UNSUPPORTED: libcpp-has-no-threads

// This test verifies behavior specified by [atomics.types.operations.req]/21:
//
//     When only one memory_order argument is supplied, the value of success is
//     order, and the value of failure is order except that a value of
//     memory_order_acq_rel shall be replaced by the value memory_order_acquire
//     and a value of memory_order_release shall be replaced by the value
//     memory_order_relaxed.
//
// Clang's atomic intrinsics do this for us, but GCC's do not. We don't actually
// have visibility to see what these memory orders are lowered to, but we can at
// least check that they are lowered at all (otherwise there is a compile
// failure with GCC).

#include <atomic>

#include "test_macros.h"

int main(int, char**) {
    std::atomic<int> i;
    volatile std::atomic<int> v;
    int exp = 0;

    (void) i.compare_exchange_weak(exp, 0, std::memory_order_acq_rel);
    (void) i.compare_exchange_weak(exp, 0, std::memory_order_release);
    i.compare_exchange_strong(exp, 0, std::memory_order_acq_rel);
    i.compare_exchange_strong(exp, 0, std::memory_order_release);

    (void) v.compare_exchange_weak(exp, 0, std::memory_order_acq_rel);
    (void) v.compare_exchange_weak(exp, 0, std::memory_order_release);
    v.compare_exchange_strong(exp, 0, std::memory_order_acq_rel);
    v.compare_exchange_strong(exp, 0, std::memory_order_release);

    return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include "stdafx.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace BatchEncoderCoreUnitTests
{
    TEST_CLASS(TestDownloader_Tests)
    {
    public:
        TEST_METHOD(TestDownloader_Constructor)
        {
            #pragma warning(push)
            #pragma warning(disable:4101)
            TestDownloader m_Downloader;
            #pragma warning(pop)
        }

        TEST_METHOD(TestDownloader_Download)
        {
        }
    };

    TEST_CLASS(TestProcess_Tests)
    {
    public:
        TEST_METHOD(TestProcess_Constructor)
        {
            #pragma warning(push)
            #pragma warning(disable:4101)
            TestProcess m_Process;
            #pragma warning(pop)
        }

        TEST_METHOD(TestProcess_ConnectStdInput)
        {
        }

        TEST_METHOD(TestProcess_ConnectStdOutput)
        {
        }

        TEST_METHOD(TestProcess_ConnectStdError)
        {
        }

        TEST_METHOD(TestProcess_Start)
        {
        }

        TEST_METHOD(TestProcess_Wait)
        {
        }

        TEST_METHOD(TestProcess_Wait_timeout)
        {
        }

        TEST_METHOD(TestProcess_Terminate)
        {
        }

        TEST_METHOD(TestProcess_Close)
        {
        }

        TEST_METHOD(TestProcess_Stop)
        {
        }

        TEST_METHOD(TestProcess_StdinHandle)
        {
        }

        TEST_METHOD(TestProcess_StdoutHandle)
        {
        }

        TEST_METHOD(TestProcess_StderrHandle)
        {
        }
    };

    TEST_CLASS(TestPipe_Tests)
    {
    public:
        TEST_METHOD(TestPipe_Constructor)
        {
            #pragma warning(push)
            #pragma warning(disable:4101)
            TestPipe m_Pipe;
            #pragma warning(pop)
        }

        TEST_METHOD(TestPipe_Create)
        {
        }

        TEST_METHOD(TestPipe_CloseRead)
        {
        }

        TEST_METHOD(TestPipe_CloseWrite)
        {
        }

        TEST_METHOD(TestPipe_InheritRead)
        {
        }

        TEST_METHOD(TestPipe_InheritWrite)
        {
        }

        TEST_METHOD(TestPipe_DuplicateRead)
        {
        }

        TEST_METHOD(TestPipe_DuplicateWrite)
        {
        }

        TEST_METHOD(TestPipe_ReadHandle)
        {
        }

        TEST_METHOD(TestPipe_WriteHandle)
        {
        }
    };

    TEST_CLASS(TestPipeToFileWriter_Tests)
    {
    public:
        TEST_METHOD(TestPipeToFileWriter_Constructor)
        {
            #pragma warning(push)
            #pragma warning(disable:4101)
            TestPipeToFileWriter m_Writer;
            #pragma warning(pop)
        }

        TEST_METHOD(TestPipeToFileWriter_WriteLoop)
        {
        }
    };

    TEST_CLASS(TestFileToPipeReader_Tests)
    {
    public:
        TEST_METHOD(TestFileToPipeReader_Constructor)
        {
            #pragma warning(push)
            #pragma warning(disable:4101)
            TestFileToPipeReader m_Reader;
            #pragma warning(pop)
        }

        TEST_METHOD(TestFileToPipeReader_ReadLoop)
        {
        }
    };

    TEST_CLASS(TestOutputParser_Tests)
    {
    public:
        TEST_METHOD(TestOutputParser_Constructor)
        {
            #pragma warning(push)
            #pragma warning(disable:4101)
            TestOutputParser m_Parser;
            #pragma warning(pop)
        }

        TEST_METHOD(TestOutputParser_Open)
        {
        }

        TEST_METHOD(TestOutputParser_Parse)
        {
        }
    };

    TEST_CLASS(TestPipeToStringWriter_Tests)
    {
    public:
        TEST_METHOD(TestPipeToStringWriter_Constructor)
        {
            #pragma warning(push)
            #pragma warning(disable:4101)
            TestPipeToStringWriter m_Writer;
            #pragma warning(pop)
        }

        TEST_METHOD(TestPipeToStringWriter_WriteLoop)
        {
        }
    };

    TEST_CLASS(TestFileSystem_Tests)
    {
    public:
        TEST_METHOD(TestFileSystem_Constructor)
        {
            #pragma warning(push)
            #pragma warning(disable:4101)
            TestFileSystem m_FileSystem;
            #pragma warning(pop)
        }

        TEST_METHOD(TestFileSystem_GenerateUuidString)
        {
        }

        TEST_METHOD(TestFileSystem_CombinePath)
        {
        }

        TEST_METHOD(TestFileSystem_GetFileName)
        {
        }

        TEST_METHOD(TestFileSystem_GetFilePath)
        {
        }

        TEST_METHOD(TestFileSystem_GetFileExtension)
        {
        }

        TEST_METHOD(TestFileSystem_GetOnlyFileName)
        {
        }

        TEST_METHOD(TestFileSystem_GetFileSize64_handle)
        {
        }

        TEST_METHOD(TestFileSystem_GetFileSize64_filename)
        {
        }

        TEST_METHOD(TestFileSystem_GetFileSizeInt64)
        {
        }

        TEST_METHOD(TestFileSystem_GetExeFilePath)
        {
        }

        TEST_METHOD(TestFileSystem_GetSettingsFilePath)
        {
        }

        TEST_METHOD(TestFileSystem_GetFullPathName_)
        {
        }

        TEST_METHOD(TestFileSystem_FileExists)
        {
        }

        TEST_METHOD(TestFileSystem_PathFileExists_)
        {
        }

        TEST_METHOD(TestFileSystem_DeleteFile_)
        {
        }

        TEST_METHOD(TestFileSystem_CreateDirectory_)
        {
        }

        TEST_METHOD(TestFileSystem_GetCurrentDirectory_)
        {
        }

        TEST_METHOD(TestFileSystem_SetCurrentDirectory_)
        {
        }

        TEST_METHOD(TestFileSystem_DirectoryExists)
        {
        }

        TEST_METHOD(TestFileSystem_MakeFullPath)
        {
        }

        TEST_METHOD(TestFileSystem_FindFiles_pattern)
        {
        }

        TEST_METHOD(TestFileSystem_FindFiles_path)
        {
        }
    };

    TEST_CLASS(TestWorkerFactory_Tests)
    {
    public:
        TEST_METHOD(TestWorkerFactory_Constructor)
        {
            #pragma warning(push)
            #pragma warning(disable:4101)
            TestWorkerFactory m_Factory;
            #pragma warning(pop)
        }

        TEST_METHOD(TestWorkerFactory_CreateDownloaderPtr)
        {
        }

        TEST_METHOD(TestWorkerFactory_CreateProcessPtr)
        {
        }

        TEST_METHOD(TestWorkerFactory_CreatePipePtr)
        {
        }

        TEST_METHOD(TestWorkerFactory_CreateFileReaderPtr)
        {
        }

        TEST_METHOD(TestWorkerFactory_CreateFileWriterPtr)
        {
        }

        TEST_METHOD(TestWorkerFactory_CreateOutputParserPtr)
        {
        }

        TEST_METHOD(TestWorkerFactory_CreateStringWriterPtr)
        {
        }
    };

    TEST_CLASS(TestWorkerContext_Tests)
    {
    public:
        TEST_METHOD(TestWorkerContext_Constructor)
        {
            TestWorkerContext ctx;
            Assert::IsTrue(ctx.bDone);
            Assert::IsFalse(ctx.bRunning);
            Assert::IsNull(ctx.pConfig);
        }

        TEST_METHOD(TestWorkerContext_GetString)
        {
        }

        TEST_METHOD(TestWorkerContext_Start)
        {
        }

        TEST_METHOD(TestWorkerContext_Stop)
        {
        }

        TEST_METHOD(TestWorkerContext_ItemProgress)
        {
        }

        TEST_METHOD(TestWorkerContext_ItemStatus)
        {
        }

        TEST_METHOD(TestWorkerContext_TotalProgress)
        {
        }
    };
}
<commit_msg>Add init function unit test<commit_after>// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include "stdafx.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace BatchEncoderCoreUnitTests
{
    TEST_CLASS(TestDownloader_Tests)
    {
    public:
        TEST_METHOD(TestDownloader_Constructor)
        {
            #pragma warning(push)
            #pragma warning(disable:4101)
            TestDownloader m_Downloader;
            #pragma warning(pop)
        }

        TEST_METHOD(TestDownloader_Download)
        {
        }
    };

    TEST_CLASS(TestProcess_Tests)
    {
    public:
        TEST_METHOD(TestProcess_Constructor)
        {
            #pragma warning(push)
            #pragma warning(disable:4101)
            TestProcess m_Process;
            #pragma warning(pop)
        }

        TEST_METHOD(TestProcess_ConnectStdInput)
        {
        }

        TEST_METHOD(TestProcess_ConnectStdOutput)
        {
        }

        TEST_METHOD(TestProcess_ConnectStdError)
        {
        }

        TEST_METHOD(TestProcess_Start)
        {
        }

        TEST_METHOD(TestProcess_Wait)
        {
        }

        TEST_METHOD(TestProcess_Wait_timeout)
        {
        }

        TEST_METHOD(TestProcess_Terminate)
        {
        }

        TEST_METHOD(TestProcess_Close)
        {
        }

        TEST_METHOD(TestProcess_Stop)
        {
        }

        TEST_METHOD(TestProcess_StdinHandle)
        {
        }

        TEST_METHOD(TestProcess_StdoutHandle)
        {
        }

        TEST_METHOD(TestProcess_StderrHandle)
        {
        }
    };

    TEST_CLASS(TestPipe_Tests)
    {
    public:
        TEST_METHOD(TestPipe_Constructor)
        {
            #pragma warning(push)
            #pragma warning(disable:4101)
            TestPipe m_Pipe;
            #pragma warning(pop)
        }

        TEST_METHOD(TestPipe_Create)
        {
        }

        TEST_METHOD(TestPipe_CloseRead)
        {
        }

        TEST_METHOD(TestPipe_CloseWrite)
        {
        }

        TEST_METHOD(TestPipe_InheritRead)
        {
        }

        TEST_METHOD(TestPipe_InheritWrite)
        {
        }

        TEST_METHOD(TestPipe_DuplicateRead)
        {
        }

        TEST_METHOD(TestPipe_DuplicateWrite)
        {
        }

        TEST_METHOD(TestPipe_ReadHandle)
        {
        }

        TEST_METHOD(TestPipe_WriteHandle)
        {
        }
    };

    TEST_CLASS(TestPipeToFileWriter_Tests)
    {
    public:
        TEST_METHOD(TestPipeToFileWriter_Constructor)
        {
            #pragma warning(push)
            #pragma warning(disable:4101)
            TestPipeToFileWriter m_Writer;
            #pragma warning(pop)
        }

        TEST_METHOD(TestPipeToFileWriter_WriteLoop)
        {
        }
    };

    TEST_CLASS(TestFileToPipeReader_Tests)
    {
    public:
        TEST_METHOD(TestFileToPipeReader_Constructor)
        {
            #pragma warning(push)
            #pragma warning(disable:4101)
            TestFileToPipeReader m_Reader;
            #pragma warning(pop)
        }

        TEST_METHOD(TestFileToPipeReader_ReadLoop)
        {
        }
    };

    TEST_CLASS(TestOutputParser_Tests)
    {
    public:
        TEST_METHOD(TestOutputParser_Constructor)
        {
            #pragma warning(push)
            #pragma warning(disable:4101)
            TestOutputParser m_Parser;
            #pragma warning(pop)
        }

        TEST_METHOD(TestOutputParser_Open)
        {
        }

        TEST_METHOD(TestOutputParser_Parse)
        {
        }
    };

    TEST_CLASS(TestPipeToStringWriter_Tests)
    {
    public:
        TEST_METHOD(TestPipeToStringWriter_Constructor)
        {
            #pragma warning(push)
            #pragma warning(disable:4101)
            TestPipeToStringWriter m_Writer;
            #pragma warning(pop)
        }

        TEST_METHOD(TestPipeToStringWriter_WriteLoop)
        {
        }
    };

    TEST_CLASS(TestFileSystem_Tests)
    {
    public:
        TEST_METHOD(TestFileSystem_Constructor)
        {
            #pragma warning(push)
            #pragma warning(disable:4101)
            TestFileSystem m_FileSystem;
            #pragma warning(pop)
        }

        TEST_METHOD(TestFileSystem_GenerateUuidString)
        {
        }

        TEST_METHOD(TestFileSystem_CombinePath)
        {
        }

        TEST_METHOD(TestFileSystem_GetFileName)
        {
        }

        TEST_METHOD(TestFileSystem_GetFilePath)
        {
        }

        TEST_METHOD(TestFileSystem_GetFileExtension)
        {
        }

        TEST_METHOD(TestFileSystem_GetOnlyFileName)
        {
        }

        TEST_METHOD(TestFileSystem_GetFileSize64_handle)
        {
        }

        TEST_METHOD(TestFileSystem_GetFileSize64_filename)
        {
        }

        TEST_METHOD(TestFileSystem_GetFileSizeInt64)
        {
        }

        TEST_METHOD(TestFileSystem_GetExeFilePath)
        {
        }

        TEST_METHOD(TestFileSystem_GetSettingsFilePath)
        {
        }

        TEST_METHOD(TestFileSystem_GetFullPathName_)
        {
        }

        TEST_METHOD(TestFileSystem_FileExists)
        {
        }

        TEST_METHOD(TestFileSystem_PathFileExists_)
        {
        }

        TEST_METHOD(TestFileSystem_DeleteFile_)
        {
        }

        TEST_METHOD(TestFileSystem_CreateDirectory_)
        {
        }

        TEST_METHOD(TestFileSystem_GetCurrentDirectory_)
        {
        }

        TEST_METHOD(TestFileSystem_SetCurrentDirectory_)
        {
        }

        TEST_METHOD(TestFileSystem_DirectoryExists)
        {
        }

        TEST_METHOD(TestFileSystem_MakeFullPath)
        {
        }

        TEST_METHOD(TestFileSystem_FindFiles_pattern)
        {
        }

        TEST_METHOD(TestFileSystem_FindFiles_path)
        {
        }
    };

    TEST_CLASS(TestWorkerFactory_Tests)
    {
    public:
        TEST_METHOD(TestWorkerFactory_Constructor)
        {
            #pragma warning(push)
            #pragma warning(disable:4101)
            TestWorkerFactory m_Factory;
            #pragma warning(pop)
        }

        TEST_METHOD(TestWorkerFactory_CreateDownloaderPtr)
        {
        }

        TEST_METHOD(TestWorkerFactory_CreateProcessPtr)
        {
        }

        TEST_METHOD(TestWorkerFactory_CreatePipePtr)
        {
        }

        TEST_METHOD(TestWorkerFactory_CreateFileReaderPtr)
        {
        }

        TEST_METHOD(TestWorkerFactory_CreateFileWriterPtr)
        {
        }

        TEST_METHOD(TestWorkerFactory_CreateOutputParserPtr)
        {
        }

        TEST_METHOD(TestWorkerFactory_CreateStringWriterPtr)
        {
        }
    };

    TEST_CLASS(TestWorkerContext_Tests)
    {
    public:
        TEST_METHOD(TestWorkerContext_Constructor)
        {
            TestWorkerContext ctx;

            Assert::IsTrue(ctx.bDone);
            Assert::IsFalse(ctx.bRunning);
            Assert::IsNull(ctx.pConfig);
        }

        TEST_METHOD(TestWorkerContext_GetString)
        {
        }

        TEST_METHOD(TestWorkerContext_Init)
        {
            TestWorkerContext ctx;
            ctx.Init();

            Assert::IsTrue(ctx.bRunning);
            Assert::IsFalse(ctx.bDone);
            Assert::AreEqual(0, ctx.nTotalFiles);
            Assert::AreEqual(0, ctx.nProcessedFiles);
            Assert::AreEqual(0, ctx.nErrors);
            Assert::AreEqual(-1, ctx.nLastItemId);
        }

        TEST_METHOD(TestWorkerContext_Start)
        {
        }

        TEST_METHOD(TestWorkerContext_Stop)
        {
        }

        TEST_METHOD(TestWorkerContext_ItemProgress)
        {
        }

        TEST_METHOD(TestWorkerContext_ItemStatus)
        {
        }

        TEST_METHOD(TestWorkerContext_TotalProgress)
        {
        }
    };
}
<|endoftext|>


<commit_before>// Copyright (C) 2013 Jérôme Leclercq
// This file is part of the "Nazara Engine - 3D module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/3D/Loaders/OBJ.hpp>
#include <Nazara/3D/Loaders/OBJ/MTLParser.hpp>
#include <Nazara/3D/Loaders/OBJ/OBJParser.hpp>
#include <Nazara/3D/Model.hpp>
#include <Nazara/Renderer/Material.hpp>
#include <Nazara/Utility/BufferMapper.hpp>
#include <Nazara/Utility/IndexMapper.hpp>
#include <Nazara/Utility/Mesh.hpp>
#include <Nazara/Utility/StaticMesh.hpp>
#include <limits>
#include <memory>
#include <unordered_map>
#include <Nazara/3D/Debug.hpp>

namespace
{
	bool IsSupported(const NzString& extension)
	{
		return (extension == "obj");
	}

	bool Check(NzInputStream& stream, const NzModelParameters& parameters)
	{
		NazaraUnused(stream);
		NazaraUnused(parameters);

		return true; ///FIXME: Pas bon
	}

	bool Load(NzModel* model, NzInputStream& stream, const NzModelParameters& parameters)
	{
		NzOBJParser parser(stream);
		if (!parser.Parse())
		{
			NazaraError("OBJ parser failed");
			return false;
		}

		std::unique_ptr<NzMesh> mesh(new NzMesh);
		mesh->SetPersistent(false);
		if (!mesh->CreateStatic()) // Ne devrait jamais échouer
		{
			NazaraInternalError("Failed to create mesh");
			return false;
		}

		const NzString* materials = parser.GetMaterials();
		const NzVector4f* positions = parser.GetPositions();
		const NzVector3f* normals = parser.GetNormals();
		const NzVector3f* texCoords = parser.GetTexCoords();

		std::vector<unsigned int> faceIndices;

		const NzOBJParser::Mesh* meshes = parser.GetMeshes();
		unsigned int meshCount = parser.GetMeshCount();
		for (unsigned int i = 0; i < meshCount; ++i)
		{
			unsigned int faceCount = meshes[i].faces.size();

			std::vector<unsigned int> indices;
			indices.reserve(faceCount*3); // Pire cas (si les faces sont des triangles)

			// Bien plus rapide qu'un vector (pour la recherche)
			std::unordered_map<int, std::unordered_map<int, std::unordered_map<int, unsigned int>>> vertices;

			unsigned int vertexCount = 0;
			for (unsigned int j = 0; j < faceCount; ++j)
			{
				unsigned int faceVertexCount = meshes[i].faces[j].vertices.size();
				faceIndices.resize(faceVertexCount);

				for (unsigned int k = 0; k < faceVertexCount; ++k)
				{
					const NzOBJParser::FaceVertex& vertex = meshes[i].faces[j].vertices[k];

					auto& map = vertices[vertex.texCoord][vertex.normal];
					auto it = map.find(vertex.position);
					if (it == map.end())
					{
						faceIndices[k] = vertexCount;
						map[vertex.position] = vertexCount++;
					}
					else
						faceIndices[k] = it->second;
				}

				for (unsigned int k = 1; k < faceVertexCount-1; ++k)
				{
					indices.push_back(faceIndices[0]);
					indices.push_back(faceIndices[k]);
					indices.push_back(faceIndices[k+1]);
				}
			}

			std::unique_ptr<NzIndexBuffer> indexBuffer(new NzIndexBuffer(indices.size(), vertexCount > std::numeric_limits<nzUInt16>::max(), parameters.mesh.storage, nzBufferUsage_Static));
			indexBuffer->SetPersistent(false);

			std::unique_ptr<NzVertexBuffer> vertexBuffer(new NzVertexBuffer(NzMesh::GetDeclaration(), vertexCount, parameters.mesh.storage, nzBufferUsage_Static));
			vertexBuffer->SetPersistent(false);

			// Remplissage des indices
			NzIndexMapper indexMapper(indexBuffer.get(), nzBufferAccess_WriteOnly);
			for (unsigned int j = 0; j < indices.size(); ++j)
				indexMapper.Set(j, indices[j]);

			indexMapper.Unmap();

			// Remplissage des vertices
			bool hasNormals = true;
			bool hasTexCoords = true;
			NzBufferMapper<NzVertexBuffer> vertexMapper(vertexBuffer.get(), nzBufferAccess_WriteOnly);
			NzMeshVertex* meshVertices = static_cast<NzMeshVertex*>(vertexMapper.GetPointer());
			for (auto uvIt : vertices)
			{
				for (auto normalIt : uvIt.second)
				{
					for (auto positionIt : normalIt.second)
					{
						NzMeshVertex& vertex = meshVertices[positionIt.second];

						const NzVector4f& vec = positions[positionIt.first];
						vertex.position.Set(vec.x/vec.w, vec.y/vec.w, vec.z/vec.w);

						int index;

						index = normalIt.first; // Normale
						if (index >= 0)
							vertex.normal = normals[index];
						else
							hasNormals = false;

						index = uvIt.first; // Coordonnées de texture
						if (index >= 0)
						{
							const NzVector3f& uvw = texCoords[index];
							vertex.uv.Set(uvw.x, uvw.y);
						}
						else
							hasTexCoords = false;
					}
				}
			}

			vertexMapper.Unmap();

			std::unique_ptr<NzStaticMesh> subMesh(new NzStaticMesh(mesh.get()));
			if (!subMesh->Create(vertexBuffer.get()))
			{
				NazaraError("Failed to create StaticMesh");
				continue;
			}
			vertexBuffer.release();

			subMesh->SetIndexBuffer(indexBuffer.get());
			indexBuffer.release();

			subMesh->GenerateAABB();
			subMesh->SetMaterialIndex(meshes[i].material);
			subMesh->SetPrimitiveType(nzPrimitiveType_TriangleList);

			if (hasNormals && hasTexCoords)
				subMesh->GenerateTangents();
			else if (hasTexCoords)
				subMesh->GenerateNormalsAndTangents();
			else
				subMesh->GenerateNormals();

			if (mesh->AddSubMesh(meshes[i].name + '_' + materials[meshes[i].material], subMesh.get()))
				subMesh.release();
			else
				NazaraError("Failed to add SubMesh to Mesh");
		}

		mesh->SetMaterialCount(parser.GetMaterialCount());

		model->SetMesh(mesh.get());
		mesh.release();

		// On charge les matériaux si demandé
		NzString mtlLib = parser.GetMtlLib();
		if (parameters.loadMaterials && !mtlLib.IsEmpty())
		{
			NzFile file(stream.GetDirectory() + mtlLib);
			if (file.Open(NzFile::ReadOnly | NzFile::Text))
			{
				NzMTLParser materialParser(file);
				if (materialParser.Parse())
				{
					NzString baseDir = file.GetDirectory();
					for (unsigned int i = 0; i < meshCount; ++i)
					{
						const NzString& matName = materials[meshes[i].material];
						const NzMTLParser::Material* mtlMat = materialParser.GetMaterial(matName);
						if (mtlMat)
						{
							std::unique_ptr<NzMaterial> material(new NzMaterial);
							material->SetPersistent(false);

							NzColor ambientColor(mtlMat->ambient);
							ambientColor.a = mtlMat->alpha;

							NzColor diffuseColor(mtlMat->diffuse);
							diffuseColor.a = mtlMat->alpha;

							NzColor specularColor(mtlMat->specular);
							specularColor.a = mtlMat->alpha;

							material->SetAmbientColor(ambientColor);
							material->SetDiffuseColor(diffuseColor);
							material->SetSpecularColor(specularColor);
							material->SetShininess(mtlMat->shininess);

							if (parameters.material.loadDiffuseMap && !mtlMat->diffuseMap.IsEmpty())
							{
								std::unique_ptr<NzTexture> diffuseMap(new NzTexture);
								diffuseMap->SetPersistent(false);

								if (diffuseMap->LoadFromFile(baseDir + mtlMat->diffuseMap))
								{
									material->SetDiffuseMap(diffuseMap.get());
									diffuseMap.release();
								}
								else
									NazaraWarning("Failed to load diffuse map");
							}

							if (parameters.material.loadSpecularMap && !mtlMat->specularMap.IsEmpty())
							{
								std::unique_ptr<NzTexture> specularMap(new NzTexture);
								specularMap->SetPersistent(false);

								if (specularMap->LoadFromFile(baseDir + mtlMat->specularMap))
								{
									material->SetSpecularMap(specularMap.get());
									specularMap.release();
								}
								else
									NazaraWarning("Failed to load specular map");
							}

							model->SetMaterial(meshes[i].material, material.get());
							material.release();
						}
						else
							NazaraWarning("MTL has no material \"" + matName + '"');
					}
				}
				else
					NazaraWarning("MTL parser failed");
			}
			else
				NazaraWarning("Failed to open MTL file (" + file.GetPath() + ')');
		}

		return true;
	}
}

void NzLoaders_OBJ_Register()
{
	NzModelLoader::RegisterLoader(IsSupported, Check, Load);
}

void NzLoaders_OBJ_Unregister()
{
	NzModelLoader::UnregisterLoader(IsSupported, Check, Load);
}
<commit_msg>Improved Warnings<commit_after>// Copyright (C) 2013 Jérôme Leclercq
// This file is part of the "Nazara Engine - 3D module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/3D/Loaders/OBJ.hpp>
#include <Nazara/3D/Loaders/OBJ/MTLParser.hpp>
#include <Nazara/3D/Loaders/OBJ/OBJParser.hpp>
#include <Nazara/3D/Model.hpp>
#include <Nazara/Renderer/Material.hpp>
#include <Nazara/Utility/BufferMapper.hpp>
#include <Nazara/Utility/IndexMapper.hpp>
#include <Nazara/Utility/Mesh.hpp>
#include <Nazara/Utility/StaticMesh.hpp>
#include <limits>
#include <memory>
#include <unordered_map>
#include <Nazara/3D/Debug.hpp>

namespace
{
	bool IsSupported(const NzString& extension)
	{
		return (extension == "obj");
	}

	bool Check(NzInputStream& stream, const NzModelParameters& parameters)
	{
		NazaraUnused(stream);
		NazaraUnused(parameters);

		return true; ///FIXME: Pas bon
	}

	bool Load(NzModel* model, NzInputStream& stream, const NzModelParameters& parameters)
	{
		NzOBJParser parser(stream);
		if (!parser.Parse())
		{
			NazaraError("OBJ parser failed");
			return false;
		}

		std::unique_ptr<NzMesh> mesh(new NzMesh);
		mesh->SetPersistent(false);
		if (!mesh->CreateStatic()) // Ne devrait jamais échouer
		{
			NazaraInternalError("Failed to create mesh");
			return false;
		}

		const NzString* materials = parser.GetMaterials();
		const NzVector4f* positions = parser.GetPositions();
		const NzVector3f* normals = parser.GetNormals();
		const NzVector3f* texCoords = parser.GetTexCoords();

		std::vector<unsigned int> faceIndices;

		const NzOBJParser::Mesh* meshes = parser.GetMeshes();
		unsigned int meshCount = parser.GetMeshCount();
		for (unsigned int i = 0; i < meshCount; ++i)
		{
			unsigned int faceCount = meshes[i].faces.size();

			std::vector<unsigned int> indices;
			indices.reserve(faceCount*3); // Pire cas (si les faces sont des triangles)

			// Bien plus rapide qu'un vector (pour la recherche)
			std::unordered_map<int, std::unordered_map<int, std::unordered_map<int, unsigned int>>> vertices;

			unsigned int vertexCount = 0;
			for (unsigned int j = 0; j < faceCount; ++j)
			{
				unsigned int faceVertexCount = meshes[i].faces[j].vertices.size();
				faceIndices.resize(faceVertexCount);

				for (unsigned int k = 0; k < faceVertexCount; ++k)
				{
					const NzOBJParser::FaceVertex& vertex = meshes[i].faces[j].vertices[k];

					auto& map = vertices[vertex.texCoord][vertex.normal];
					auto it = map.find(vertex.position);
					if (it == map.end())
					{
						faceIndices[k] = vertexCount;
						map[vertex.position] = vertexCount++;
					}
					else
						faceIndices[k] = it->second;
				}

				for (unsigned int k = 1; k < faceVertexCount-1; ++k)
				{
					indices.push_back(faceIndices[0]);
					indices.push_back(faceIndices[k]);
					indices.push_back(faceIndices[k+1]);
				}
			}

			std::unique_ptr<NzIndexBuffer> indexBuffer(new NzIndexBuffer(indices.size(), vertexCount > std::numeric_limits<nzUInt16>::max(), parameters.mesh.storage, nzBufferUsage_Static));
			indexBuffer->SetPersistent(false);

			std::unique_ptr<NzVertexBuffer> vertexBuffer(new NzVertexBuffer(NzMesh::GetDeclaration(), vertexCount, parameters.mesh.storage, nzBufferUsage_Static));
			vertexBuffer->SetPersistent(false);

			// Remplissage des indices
			NzIndexMapper indexMapper(indexBuffer.get(), nzBufferAccess_WriteOnly);
			for (unsigned int j = 0; j < indices.size(); ++j)
				indexMapper.Set(j, indices[j]);

			indexMapper.Unmap();

			// Remplissage des vertices
			bool hasNormals = true;
			bool hasTexCoords = true;
			NzBufferMapper<NzVertexBuffer> vertexMapper(vertexBuffer.get(), nzBufferAccess_WriteOnly);
			NzMeshVertex* meshVertices = static_cast<NzMeshVertex*>(vertexMapper.GetPointer());
			for (auto uvIt : vertices)
			{
				for (auto normalIt : uvIt.second)
				{
					for (auto positionIt : normalIt.second)
					{
						NzMeshVertex& vertex = meshVertices[positionIt.second];

						const NzVector4f& vec = positions[positionIt.first];
						vertex.position.Set(vec.x/vec.w, vec.y/vec.w, vec.z/vec.w);

						int index;

						index = normalIt.first; // Normale
						if (index >= 0)
							vertex.normal = normals[index];
						else
							hasNormals = false;

						index = uvIt.first; // Coordonnées de texture
						if (index >= 0)
						{
							const NzVector3f& uvw = texCoords[index];
							vertex.uv.Set(uvw.x, uvw.y);
						}
						else
							hasTexCoords = false;
					}
				}
			}

			vertexMapper.Unmap();

			std::unique_ptr<NzStaticMesh> subMesh(new NzStaticMesh(mesh.get()));
			if (!subMesh->Create(vertexBuffer.get()))
			{
				NazaraError("Failed to create StaticMesh");
				continue;
			}
			vertexBuffer.release();

			subMesh->SetIndexBuffer(indexBuffer.get());
			indexBuffer.release();

			subMesh->GenerateAABB();
			subMesh->SetMaterialIndex(meshes[i].material);
			subMesh->SetPrimitiveType(nzPrimitiveType_TriangleList);

			if (hasNormals && hasTexCoords)
				subMesh->GenerateTangents();
			else if (hasTexCoords)
				subMesh->GenerateNormalsAndTangents();
			else
				subMesh->GenerateNormals();

			if (mesh->AddSubMesh(meshes[i].name + '_' + materials[meshes[i].material], subMesh.get()))
				subMesh.release();
			else
				NazaraError("Failed to add SubMesh to Mesh");
		}

		mesh->SetMaterialCount(parser.GetMaterialCount());

		model->SetMesh(mesh.get());
		mesh.release();

		// On charge les matériaux si demandé
		NzString mtlLib = parser.GetMtlLib();
		if (parameters.loadMaterials && !mtlLib.IsEmpty())
		{
			NzFile file(stream.GetDirectory() + mtlLib);
			if (file.Open(NzFile::ReadOnly | NzFile::Text))
			{
				NzMTLParser materialParser(file);
				if (materialParser.Parse())
				{
					NzString baseDir = file.GetDirectory();
					for (unsigned int i = 0; i < meshCount; ++i)
					{
						const NzString& matName = materials[meshes[i].material];
						const NzMTLParser::Material* mtlMat = materialParser.GetMaterial(matName);
						if (mtlMat)
						{
							std::unique_ptr<NzMaterial> material(new NzMaterial);
							material->SetPersistent(false);

							NzColor ambientColor(mtlMat->ambient);
							ambientColor.a = mtlMat->alpha;

							NzColor diffuseColor(mtlMat->diffuse);
							diffuseColor.a = mtlMat->alpha;

							NzColor specularColor(mtlMat->specular);
							specularColor.a = mtlMat->alpha;

							material->SetAmbientColor(ambientColor);
							material->SetDiffuseColor(diffuseColor);
							material->SetSpecularColor(specularColor);
							material->SetShininess(mtlMat->shininess);

							if (parameters.material.loadDiffuseMap && !mtlMat->diffuseMap.IsEmpty())
							{
								std::unique_ptr<NzTexture> diffuseMap(new NzTexture);
								diffuseMap->SetPersistent(false);

								if (diffuseMap->LoadFromFile(baseDir + mtlMat->diffuseMap))
								{
									material->SetDiffuseMap(diffuseMap.get());
									diffuseMap.release();
								}
								else
									NazaraWarning("Failed to load diffuse map (" + mtlMat->diffuseMap + ')');
							}

							if (parameters.material.loadSpecularMap && !mtlMat->specularMap.IsEmpty())
							{
								std::unique_ptr<NzTexture> specularMap(new NzTexture);
								specularMap->SetPersistent(false);

								if (specularMap->LoadFromFile(baseDir + mtlMat->specularMap))
								{
									material->SetSpecularMap(specularMap.get());
									specularMap.release();
								}
								else
									NazaraWarning("Failed to load specular map (" + mtlMat->diffuseMap + ')');
							}

							model->SetMaterial(meshes[i].material, material.get());
							material.release();
						}
						else
							NazaraWarning("MTL has no material \"" + matName + '"');
					}
				}
				else
					NazaraWarning("MTL parser failed");
			}
			else
				NazaraWarning("Failed to open MTL file (" + file.GetPath() + ')');
		}

		return true;
	}
}

void NzLoaders_OBJ_Register()
{
	NzModelLoader::RegisterLoader(IsSupported, Check, Load);
}

void NzLoaders_OBJ_Unregister()
{
	NzModelLoader::UnregisterLoader(IsSupported, Check, Load);
}
<|endoftext|>


<commit_before>#include "notendaui.h"
#include <iostream>

using namespace std;

NotendaUI::NotendaUI()
{

}

bool check = true;

void NotendaUI::keyra()
{
<<<<<<< HEAD
=======
    //TEMP
    vector<tolvufolk> data;
    data.push_back(tolvufolk("Ada Lovelace", "kvk", 1880, 1890));
    data.push_back(tolvufolk("Charles Babbage", "kk", 1900, 1920));

    cout << "*==============================================================*" << endl;
    cout << "*||Please enter one the following commands*                  ||*" << endl;
    cout << "*==============================================================*" << endl;
    cout << "*||list - Shows a list of all known entries in the database. ||*" << endl;
    cout << "*||add - Add a new entry into the database.                  ||*" << endl;
    cout << "*||delete - Removes an entry from the database.              ||*" << endl;
    cout << "*||update - Updates an entry from the database.              ||*" << endl;
    cout << "*||purge - Removes every entry from the database.            ||*" << endl;
    cout << "*==============================================================*" << endl;
>>>>>>> 5eba62eefebf3fb799f5906f5776e719dc50e634

    do
        {
        cout << "*==============================================================*" << endl;
        cout << "*||Please enter one the following commands*                  ||*" << endl;
        cout << "*==============================================================*" << endl;
        cout << "*||list - Shows a list of all known entries in the database. ||*" << endl;
        cout << "*||add - Add a new entry into the database.                  ||*" << endl;
        cout << "*||delete - Removes an entry from the database.              ||*" << endl;
        cout << "*||update - Updates an entry from the database.              ||*" << endl;
        cout << "*||purge - Removes every entry from the database.            ||*" << endl;
        cout << "*==============================================================*" << endl;

        string skipun;
        cin >> skipun;
        system("cls");

        if (skipun == "list" || skipun == "l")
        {

        }

        else if (skipun == "add" || skipun == "a")
        {

        }

        else if (skipun == "delete" || skipun == "d")
        {

        }

        else if (skipun == "update" || skipun == "u")
        {

        }

        else if (skipun == "purge" || skipun == "p")
        {

        }

        else
        {
            cerr << "Input not valid, try again." << endl;
            cin >> skipun;
            check = false;
        }
    } while (check == false);
}
<commit_msg>Bætti við errorcatcher í UI<commit_after>#include "notendaui.h"
#include <iostream>

using namespace std;

NotendaUI::NotendaUI()
{

}

void Skrifaut()
{
    cout << "*==============================================================*" << endl;
    cout << "*||Please enter one the following commands*                  ||*" << endl;
    cout << "*==============================================================*" << endl;
    cout << "*||list - Shows a list of all known entries in the database. ||*" << endl;
    cout << "*||add - Add a new entry into the database.                  ||*" << endl;
    cout << "*||delete - Removes an entry from the database.              ||*" << endl;
    cout << "*||update - Updates an entry from the database.              ||*" << endl;
    cout << "*||purge - Removes every entry from the database.            ||*" << endl;
    cout << "*==============================================================*" << endl;
}

bool check = true;

void NotendaUI::keyra()
{
    //TEMP
    vector<tolvufolk> data;
    data.push_back(tolvufolk("Ada Lovelace", "kvk", 1880, 1890));
    data.push_back(tolvufolk("Charles Babbage", "kk", 1900, 1920));

    Skrifaut();

    do
        {
        string skipun;
        cin >> skipun;
        system("cls");

        if (skipun == "list" || skipun == "l")
        {

        }

        else if (skipun == "add" || skipun == "a")
        {

        }

        else if (skipun == "delete" || skipun == "d")
        {

        }

        else if (skipun == "update" || skipun == "u")
        {

        }

        else if (skipun == "purge" || skipun == "p")
        {

        }

        else
        {
            system("cls");
            Skrifaut();
            cerr << "Input not valid, try again: ";
            check = false;
        }
    } while (check == false);
}
<|endoftext|>


<commit_before>/*===========================================================================*\
 *                                                                           *
 *                               OpenMesh                                    *
 *      Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen      *
 *                           www.openmesh.org                                *
 *                                                                           *
 *---------------------------------------------------------------------------*
 *  This file is part of OpenMesh.                                           *
 *                                                                           *
 *  OpenMesh is free software: you can redistribute it and/or modify         *
 *  it under the terms of the GNU Lesser General Public License as           *
 *  published by the Free Software Foundation, either version 3 of           *
 *  the License, or (at your option) any later version with the              *
 *  following exceptions:                                                    *
 *                                                                           *
 *  If other files instantiate templates or use macros                       *
 *  or inline functions from this file, or you compile this file and         *
 *  link it with other files to produce an executable, this file does        *
 *  not by itself cause the resulting executable to be covered by the        *
 *  GNU Lesser General Public License. This exception does not however       *
 *  invalidate any other reasons why the executable file might be            *
 *  covered by the GNU Lesser General Public License.                        *
 *                                                                           *
 *  OpenMesh 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 LesserGeneral Public          *
 *  License along with OpenMesh.  If not,                                    *
 *  see <http://www.gnu.org/licenses/>.                                      *
 *                                                                           *
\*===========================================================================*/

/*===========================================================================*\
 *                                                                           *
 *   $Revision$                                                         *
 *   $Date$                   *
 *                                                                           *
\*===========================================================================*/

//=============================================================================
//
//  Helper Functions for binary reading / writing
//
//=============================================================================

//== INCLUDES =================================================================

#include <OpenMesh/Core/System/config.h>
// -------------------- STL
#include <algorithm>
// -------------------- OpenMesh
#include <OpenMesh/Core/IO/BinaryHelper.hh>

//== NAMESPACES ===============================================================

namespace OpenMesh {
namespace IO {

#ifndef DOXY_IGNORE_THIS

//== IMPLEMENTATION ===========================================================

union u1 { short int s;  unsigned char c[2]; }  sc;
union u2 { int i;        unsigned char c[4]; }  ic;
union u3 { float f;      unsigned char c[4]; }  fc;
union u4 { double d;     unsigned char c[8]; }  dc;

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

short int read_short(FILE* _in, bool _swap)
{
  fread((char*)sc.c, 1, 2, _in);
  if (_swap) std::swap(sc.c[0], sc.c[1]);
  return sc.s;
}

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

int read_int(FILE* _in, bool _swap)
{
  fread((char*)ic.c, 1, 4, _in);
  if (_swap) {
    std::swap(ic.c[0], ic.c[3]);
    std::swap(ic.c[1], ic.c[2]);
  }
  return ic.i;
}

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

float read_float(FILE* _in, bool _swap)
{
  fread((char*)fc.c, 1, 4, _in);
  if (_swap) {
    std::swap(fc.c[0], fc.c[3]);
    std::swap(fc.c[1], fc.c[2]);
  }
  return fc.f;
}

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

double read_double(FILE* _in, bool _swap)
{
  fread((char*)dc.c, 1, 8, _in);
  if (_swap) {
    std::swap(dc.c[0], dc.c[7]);
    std::swap(dc.c[1], dc.c[6]);
    std::swap(dc.c[2], dc.c[5]);
    std::swap(dc.c[3], dc.c[4]);
  }
  return dc.d;
}

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

void write_short(short int _i, FILE* _out, bool _swap)
{
  sc.s = _i;
  if (_swap) std::swap(sc.c[0], sc.c[1]);
  fwrite((char*)sc.c, 1, 2, _out);
}

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

void write_int(int _i, FILE* _out, bool _swap)
{
  ic.i = _i;
  if (_swap) {
    std::swap(ic.c[0], ic.c[3]);
    std::swap(ic.c[1], ic.c[2]);
  }
  fwrite((char*)ic.c, 1, 4, _out);
}

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

void write_float(float _f, FILE* _out, bool _swap)
{
  fc.f = _f;
  if (_swap) {
    std::swap(fc.c[0], fc.c[3]);
    std::swap(fc.c[1], fc.c[2]);
  }
  fwrite((char*)fc.c, 1, 4, _out);
}

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

void write_double(double _d, FILE* _out, bool _swap)
{
  dc.d = _d;
  if (_swap) {
    std::swap(dc.c[0], dc.c[7]);
    std::swap(dc.c[1], dc.c[6]);
    std::swap(dc.c[2], dc.c[5]);
    std::swap(dc.c[3], dc.c[4]);
  }
  fwrite((char*)dc.c, 1, 8, _out);
}

#endif

//=============================================================================
} // namespace IO
} // namespace OpenMesh
//=============================================================================
<commit_msg>Making Binary IO readers multi-thread safe. (Thanks to Dominic Genest for the patch)<commit_after>/*===========================================================================*\
 *                                                                           *
 *                               OpenMesh                                    *
 *      Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen      *
 *                           www.openmesh.org                                *
 *                                                                           *
 *---------------------------------------------------------------------------*
 *  This file is part of OpenMesh.                                           *
 *                                                                           *
 *  OpenMesh is free software: you can redistribute it and/or modify         *
 *  it under the terms of the GNU Lesser General Public License as           *
 *  published by the Free Software Foundation, either version 3 of           *
 *  the License, or (at your option) any later version with the              *
 *  following exceptions:                                                    *
 *                                                                           *
 *  If other files instantiate templates or use macros                       *
 *  or inline functions from this file, or you compile this file and         *
 *  link it with other files to produce an executable, this file does        *
 *  not by itself cause the resulting executable to be covered by the        *
 *  GNU Lesser General Public License. This exception does not however       *
 *  invalidate any other reasons why the executable file might be            *
 *  covered by the GNU Lesser General Public License.                        *
 *                                                                           *
 *  OpenMesh 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 LesserGeneral Public          *
 *  License along with OpenMesh.  If not,                                    *
 *  see <http://www.gnu.org/licenses/>.                                      *
 *                                                                           *
\*===========================================================================*/

/*===========================================================================*\
 *                                                                           *
 *   $Revision$                                                         *
 *   $Date$                   *
 *                                                                           *
\*===========================================================================*/

//=============================================================================
//
//  Helper Functions for binary reading / writing
//
//=============================================================================

//== INCLUDES =================================================================

#include <OpenMesh/Core/System/config.h>
// -------------------- STL
#include <algorithm>
// -------------------- OpenMesh
#include <OpenMesh/Core/IO/BinaryHelper.hh>

//== NAMESPACES ===============================================================

namespace OpenMesh {
namespace IO {

#ifndef DOXY_IGNORE_THIS

//== IMPLEMENTATION ===========================================================

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

short int read_short(FILE* _in, bool _swap)
{
  union u1 { short int s; unsigned char c[2]; }  sc;
  fread((char*)sc.c, 1, 2, _in);
  if (_swap) std::swap(sc.c[0], sc.c[1]);
  return sc.s;
}

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

int read_int(FILE* _in, bool _swap)
{
  union u2 { int i; unsigned char c[4]; } ic;
  fread((char*)ic.c, 1, 4, _in);
  if (_swap) {
    std::swap(ic.c[0], ic.c[3]);
    std::swap(ic.c[1], ic.c[2]);
  }
  return ic.i;
}

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

float read_float(FILE* _in, bool _swap)
{
  union u3 { float f; unsigned char c[4]; } fc;
  fread((char*)fc.c, 1, 4, _in);
  if (_swap) {
    std::swap(fc.c[0], fc.c[3]);
    std::swap(fc.c[1], fc.c[2]);
  }
  return fc.f;
}

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

double read_double(FILE* _in, bool _swap)
{
  union u4 { double d; unsigned char c[8]; } dc;
  fread((char*)dc.c, 1, 8, _in);
  if (_swap) {
    std::swap(dc.c[0], dc.c[7]);
    std::swap(dc.c[1], dc.c[6]);
    std::swap(dc.c[2], dc.c[5]);
    std::swap(dc.c[3], dc.c[4]);
  }
  return dc.d;
}

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

void write_short(short int _i, FILE* _out, bool _swap)
{
  union u1 { short int s; unsigned char c[2]; } sc;
  sc.s = _i;
  if (_swap) std::swap(sc.c[0], sc.c[1]);
  fwrite((char*)sc.c, 1, 2, _out);
}

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

void write_int(int _i, FILE* _out, bool _swap)
{
  union u2 { int i; unsigned char c[4]; } ic;
  ic.i = _i;
  if (_swap) {
    std::swap(ic.c[0], ic.c[3]);
    std::swap(ic.c[1], ic.c[2]);
  }
  fwrite((char*)ic.c, 1, 4, _out);
}

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

void write_float(float _f, FILE* _out, bool _swap)
{
  union u3 { float f; unsigned char c[4]; } fc;
  fc.f = _f;
  if (_swap) {
    std::swap(fc.c[0], fc.c[3]);
    std::swap(fc.c[1], fc.c[2]);
  }
  fwrite((char*)fc.c, 1, 4, _out);
}

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

void write_double(double _d, FILE* _out, bool _swap)
{
  union u4 { double d; unsigned char c[8]; } dc;
  dc.d = _d;
  if (_swap) {
    std::swap(dc.c[0], dc.c[7]);
    std::swap(dc.c[1], dc.c[6]);
    std::swap(dc.c[2], dc.c[5]);
    std::swap(dc.c[3], dc.c[4]);
  }
  fwrite((char*)dc.c, 1, 8, _out);
}

#endif

//=============================================================================
} // namespace IO
} // namespace OpenMesh
//=============================================================================
<|endoftext|>