; _______________________________________________________________________________________
;|                                                                                       |
;| ..::FreshLib::..  Free, open source. Licensed under "BSD 2-clause" license."          |
;|_______________________________________________________________________________________|
;
;  Description: Clipboard management library.
;
;  Target OS: Linux
;
;  Dependencies:
;
;  Notes:
;_________________________________________________________________________________________


if used ClipboardRead | used ClipboardWrite
  __UseClipboard = 1
else
  __UseClipboard = 0
end if



body ClipboardRead
.result dd ?

.event XEvent

.return_type    dd ?
.return_format  dd ?
.return_items   dd ?
.return_remains dd ?
.return_data    dd ?

begin
        pushad
        mov     [.result], 0

        cinvoke XGetSelectionOwner, [hApplicationDisplay], [atomSelClipboard]
        test    eax, eax
        jz      .finish

        cinvoke XConvertSelection, [hApplicationDisplay], [atomSelClipboard], [atomUTF8], [atomUTF8], [hClipboardWindow], CurrentTime

.wait_loop:
        lea     eax, [.event]
        cinvoke XCheckTypedEvent, [hApplicationDisplay], SelectionNotify, eax
        test    eax, eax
        jz      .wait_loop

        cmp     [.event+XSelectionEvent.property], None
        je      .finish

        lea     esi, [.return_data]
        lea     edx, [.return_remains]
        lea     ecx, [.return_items]
        lea     ebx, [.return_format]
        lea     eax, [.return_type]

        cinvoke XGetWindowProperty, [hApplicationDisplay], [.event+XSelectionEvent.requestor], [.event+XSelectionEvent.property], 0, $7fffffff, FALSE, AnyPropertyType, eax, ebx, ecx, edx, esi

        mov     eax, [.return_type]
        cmp     eax, [atomUTF8]
        jne     .finish

        mov      eax, [.return_data]
        test     eax, eax
        jz       .finish

        stdcall StrDup, eax
        mov     [.result], eax

        cinvoke XFree, [.return_data]

.finish:
        popad
        mov     eax, [.result]
        return
endp



body ClipboardWrite   ; .hstrings
begin



        return
endp




uglobal
  var atomSelClipboard = 0
  var atomUTF8 = 0
  var hClipboardWindow = 0
endg


proc __InitLinuxClipboard
begin
        cinvoke XInternAtom, [hApplicationDisplay], "CLIPBOARD", FALSE
        mov     [atomSelClipboard], eax

        cinvoke XInternAtom, [hApplicationDisplay], "UTF8_STRING", FALSE
        mov     [atomUTF8], eax

        cinvoke XCreateWindow, [hApplicationDisplay], [hRootWindow], 0, 0, 1, 1, 0, CopyFromParent, InputOnly, CopyFromParent, 0, 0
        mov     [hClipboardWindow], eax
        return
endp

