Click here to Skip to main content
15,895,781 members
Articles / Multimedia / DirectX

Rendering Text with Direct2D & DirectWrite

Rate me:
Please Sign up or sign in to vote.
4.94/5 (39 votes)
3 Jan 2015CPOL8 min read 106.6K   2.8K   76  
Direct2D, DirectWrite, Windows API, C++, std::shared_ptr and more
#include "stdafx.h"
#include "hwinio.h"
#include "hwinexception.h"
#include "hwincomobject.h"

namespace harlinn
{
    namespace windows
    {
        namespace
        {
            wchar_t TrimEndChars [] = { 0x9, 0xA, 0xB, 0xC, 0xD, 0x20, 0x85, 0xA0 };

            wchar_t RealInvalidPathChars [] = { '\"', '<', '>', '|', '\0', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 };

            wchar_t InvalidFileNameChars [] = { '\"', '<', '>', '|', '\0', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, ':', '*', '?', '\\', '/' };


            inline void CheckInvalidPathChars( const WideString& path )
            {
                if ( path.IndexOf( []( wchar_t c ) -> bool
                {
                    return ( c == '\"' || c == '<' || c == '>' || c == '|' || c < 32 );
                } ) != WideString::npos )
                {
                    throw ArgumentException( "Invalid path character" );
                }
            }
        }


        // ----------------------------------------------------------------------
        // StreamBase
        // ----------------------------------------------------------------------

        HWIN_EXPORT StreamBase::~StreamBase( )
        {

        }

        HWIN_EXPORT  long long StreamBase::Position( ) const
        {
            return const_cast<StreamBase*>( this )->Seek( 0, SeekOrigin::CurrentPosition );
        }

        HWIN_EXPORT  StreamBase& StreamBase::SetPosition( long long thePosition )
        {
            this->Seek( thePosition, SeekOrigin::StartOfFile );
            return *this;
        }

        HWIN_EXPORT  long long StreamBase::Size( ) const
        {
            long long currentPosition = this->Position( );
            long long result = const_cast<StreamBase*>( this )->Seek( 0, SeekOrigin::EndOfFile );
            const_cast<StreamBase*>( this )->Seek( currentPosition, SeekOrigin::StartOfFile );
            return result;
        }

        HWIN_EXPORT  StreamBase& StreamBase::SetSize( long long theSize )
        {
            // this is intentionally a nop
            return *this;
        }

        HWIN_EXPORT  StreamBase& StreamBase::Flush( )
        {
            // this is intentionally a nop
            return *this;
        }

        // -----------------------------------------------------------------
        // MemoryStream
        // -----------------------------------------------------------------

        HWIN_EXPORT MemoryStream::Data::Data( )
            : referenceCount_( 1 ), ownsData_( true ), capacity_( 8192 ), size_( 0 ), data_( ( byte* )malloc( 8192 ) )
        {

        }
        HWIN_EXPORT MemoryStream::Data::Data( byte* buffer, size_t bufferSize )
            : referenceCount_( 1 ), ownsData_( false ), capacity_( bufferSize ), size_( bufferSize ), data_( buffer )
        {

        }
        HWIN_EXPORT MemoryStream::Data::~Data( )
        {
            if ( ownsData_ && data_ )
            {
                free( data_ );
            }
        }


