/* COM desktop-switch notifications adapted from Ciantic/VirtualDesktopAccessor.
 * Copyright (c) 2015-2023 Jari Otto Oskari Pennanen. See LICENSE.txt.
 * Listener HWNDs must be unregistered before unloading the DLL.
 */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <objbase.h>
#include <winstring.h>
#include <string.h>
#define VDA_BUILD_DLL
#include "virtualdesktopaccessor.h"

#define EXPORT __declspec(dllexport)
#define SLOT(obj, index, type) ((type)(*(void ***)(obj))[index])
#define RELEASE(obj) do { if (obj) SLOT(obj, 2, ULONG (STDMETHODCALLTYPE *)(void *))(obj); } while (0)

static const GUID cls_shell = {0xc2f03a33,0x21f5,0x47fa,{0xb4,0xbb,0x15,0x63,0x62,0xa2,0xf2,0x39}};
static const GUID iid_service = {0x6d5140c1,0x7436,0x11ce,{0x80,0x34,0x00,0xaa,0x00,0x60,0x09,0xfa}};
static const GUID cls_notifications = {0xa501fdec,0x4a09,0x464c,{0xae,0x4e,0x1b,0x9c,0x21,0xb8,0x49,0x18}};
static const GUID iid_notifications = {0x0cd45e71,0xd927,0x4f15,{0x8b,0x0a,0x8f,0xef,0x52,0x53,0x37,0xbf}};
static const GUID iid_callback = {0xb9e5e94d,0x233e,0x49ab,{0xaf,0x5c,0x2b,0x45,0x41,0xc3,0xaa,0xde}};
static const GUID iid_unknown = {0x00000000,0x0000,0x0000,{0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46}};
static const GUID cls_internal = {0xc5e0cdca,0x7b6e,0x41b2,{0x9f,0xc4,0xd9,0x39,0x75,0xcc,0x46,0x7b}};
static const GUID iid_internal = {0x53f5ca0b,0x158f,0x4124,{0x90,0x0c,0x05,0x71,0x58,0x06,0x0b,0x27}};

typedef struct { HWND hwnd; UINT message; } Listener;
typedef struct DesktopEvent { GUID old_id, new_id; struct DesktopEvent *next; } DesktopEvent;
static CRITICAL_SECTION listeners_lock;
static INIT_ONCE once = INIT_ONCE_STATIC_INIT;
static HANDLE stop_event, ready_event, queue_event, thread;
static DesktopEvent *pending_head, *pending_tail;
static int ready_status, stopping;
static Listener *listeners;
static size_t listener_count, listener_capacity;

static BOOL CALLBACK init_state(PINIT_ONCE ignored, PVOID parameter, PVOID *context) {
    (void)ignored; (void)parameter; (void)context;
    InitializeCriticalSection(&listeners_lock);
    stop_event = CreateEventA(NULL, TRUE, FALSE, NULL);
    ready_event = CreateEventA(NULL, TRUE, FALSE, NULL);
    queue_event = CreateEventA(NULL, FALSE, FALSE, NULL);
    return stop_event && ready_event && queue_event;
}

static ULONG STDMETHODCALLTYPE callback_addref(void *self) {
    return (ULONG)InterlockedIncrement((LONG *)((char *)self + sizeof(void *)));
}
static ULONG STDMETHODCALLTYPE callback_release(void *self) {
    return (ULONG)InterlockedDecrement((LONG *)((char *)self + sizeof(void *)));
}
static HRESULT STDMETHODCALLTYPE callback_query(void *self, const GUID *iid, void **out) {
    if (!out || !iid) return E_POINTER;
    *out = NULL;
    if (!IsEqualGUID(iid, &iid_unknown) && !IsEqualGUID(iid, &iid_callback)) return E_NOINTERFACE;
    *out = self;
    callback_addref(self);
    return S_OK;
}
static HRESULT STDMETHODCALLTYPE ignore_one(void *self, void *a) { (void)self; (void)a; return S_OK; }
static HRESULT STDMETHODCALLTYPE ignore_two(void *self, void *a, void *b) {
    (void)self; (void)a; (void)b; return S_OK;
}
static HRESULT STDMETHODCALLTYPE ignore_moved(void *self, void *desktop, LONGLONG old, LONGLONG next) {
    (void)self; (void)desktop; (void)old; (void)next; return S_OK;
}
static HRESULT STDMETHODCALLTYPE ignore_string(void *self, void *desktop, HSTRING text) {
    (void)self; (void)desktop; (void)text; return S_OK;
}

