; _______________________________________________________________________________________
;|                                                                                       |
;| ..::FreshLib::..  Free, open source. Licensed under "Fresh artistic license."         |
;|_______________________________________________________________________________________|
;
;  Description: Clipboard management library.
;
;  Target OS: Win32
;
;  Dependencies:
;_________________________________________________________________________________________


; returns eax = handle to string with the clipboard data.
proc ClipboardRead
.result dd ?
begin
        pushad
        xor     eax, eax
        mov     [.result], eax

        invoke  OpenClipboard, eax
        test    eax, eax
        jz      .finish

        invoke  GetClipboardData, CF_UNICODETEXT
        test    eax, eax
        jz      .close

        mov     ebx, eax

        invoke  GlobalSize, ebx
        mov     edi, eax

        invoke  GlobalLock, ebx
        mov     esi, eax

        lea     ecx, [8*edi]

        stdcall GetMem, ecx
        jc      .close3
        mov     edi, eax

        invoke  WideCharToMultiByte, CP_UTF8, 0, esi, -1, edi, ecx, 0, 0
        test    eax, eax
        jz      .close2

        mov     dword [edi+eax], 0

        stdcall StrDup, edi
        mov     [.result], eax

.close2:
        stdcall FreeMem, edi
.close3:
        invoke  GlobalUnlock, ebx
.close:
        invoke  CloseClipboard
        popad
.finish:
        mov     eax, [.result]
        return
endp



; writes the string .hstring to the clipboard.
; returns nothing.

proc ClipboardWrite, .hstring
begin
        pushad
        xor     eax, eax
        invoke  OpenClipboard, eax
        test    eax, eax
        jz      .finish

        invoke  EmptyClipboard

        stdcall utf8ToWideChar, [.hstring]
        mov     esi, eax
        shl     ecx, 3

        invoke  GlobalAlloc, GMEM_MOVEABLE or GMEM_ZEROINIT or GMEM_DDESHARE, ecx
        test    eax, eax
        jz      .close
        mov     ebx, eax

        invoke  GlobalLock, ebx
        mov     edi, eax
        invoke  lstrcpyW, edi, esi
        invoke  GlobalUnlock, ebx

        invoke  SetClipboardData, CF_UNICODETEXT, ebx

.close:
        stdcall FreeMem, esi
        invoke  CloseClipboard
.finish:
        popad
        return
endp