        HWIN_EXPORT long long MemoryStream::Data::Capacity( ) const
        {
            return static_cast<long long>( capacity_ );
        }
        HWIN_EXPORT void MemoryStream::Data::SetCapacity( long long theSize )
        {
            size_t newCapacity = static_cast<size_t>( theSize );
            if ( ( newCapacity == capacity_ ) || ( newCapacity < size_ ) )
            {
                return;
            }
            if ( !ownsData_ )
            {
                throw InvalidOperationException( "Buffer is read only" );
            }
            byte* ptr = ( byte* )realloc( data_, newCapacity );
            if ( ptr == nullptr )
            {
                throw OutOfMemoryException( );
            }
            data_ = ptr;
            capacity_ = newCapacity;
        }
        HWIN_EXPORT long long MemoryStream::Data::Size( ) const
        {
            return static_cast<long long>( size_ );
        }
        HWIN_EXPORT void MemoryStream::Data::SetSize( long long theSize )
        {
            size_t newSize = static_cast<size_t>( theSize );
            if ( newSize == size_ )
            {
                return;
            }
            if ( newSize > capacity_ )
            {
                size_t newCapacity = allocationByteCount( newSize );
                SetCapacity( static_cast<long long>( newCapacity ) );
            }
            size_ = newSize;
        }
        HWIN_EXPORT long long MemoryStream::Data::Read( long long& thePosition, void* buffer, size_t numberOfBytesToRead )
        {
            size_t currentPosition = static_cast<size_t>( thePosition );
            if ( currentPosition < size_ )
            {
                if ( currentPosition + numberOfBytesToRead > size_ )
                {
                    numberOfBytesToRead = size_ - currentPosition;
                }
                memcpy( buffer, &data_[currentPosition], numberOfBytesToRead );
                long long result = static_cast<long long>( numberOfBytesToRead );
                thePosition += result;
                return result;
            }
            return 0;
        }
        HWIN_EXPORT long long MemoryStream::Data::Write( long long& thePosition, const void* buffer, size_t numberOfBytesToWrite )
        {
            if ( numberOfBytesToWrite == 0 )
            {
                return 0;
            }
            if ( !ownsData_ )
            {
                throw InvalidOperationException( "Buffer is read only" );
            }
            size_t currentPosition = static_cast<size_t>( thePosition );
            size_t sizeRequired = currentPosition + numberOfBytesToWrite;
            if ( sizeRequired > size_ )
            {
                SetSize( static_cast<long long>( sizeRequired ) );
            }
            memcpy( &data_[currentPosition], buffer, numberOfBytesToWrite );
            long long result = static_cast<long long>( numberOfBytesToWrite );
            thePosition += result;
            return result;
        }
        HWIN_EXPORT long long MemoryStream::Data::Seek( long long& thePosition, long long offset, SeekOrigin seekOrigin )
        {
            long long newPosition = 0;
            size_t currentPosition = static_cast<size_t>( thePosition );
            switch ( seekOrigin )
            {
                case SeekOrigin::StartOfFile:
                if ( offset > 0 )
                {
                    newPosition = offset;
                }
                break;
                case SeekOrigin::CurrentPosition:
                newPosition = thePosition + offset;
                break;
                case SeekOrigin::EndOfFile:
                newPosition = size_ + offset;
                break;
            }
            if ( newPosition < 0 )
            {
                newPosition = 0;
            }
            thePosition = newPosition;
            return newPosition;
        }


        HWIN_EXPORT MemoryStream::MemoryStream( )
            : data_( nullptr ), position_( 0 )
        {
        }

        HWIN_EXPORT MemoryStream::MemoryStream( const MemoryStream& other )
            : data_( other.data_ ), position_( other.position_ )
        {
            if ( data_ )
            {
                data_->AddReference( );
            }
        }

        HWIN_EXPORT MemoryStream::MemoryStream( byte* buffer, size_t bufferSize )
            : data_( nullptr ), position_( 0 )
        {
            data_ = new Data( buffer, bufferSize );
        }

        HWIN_EXPORT MemoryStream::~MemoryStream( )
        {
            if ( data_ )
            {
                data_->Release( );
            }
        }


        HWIN_EXPORT MemoryStream& MemoryStream::operator = ( const MemoryStream& other )
        {
            if ( data_ != other.data_ )
            {
                if ( data_ )
                {
                    data_->Release( );
                }
                data_ = other.data_;
                if ( data_ )
                {
                    data_->AddReference( );
                }
            }
            return *this;
        }

        HWIN_EXPORT bool MemoryStream::CanRead( ) const
        {
            return true;
        }
        HWIN_EXPORT bool MemoryStream::CanSeek( ) const
        {
            return true;
        }
        HWIN_EXPORT bool MemoryStream::CanTimeout( ) const
        {
            return false;
        }
        HWIN_EXPORT bool MemoryStream::CanWrite( ) const
        {
            if ( data_ )
            {
                return data_->OwnsData( );
            }
            return true;
        }

        HWIN_EXPORT const byte* MemoryStream::Buffer( ) const
        {
            if ( data_ )
            {
                return data_->Buffer( );
            }
            return nullptr;
        }