static HRESULT STDMETHODCALLTYPE current_changed(void *self, void *old, void *next) {
    (void)self;
    if (!old || !next) return S_OK;
    GUID old_id = {0}, new_id = {0};
    if (FAILED(SLOT(old, 4, HRESULT (STDMETHODCALLTYPE *)(void *, GUID *))(old, &old_id)) ||
        FAILED(SLOT(next, 4, HRESULT (STDMETHODCALLTYPE *)(void *, GUID *))(next, &new_id))) return S_OK;
    /* Shell owns old/next: never Release callback parameters. */
    /* Do not make reentrant Explorer COM calls inside an Explorer callback. */
    DesktopEvent *event = HeapAlloc(GetProcessHeap(), 0, sizeof *event);
    if (!event) return S_OK;
    *event = (DesktopEvent){ .old_id = old_id, .new_id = new_id, .next = NULL };
    EnterCriticalSection(&listeners_lock);
    if (!listener_count) {
        LeaveCriticalSection(&listeners_lock);
        HeapFree(GetProcessHeap(), 0, event);
        return S_OK;
    }
    if (pending_tail) pending_tail->next = event;
    else pending_head = event;
    pending_tail = event;
    LeaveCriticalSection(&listeners_lock);
    SetEvent(queue_event);
    return S_OK;
}

/* IUnknown (0-2), followed by the 11 slots of IVirtualDesktopNotification. */
static void *callback_vtable[] = {
    callback_query, callback_addref, callback_release,
    ignore_one, ignore_two, ignore_two, ignore_two, ignore_moved,
    ignore_string, ignore_one, current_changed, ignore_string, ignore_one, ignore_one
};
static struct { void **vtbl; LONG refs; } callback = { callback_vtable, 1 };

static int connect_service(void **provider, void **service, void **manager, DWORD *cookie) {
    HRESULT hr = CoCreateInstance(&cls_shell, NULL, CLSCTX_LOCAL_SERVER, &iid_service, provider);
    if (FAILED(hr) || !*provider) return 0;
    HRESULT (STDMETHODCALLTYPE *query)(void *, const GUID *, const GUID *, void **) =
        SLOT(*provider, 3, HRESULT (STDMETHODCALLTYPE *)(void *, const GUID *, const GUID *, void **));
    hr = query(*provider, &cls_notifications, &iid_notifications, service);
    if (FAILED(hr) || !*service) return 0;
    hr = query(*provider, &cls_internal, &iid_internal, manager);
    if (FAILED(hr) || !*manager) return 0;
    hr = SLOT(*service, 3, HRESULT (STDMETHODCALLTYPE *)(void *, void *, DWORD *))
        (*service, &callback, cookie);
    return SUCCEEDED(hr);
}

static int disconnect_service(void **provider, void **service, void **manager,
    DWORD cookie, int registered) {
    int safe_to_unload = 1;
    if (*service && registered && FAILED(SLOT(*service, 4,
        HRESULT (STDMETHODCALLTYPE *)(void *, DWORD))(*service, cookie)))
        safe_to_unload = 0;
    RELEASE(*manager); RELEASE(*service); RELEASE(*provider);
    *manager = *service = *provider = NULL;
    return safe_to_unload;
}