        HWIN_EXPORT long long MemoryStream::Capacity( ) const
        {
            if ( data_ )
            {
                return data_->Capacity( );
            }
            return 0;
        }
        HWIN_EXPORT MemoryStream& MemoryStream::SetCapacity( long long theSize )
        {
            if ( !data_ )
            {
                data_ = new Data( );
            }
            data_->SetCapacity( theSize );
            return *this;
        }

        HWIN_EXPORT long long MemoryStream::Size( ) const
        {
            if ( data_ )
            {
                return data_->Size( );
            }
            return 0;
        }
        HWIN_EXPORT StreamBase& MemoryStream::SetSize( long long theSize )
        {
            if ( !data_ )
            {
                data_ = new Data( );
            }
            data_->SetSize( theSize );
            return *this;
        }
        HWIN_EXPORT long long MemoryStream::Read( void* buffer, size_t numberOfBytesToRead )
        {
            if ( data_ )
            {
                auto result = data_->Read( position_, buffer, numberOfBytesToRead );
                return result;
            }
            return 0;
        }
        HWIN_EXPORT long long MemoryStream::Write( const void* buffer, size_t numberOfBytesToWrite )
        {
            if ( numberOfBytesToWrite )
            {
                if ( !data_ )
                {
                    data_ = new Data( );
                }
                auto result = data_->Write( position_, buffer, numberOfBytesToWrite );
                return result;
            }
            return 0;
        }
        HWIN_EXPORT long long MemoryStream::Seek( long long offset, SeekOrigin seekOrigin )
        {
            if ( !data_ )
            {
                data_ = new Data( );
            }
            auto result = data_->Seek( position_, offset, seekOrigin );
            return result;
        }
        HWIN_EXPORT std::shared_ptr<StreamBase> MemoryStream::Clone( ) const
        {
            auto result = std::make_shared<MemoryStream>( *this );
            return result;
        }


        // -----------------------------------------------------------------
        // FileSystemEntry
        // -----------------------------------------------------------------
        HWIN_EXPORT  FileSystemEntry::FileSystemEntry( const WideString& theParentDirectory, const WideString& theName, FileAttributes theAttributes,
                                                                                         const DateTime& theCreationTime, const DateTime& theLastAccessTime, const DateTime& theLastWriteTime )
                                                                                         : parentDirectory( theParentDirectory ), name( theName ), attributes( theAttributes ),
                                                                                         creationTime( theCreationTime ), lastAccessTime( theLastAccessTime ), lastWriteTime( theLastWriteTime )
        {
        }

        // -----------------------------------------------------------------
        // FileInfo
        // -----------------------------------------------------------------
        HWIN_EXPORT  FileInfo::FileInfo( const WideString& theParentDirectory, const WideString& theName, FileAttributes theAttributes,
                                                                           const DateTime& theCreationTime, const DateTime& theLastAccessTime, const DateTime& lastWriteTime,
                                                                           long long theFileSize )
                                                                           : Base( theParentDirectory, theName, theAttributes, theCreationTime, theLastAccessTime, lastWriteTime ),
                                                                           fileSize( theFileSize )
        {
        }


        // -----------------------------------------------------------------
        // DirectoryInfo
        // -----------------------------------------------------------------
        HWIN_EXPORT  DirectoryInfo::DirectoryInfo( const WideString& theParentDirectory, const WideString& theName, FileAttributes theAttributes,
                                                                                     const DateTime& theCreationTime, const DateTime& theLastAccessTime, const DateTime& lastWriteTime )
                                                                                     : Base( theParentDirectory, theName, theAttributes, theCreationTime, theLastAccessTime, lastWriteTime )
        {
        }

        // -----------------------------------------------------------------
        // FileSystemEntriesBase
        // -----------------------------------------------------------------
        HWIN_EXPORT  FileSystemEntriesBase::FileSystemEntriesBase( const WideString& thePath, const WideString& theSearchPattern )
            : path( thePath ), searchPattern( theSearchPattern ), searchHandle( INVALID_HANDLE_VALUE )
        {
            path.TrimRight( L"\\/", 2 );
            path = Path::GetFullPathName( path );
        }

        HWIN_EXPORT  FileSystemEntriesBase::FileSystemEntriesBase( const WideString& theSearchPattern )
            : searchPattern( theSearchPattern ),
            searchHandle( INVALID_HANDLE_VALUE )
        {
            path = Directory::GetCurrentDirectory( );
        }

        HWIN_EXPORT  FileSystemEntriesBase::~FileSystemEntriesBase( )
        {
            if ( searchHandle != INVALID_HANDLE_VALUE )
            {
                FindClose( searchHandle );
            }
        }

        HWIN_EXPORT  bool FileSystemEntriesBase::Read( )
        {
            current.reset( );
            memset( &data, 0, sizeof( WIN32_FIND_DATA ) );
            if ( searchHandle == INVALID_HANDLE_VALUE )
            {
                WideString s = path;
                s += L'\\';
                s += searchPattern;

                searchHandle = FindFirstFileExW( s.c_str( ), FindExInfoBasic, &data, FindExSearchNameMatch, nullptr, 0 );
                if ( searchHandle == INVALID_HANDLE_VALUE )
                {
                    if ( GetLastError( ) != ERROR_FILE_NOT_FOUND )
                    {
                        ThrowLastOSError( );
                    }
                    else
                    {
                        return false;
                    }
                }
                return true;
            }
            else
            {
                if ( FindNextFileW( searchHandle, &data ) == 0 )
                {
                    if ( GetLastError( ) != ERROR_FILE_NOT_FOUND )
                    {
                        ThrowLastOSError( );
                    }
                    else
                    {
                        return false;
                    }
                }
                return true;
            }
        }

        HWIN_EXPORT  WideString FileSystemEntriesBase::Name( ) const
        {
            return data.cFileName;
        }
        HWIN_EXPORT  WideString FileSystemEntriesBase::FullPath( ) const
        {
            WideString result = path;
            result += '\\';
            result += data.cFileName;
            return result;
        }


        // -----------------------------------------------------------------
        // Path
        // -----------------------------------------------------------------
        HWIN_EXPORT  WideString Path::ChangeExtension( const WideString& path, const WideString& newExtension )
        {
            if ( path.IsEmpty( ) == false )
            {
                CheckInvalidPathChars( path );
                wchar_t stopCharacters [] = { '.', DirectorySeparatorChar, AltDirectorySeparatorChar, VolumeSeparatorChar, '\x00' };


                WideString::size_type index = path.LastIndexOfAnyOf( stopCharacters );
                WideString result = path;
                if ( index != WideString::npos )
                {
                    if ( path[index] == '.' )
                    {
                        result = path.SubString( 0, index );
                    }
                }

                if ( newExtension.IsEmpty( ) == false )
                {
                    if ( newExtension[0] != '.' )
                    {
                        result += '.';
                    }
                    result += newExtension;
                }
                return result;
            }
            return WideString( );
        }

        HWIN_EXPORT  WideString Path::GetLongPathName( const WideString& path )
        {
            if ( path.IsEmpty( ) == false )
            {
                wchar_t buffer[MAX_PATH + 1] = { 0, };
                auto length = ::GetLongPathNameW( path.c_str( ), buffer, sizeof( buffer ) / sizeof( wchar_t ) );
                if ( length == 0 )
                {
                    ThrowLastOSError( );
                }
                if ( length > ( sizeof( buffer ) / sizeof( wchar_t ) ) )
                {
                    WideString result;
                    result.SetLength( length - 1 );
                    length = ::GetLongPathNameW( path.c_str( ), result.c_str( ), length );
                    if ( length == 0 )
                    {
                        ThrowLastOSError( );
                    }
                    return result;
                }
                else
                {
                    WideString result( buffer, length );
                    return result;
                }
            }
            return WideString( );
        }