static DWORD WINAPI notification_thread(void *unused) {
    (void)unused;
    /* Keep code mapped while Explorer holds a pointer to our COM callback. */
    HMODULE self_pin = NULL;
    GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
        (LPCSTR)notification_thread, &self_pin);
    HRESULT hr = self_pin ? CoInitializeEx(NULL, COINIT_MULTITHREADED) : E_FAIL;
    void *provider = NULL, *service = NULL, *manager = NULL;
    DWORD cookie = 0;
    int registered = SUCCEEDED(hr) &&
        connect_service(&provider, &service, &manager, &cookie);
    ready_status = registered;
    SetEvent(ready_event);
    HANDLE events[] = {stop_event, queue_event};
    while (ready_status) {
        DWORD wait = WaitForMultipleObjects(2, events, FALSE, 3000);
        if (wait == WAIT_OBJECT_0) break;
        if (wait == WAIT_OBJECT_0 + 1) {
            EnterCriticalSection(&listeners_lock);
            DesktopEvent *list = pending_head;
            pending_head = pending_tail = NULL;
            LeaveCriticalSection(&listeners_lock);
            while (list) {
                DesktopEvent *next = list->next;
                int old_index = GetDesktopNumberById(list->old_id);
                int new_index = GetDesktopNumberById(list->new_id);
                if (old_index >= 0 && new_index >= 0) {
                    EnterCriticalSection(&listeners_lock);
                    for (size_t i = 0; i < listener_count; i++)
                        PostMessageW(listeners[i].hwnd, listeners[i].message,
                            (WPARAM)old_index, (LPARAM)new_index);
                    LeaveCriticalSection(&listeners_lock);
                }
                HeapFree(GetProcessHeap(), 0, list);
                list = next;
            }
        } else if (wait == WAIT_TIMEOUT) {
            UINT count = 0;
            HRESULT status = manager
                ? SLOT(manager, 3, HRESULT (STDMETHODCALLTYPE *)(void *, UINT *))(manager, &count)
                : E_FAIL;
            if (FAILED(status) || count == 0) {
                /* Unregister the old cookie before the new server can reuse it. */
                if (!disconnect_service(&provider, &service, &manager, cookie, registered))
                    self_pin = NULL; /* Leak one module reference rather than unload live callback code. */
                cookie = 0;
                registered = connect_service(&provider, &service, &manager, &cookie);
            }
        } else break;
    }
    if (!disconnect_service(&provider, &service, &manager, cookie, registered))
        self_pin = NULL;
    EnterCriticalSection(&listeners_lock);
    while (pending_head) {
        DesktopEvent *next = pending_head->next;
        HeapFree(GetProcessHeap(), 0, pending_head);
        pending_head = next;
    }
    pending_tail = NULL;
    LeaveCriticalSection(&listeners_lock);
    if (SUCCEEDED(hr)) CoUninitialize();
    if (self_pin) FreeLibraryAndExitThread(self_pin, 0);
    return 0;
}

EXPORT int RegisterPostMessageHook(HWND hwnd, UINT message) {
    if (!hwnd || !IsWindow(hwnd) || !message ||
        !InitOnceExecuteOnce(&once, init_state, NULL, NULL)) return -1;
    EnterCriticalSection(&listeners_lock);
    if (stopping) { LeaveCriticalSection(&listeners_lock); return -1; }
    for (size_t i = 0; i < listener_count; i++) {
        if (listeners[i].hwnd == hwnd) {
            listeners[i].message = message;
            LeaveCriticalSection(&listeners_lock);
            return 1;
        }
    }
    if (listener_count == listener_capacity) {
        size_t capacity = listener_capacity ? listener_capacity * 2 : 4;
        Listener *next = listener_capacity
            ? HeapReAlloc(GetProcessHeap(), 0, listeners, capacity * sizeof *next)
            : HeapAlloc(GetProcessHeap(), 0, capacity * sizeof *next);
        if (!next) { LeaveCriticalSection(&listeners_lock); return -1; }
        listeners = next;
        listener_capacity = capacity;
    }
    listeners[listener_count++] = (Listener){hwnd, message};
    if (!thread) {
        ResetEvent(stop_event);
        ResetEvent(ready_event);
        thread = CreateThread(NULL, 0, notification_thread, NULL, 0, NULL);
        if (!thread) { listener_count--; LeaveCriticalSection(&listeners_lock); return -1; }
    }
    LeaveCriticalSection(&listeners_lock);
    if (WaitForSingleObject(ready_event, 5000) != WAIT_OBJECT_0 || !ready_status) {
        UnregisterPostMessageHook(hwnd);
        return -1;
    }
    return 1;
}

EXPORT void UnregisterPostMessageHook(HWND hwnd) {
    if (!InitOnceExecuteOnce(&once, init_state, NULL, NULL)) return;
    EnterCriticalSection(&listeners_lock);
    for (size_t i = 0; i < listener_count; i++) {
        if (listeners[i].hwnd == hwnd) {
            memmove(&listeners[i], &listeners[i + 1],
                (listener_count - i - 1) * sizeof *listeners);
            listener_count--;
            break;
        }
    }
    if (listener_count || !thread || stopping) { LeaveCriticalSection(&listeners_lock); return; }
    stopping = 1;
    HANDLE handle = thread;
    SetEvent(stop_event);
    LeaveCriticalSection(&listeners_lock);
    WaitForSingleObject(handle, INFINITE); /* Never hold listeners_lock while joining. */
    EnterCriticalSection(&listeners_lock);
    CloseHandle(handle);
    thread = NULL;
    stopping = 0;
    LeaveCriticalSection(&listeners_lock);
}