        HWIN_EXPORT  WideString Path::GetFullPathName( const WideString& path )
        {
            if ( path.IsEmpty( ) == false )
            {
                LPWSTR filePart;
                wchar_t buffer[MAX_PATH + 1] = { 0, };
                auto length = ::GetFullPathNameW( path.c_str( ), sizeof( buffer ) / sizeof( wchar_t ), buffer, &filePart );
                if ( length == 0 )
                {
                    ThrowLastOSError( );
                }
                if ( length >= ( sizeof( buffer ) / sizeof( wchar_t ) ) )
                {
                    WideString result;
                    result.SetLength( length - 1 );
                    length = ::GetFullPathNameW( path.c_str( ), length, result.c_str( ), &filePart );
                    if ( length == 0 )
                    {
                        ThrowLastOSError( );
                    }
                    return result;
                }
                else
                {
                    WideString result( buffer, length );
                    return result;
                }
            }
            return WideString( );
        }
        HWIN_EXPORT  WideString Path::GetFullPathName( const WideString& path, WideString::size_type& indexOfFileName )
        {
            if ( path.IsEmpty( ) == false )
            {
                LPWSTR filePart;
                wchar_t buffer[MAX_PATH + 1] = { 0, };
                auto length = ::GetFullPathNameW( path.c_str( ), sizeof( buffer ) / sizeof( wchar_t ), buffer, &filePart );
                if ( length == 0 )
                {
                    ThrowLastOSError( );
                }
                if ( length >= ( sizeof( buffer ) / sizeof( wchar_t ) ) )
                {
                    WideString result;
                    result.SetLength( length - 1 );
                    length = ::GetFullPathNameW( path.c_str( ), length, result.c_str( ), &filePart );
                    if ( length == 0 )
                    {
                        ThrowLastOSError( );
                    }
                    indexOfFileName = filePart - result.c_str( );
                    return result;
                }
                else
                {
                    indexOfFileName = filePart - buffer;
                    WideString result( buffer, length );
                    return result;
                }
            }
            indexOfFileName = WideString::npos;
            return WideString( );
        }

        // -----------------------------------------------------------------
        // File
        // -----------------------------------------------------------------
        namespace
        {
            bool ExistsLockedOrShared( const wchar_t* path )
            {
                WIN32_FIND_DATAW FindData;
                HANDLE hFind;
                bool result = false;
                // Either the file is locked/share_exclusive or we got an access denied 
                hFind = FindFirstFileW( path, &FindData );
                if ( hFind != INVALID_HANDLE_VALUE )
                {
                    FindClose( hFind );
                    result = ( FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) == 0;
                }
                return result;
            }
        }
        HWIN_EXPORT  bool File::Exist( const WideString& path )
        {
            if ( path.IsEmpty( ) == false )
            {
                auto attrs = GetFileAttributesW( path.c_str( ) );
                if ( attrs != INVALID_FILE_ATTRIBUTES )
                {
                    if ( ( attrs & FILE_ATTRIBUTE_DIRECTORY ) == 0 )
                    {
                        return true;
                    }
                }
                else
                {
                    auto lastError = GetLastError( );
                    if ( ( lastError != ERROR_FILE_NOT_FOUND ) &&
                         ( lastError != ERROR_PATH_NOT_FOUND ) &&
                         ( lastError != ERROR_INVALID_NAME ) )
                    {
                        return ExistsLockedOrShared( path.c_str( ) );
                    }

                }
            }
            return false;
        }

        HWIN_EXPORT  bool File::Exist( const wchar_t* path )
        {
            if ( path && path[0] )
            {
                auto attrs = GetFileAttributesW( path );
                if ( attrs != INVALID_FILE_ATTRIBUTES )
                {
                    if ( ( attrs & FILE_ATTRIBUTE_DIRECTORY ) == 0 )
                    {
                        return true;
                    }
                }
                else
                {
                    auto lastError = GetLastError( );
                    if ( ( lastError != ERROR_FILE_NOT_FOUND ) &&
                         ( lastError != ERROR_PATH_NOT_FOUND ) &&
                         ( lastError != ERROR_INVALID_NAME ) )
                    {
                        return ExistsLockedOrShared( path );
                    }

                }
            }
            return false;
        }


        // -----------------------------------------------------------------
        // Directory
        // -----------------------------------------------------------------
        HWIN_EXPORT  WideString Directory::GetCurrentDirectory( )
        {
            wchar_t buffer[MAX_PATH + 1] = { 0, };
            auto length = ::GetCurrentDirectoryW( sizeof( buffer ) / sizeof( wchar_t ), buffer );
            if ( length == 0 )
            {
                ThrowLastOSError( );
            }
            if ( length > ( sizeof( buffer ) / sizeof( wchar_t ) ) )
            {
                WideString result;
                result.SetLength( length - 1 );
                length = ::GetCurrentDirectoryW( length, result.c_str( ) );
                if ( length == 0 )
                {
                    ThrowLastOSError( );
                }
                return result;
            }
            else
            {
                WideString result( buffer, length );
                return result;
            }
        }


        HWIN_EXPORT  bool Directory::Exist( const WideString& path )
        {
            if ( path.IsEmpty( ) == false )
            {
                auto attrs = GetFileAttributesW( path.c_str( ) );
                if ( attrs != INVALID_FILE_ATTRIBUTES )
                {
                    if ( ( attrs & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        HWIN_EXPORT  bool Directory::Exist( const wchar_t* path )
        {
            if ( path )
            {
                auto attrs = GetFileAttributesW( path );
                if ( attrs != INVALID_FILE_ATTRIBUTES )
                {
                    if ( ( attrs & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        // -----------------------------------------------------------------
        // StreamCore
        // -----------------------------------------------------------------

        HWIN_EXPORT  StreamCore::StreamCore( HANDLE theFileHandle )
            : hFile( theFileHandle )
        {
        }

        HWIN_EXPORT  StreamCore::~StreamCore( )
        {
            if ( hFile != INVALID_HANDLE_VALUE )
            {
                CloseHandle( hFile );
                hFile = INVALID_HANDLE_VALUE;
            }
        }

        HWIN_EXPORT bool StreamCore::CanRead( ) const
        {
            return true;
        }
        HWIN_EXPORT bool StreamCore::CanSeek( ) const
        {
            return true;
        }
        HWIN_EXPORT bool StreamCore::CanTimeout( ) const
        {
            return true;
        }
        HWIN_EXPORT bool StreamCore::CanWrite( ) const
        {
            return true;
        }

        HWIN_EXPORT  StreamBase& StreamCore::SetPosition( long long thePosition )
        {
            Seek( thePosition, SeekOrigin::StartOfFile );
            return *this;
        }

        HWIN_EXPORT  long long StreamCore::Size( ) const
        {
            LARGE_INTEGER llFileSize;
            llFileSize.QuadPart = 0;
            if ( GetFileSizeEx( hFile, &llFileSize ) == 0 )
            {
                ThrowLastOSError( );
            }
            return llFileSize.QuadPart;
        }
        HWIN_EXPORT  StreamBase& StreamCore::SetSize( long long theSize )
        {
            long long currentPosition = this->Position( );
            long long newPosition = Seek( theSize, SeekOrigin::StartOfFile );
            SetEndOfFile( hFile );
            if ( currentPosition < newPosition )
            {
                Seek( currentPosition, SeekOrigin::StartOfFile );
            }
            return *this;
        }

        HWIN_EXPORT  StreamBase& StreamCore::Flush( )
        {
            if ( FlushFileBuffers( hFile ) == 0 )
            {
                ThrowLastOSError( );
            }
            return *this;
        }

        HWIN_EXPORT  long long StreamCore::Read( void* buffer, size_t numberOfBytesToRead )
        {
            DWORD numberOfBytesRead = 0;
            if ( ReadFile( hFile, buffer, DWORD( numberOfBytesToRead ), &numberOfBytesRead, nullptr ) == 0 )
            {
                ThrowLastOSError( );
            }
            return numberOfBytesRead;
        }

        HWIN_EXPORT  long long StreamCore::Write( const void* buffer, size_t numberOfBytesToWrite )
        {
            DWORD numberOfBytesWritten = 0;
            if ( WriteFile( hFile, buffer, DWORD( numberOfBytesToWrite ), &numberOfBytesWritten, nullptr ) == 0 )
            {
                ThrowLastOSError( );
            }
            return numberOfBytesWritten;
        }

        HWIN_EXPORT  long long StreamCore::Seek( long long offset, SeekOrigin seekOrigin )
        {
            LARGE_INTEGER llOffset;
            llOffset.QuadPart = offset;
            LARGE_INTEGER llNewPosition;
            llNewPosition.QuadPart = 0;
            if ( SetFilePointerEx( hFile, llOffset, &llNewPosition, DWORD( seekOrigin ) ) == 0 )
            {
                ThrowLastOSError( );
            }
            return llNewPosition.QuadPart;
        }

        HWIN_EXPORT  std::shared_ptr<StreamBase> StreamCore::Clone( ) const
        {
            HANDLE newHandle = 0;
            if ( ::DuplicateHandle( GetCurrentProcess( ), hFile, GetCurrentProcess( ), &newHandle, 0, FALSE, DUPLICATE_SAME_ACCESS ) == 0 )
            {
                ThrowLastOSError( );
            }
            auto result = std::make_shared<StreamCore>( newHandle );
            return result;
        }

        // -----------------------------------------------------------------
        // FileStream
        // -----------------------------------------------------------------

        HWIN_EXPORT  HANDLE FileStream::Create( LPCWSTR lpFileName, FileAccess fileAccess, FileShare fileShare, LPSECURITY_ATTRIBUTES lpSecurityAttributes, FileMode fileMode, FileAttributes attributes, FileOptions fileOptions )
        {
            DWORD creationDisposition = 0;
            if ( fileMode != FileMode::Append )
            {
                creationDisposition = DWORD( fileMode );
            }
            else
            {
                creationDisposition = DWORD( FileMode::OpenOrCreate );
            }
            DWORD flagsAndAttributes = DWORD( attributes ) | DWORD( fileOptions );
            HANDLE result = ::CreateFileW( lpFileName, DWORD( fileAccess ), DWORD( fileShare ), lpSecurityAttributes, creationDisposition, flagsAndAttributes, nullptr );

            if ( result == INVALID_HANDLE_VALUE )
            {
                ThrowLastOSError( );
            }

            if ( fileMode == FileMode::Append )
            {
                LARGE_INTEGER liDistanceToMove;
                liDistanceToMove.QuadPart = 0;
                if ( SetFilePointerEx( result, liDistanceToMove, nullptr, FILE_END ) == 0 )
                {
                    CloseHandle( result );
                    ThrowLastOSError( );
                }
            }

            return result;
        }

        HWIN_EXPORT  FileStream::FileStream( const WideString& fileName, FileAccess fileAccess, FileShare fileShare, LPSECURITY_ATTRIBUTES lpSecurityAttributes, FileMode fileMode, FileAttributes attributes, FileOptions fileOptions )
            : Base( Create( fileName.c_str( ), fileAccess, fileShare, lpSecurityAttributes, fileMode, attributes, fileOptions ) )
        {
        }
        HWIN_EXPORT  FileStream::FileStream( LPCWSTR fileName, FileAccess fileAccess, FileShare fileShare, LPSECURITY_ATTRIBUTES lpSecurityAttributes, FileMode fileMode, FileAttributes attributes, FileOptions fileOptions )
            : Base( Create( fileName, fileAccess, fileShare, lpSecurityAttributes, fileMode, attributes, fileOptions ) )
        {
        }

        HWIN_EXPORT  FileStream::FileStream( const WideString& fileName )
            : Base( Create( fileName.c_str( ), FileAccess::Default, FileShare::Default, nullptr, FileMode::Default, FileAttributes::Normal, FileOptions::Default ) )
        {
        }
        HWIN_EXPORT  FileStream::FileStream( LPCWSTR fileName )
            : Base( Create( fileName, FileAccess::Default, FileShare::Default, nullptr, FileMode::Default, FileAttributes::Normal, FileOptions::Default ) )
        {
        }

        HWIN_EXPORT  FileStream::FileStream( const WideString& fileName, FileAccess fileAccess )
            : Base( Create( fileName.c_str( ), fileAccess, FileShare::Default, nullptr, FileMode::Default, FileAttributes::Normal, FileOptions::Default ) )
        {
        }
        HWIN_EXPORT  FileStream::FileStream( LPCWSTR fileName, FileAccess fileAccess )
            : Base( Create( fileName, fileAccess, FileShare::Default, nullptr, FileMode::Default, FileAttributes::Normal, FileOptions::Default ) )
        {
        }

        HWIN_EXPORT  FileStream::FileStream( const WideString& fileName, FileAccess fileAccess, FileShare fileShare )
            : Base( Create( fileName.c_str( ), fileAccess, fileShare, nullptr, FileMode::Default, FileAttributes::Normal, FileOptions::Default ) )
        {
        }
        HWIN_EXPORT  FileStream::FileStream( LPCWSTR fileName, FileAccess fileAccess, FileShare fileShare )
            : Base( Create( fileName, fileAccess, fileShare, nullptr, FileMode::Default, FileAttributes::Normal, FileOptions::Default ) )
        {
        }

        HWIN_EXPORT  FileStream::FileStream( const WideString& fileName, FileAccess fileAccess, FileMode fileMode )
            : Base( Create( fileName.c_str( ), fileAccess, FileShare::Default, nullptr, fileMode, FileAttributes::Normal, FileOptions::Default ) )
        {
        }
        HWIN_EXPORT  FileStream::FileStream( LPCWSTR fileName, FileAccess fileAccess, FileMode fileMode )
            : Base( Create( fileName, fileAccess, FileShare::Default, nullptr, fileMode, FileAttributes::Normal, FileOptions::Default ) )
        {
        }

        HWIN_EXPORT  FileStream::FileStream( const WideString& fileName, FileAccess fileAccess, FileShare fileShare, FileMode fileMode )
            : Base( Create( fileName.c_str( ), fileAccess, fileShare, nullptr, fileMode, FileAttributes::Normal, FileOptions::Default ) )
        {
        }
        HWIN_EXPORT  FileStream::FileStream( LPCWSTR fileName, FileAccess fileAccess, FileShare fileShare, FileMode fileMode )
            : Base( Create( fileName, fileAccess, fileShare, nullptr, fileMode, FileAttributes::Normal, FileOptions::Default ) )
        {
        }

        HWIN_EXPORT  FileStream::FileStream( const WideString& fileName, FileShare fileShare, FileMode fileMode )
            : Base( Create( fileName.c_str( ), FileAccess::Default, fileShare, nullptr, fileMode, FileAttributes::Normal, FileOptions::Default ) )
        {
        }
        HWIN_EXPORT  FileStream::FileStream( LPCWSTR fileName, FileShare fileShare, FileMode fileMode )
            : Base( Create( fileName, FileAccess::Default, fileShare, nullptr, fileMode, FileAttributes::Normal, FileOptions::Default ) )
        {
        }

        HWIN_EXPORT  FileStream::FileStream( const WideString& fileName, FileMode fileMode )
            : Base( Create( fileName.c_str( ), FileAccess::Default, FileShare::Default, nullptr, fileMode, FileAttributes::Normal, FileOptions::Default ) )
        {
        }
        HWIN_EXPORT  FileStream::FileStream( LPCWSTR fileName, FileMode fileMode )
            : Base( Create( fileName, FileAccess::Default, FileShare::Default, nullptr, fileMode, FileAttributes::Normal, FileOptions::Default ) )
        {
        }


        HWIN_EXPORT  FileStream::FileStream( const WideString& fileName, FileAccess fileAccess, FileShare fileShare, FileMode fileMode, FileAttributes attributes, FileOptions fileOptions )
            : Base( Create( fileName.c_str( ), fileAccess, fileShare, nullptr, fileMode, attributes, fileOptions ) )
        {
        }
        HWIN_EXPORT  FileStream::FileStream( LPCWSTR fileName, FileAccess fileAccess, FileShare fileShare, FileMode fileMode, FileAttributes attributes, FileOptions fileOptions )
            : Base( Create( fileName, fileAccess, fileShare, nullptr, fileMode, attributes, fileOptions ) )
        {
        }
    };
};

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Sea Surveillance AS
Norway Norway
Chief Architect - Sea Surveillance AS.

Specializing in integrated operations and high performance computing solutions.

I’ve been fooling around with computers since the early eighties, I’ve even done work on CP/M and MP/M.

Wrote my first “real” program on a BBC micro model B based on a series in a magazine at that time. It was fun and I got hooked on this thing called programming ...

A few Highlights:

  • High performance application server development
  • Model Driven Architecture and Code generators
  • Real-Time Distributed Solutions
  • C, C++, C#, Java, TSQL, PL/SQL, Delphi, ActionScript, Perl, Rexx
  • Microsoft SQL Server, Oracle RDBMS, IBM DB2, PostGreSQL
  • AMQP, Apache qpid, RabbitMQ, Microsoft Message Queuing, IBM WebSphereMQ, Oracle TuxidoMQ
  • Oracle WebLogic, IBM WebSphere
  • Corba, COM, DCE, WCF
  • AspenTech InfoPlus.21(IP21), OsiSoft PI


More information about what I do for a living can be found at: harlinn.com or LinkedIn

You can contact me at espen@harlinn.no

Comments and Discussions