/* Windows 11 24H2 VirtualDesktopAccessor-compatible exports.
 * Interface IDs and vtable ordering adapted from Ciantic/VirtualDesktopAccessor
 * (c) 2015-2023 Jari Otto Oskari Pennanen, MIT; see LICENSE.txt.
 * These interfaces are undocumented and can change across Windows builds.
 */
#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_internal = {0xc5e0cdca,0x7b6e,0x41b2,{0x9f,0xc4,0xd9,0x39,0x75,0xcc,0x46,0x7b}};
static const GUID cls_pinned = {0xb5a399e7,0x1c87,0x46b8,{0x88,0xe9,0xfc,0x57,0x47,0xb1,0x71,0xbd}};
static const GUID iid_pinned = {0x4ce81583,0x1e4c,0x4632,{0xa6,0x21,0x07,0xa5,0x35,0x43,0x14,0x8f}};
static const GUID iid_internal = {0x53f5ca0b,0x158f,0x4124,{0x90,0x0c,0x05,0x71,0x58,0x06,0x0b,0x27}};
static const GUID iid_manager = {0xa5cd92ff,0x29be,0x454c,{0x8d,0x04,0xd8,0x28,0x79,0xfb,0x3f,0x1b}};
static const GUID iid_views = {0x1841c6d7,0x4f9d,0x42c0,{0xaf,0x41,0x87,0x47,0x53,0x8f,0x10,0xe5}};
static const GUID iid_desktop = {0x3f07f4be,0xb107,0x441a,{0xaf,0x0f,0x39,0xd8,0x25,0x29,0x07,0x2c}};

/* Each call uses its calling thread's COM apartment; pointers never cross threads. */
typedef struct {
    void *provider, *internal, *manager, *views, *pinned;
    int initialized;
} Services;

static int open_services(Services *s, int need_manager, int need_views, int need_pinned) {
    memset(s, 0, sizeof *s);
    HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
    if (FAILED(hr) && hr != RPC_E_CHANGED_MODE) return 0;
    s->initialized = SUCCEEDED(hr);
    hr = CoCreateInstance(&cls_shell, NULL, CLSCTX_LOCAL_SERVER, &iid_service, &s->provider);
    if (FAILED(hr) || !s->provider) return 0;
    HRESULT (STDMETHODCALLTYPE *query)(void *, const GUID *, const GUID *, void **) =
        SLOT(s->provider, 3, HRESULT (STDMETHODCALLTYPE *)(void *, const GUID *, const GUID *, void **));
    hr = query(s->provider, &cls_internal, &iid_internal, &s->internal);
    if (FAILED(hr) || !s->internal) return 0;
    if (need_manager) {
        hr = query(s->provider, &iid_manager, &iid_manager, &s->manager);
        if (FAILED(hr) || !s->manager) return 0;
    }
    if (need_views) {
        hr = query(s->provider, &iid_views, &iid_views, &s->views);
        if (FAILED(hr) || !s->views) return 0;
    }
    if (need_pinned) {
        hr = query(s->provider, &cls_pinned, &iid_pinned, &s->pinned);
        if (FAILED(hr) || !s->pinned) return 0;
    }
    return 1;
}

static void close_services(Services *s) {
    RELEASE(s->pinned);
    RELEASE(s->views);
    RELEASE(s->manager);
    RELEASE(s->internal);
    RELEASE(s->provider);
    if (s->initialized) CoUninitialize();
}

/* IObjectArray::GetCount / GetAt and IVirtualDesktop::GetID. */
static void *desktop_at(void *internal, int index) {
    if (index < 0) return NULL;
    void *array = NULL, *desktop = NULL;
    HRESULT hr = SLOT(internal, 7, HRESULT (STDMETHODCALLTYPE *)(void *, void **))(internal, &array);
    if (FAILED(hr) || !array) return NULL;
    UINT count = 0;
    hr = SLOT(array, 3, HRESULT (STDMETHODCALLTYPE *)(void *, UINT *))(array, &count);
    if (SUCCEEDED(hr) && (UINT)index < count)
        hr = SLOT(array, 4, HRESULT (STDMETHODCALLTYPE *)(void *, UINT, const GUID *, void **))
            (array, (UINT)index, &iid_desktop, &desktop);
    RELEASE(array);
    if (FAILED(hr)) { RELEASE(desktop); return NULL; }
    return desktop;
}

static int index_of(void *internal, const GUID *id) {
    void *array = NULL;
    HRESULT hr = SLOT(internal, 7, HRESULT (STDMETHODCALLTYPE *)(void *, void **))(internal, &array);
    if (FAILED(hr) || !array) return -1;
    UINT count = 0;
    hr = SLOT(array, 3, HRESULT (STDMETHODCALLTYPE *)(void *, UINT *))(array, &count);
    int found = -1;
    for (UINT i = 0; SUCCEEDED(hr) && i < count; i++) {
        void *desktop = NULL;
        hr = SLOT(array, 4, HRESULT (STDMETHODCALLTYPE *)(void *, UINT, const GUID *, void **))
            (array, i, &iid_desktop, &desktop);
        if (FAILED(hr) || !desktop) { RELEASE(desktop); break; }
        GUID candidate = {0};
        hr = SLOT(desktop, 4, HRESULT (STDMETHODCALLTYPE *)(void *, GUID *))(desktop, &candidate);
        RELEASE(desktop);
        if (SUCCEEDED(hr) && IsEqualGUID(&candidate, id)) { found = (int)i; break; }
    }
    RELEASE(array);
    return found;
}

EXPORT int GetDesktopCount(void) {
    Services s;
    int result = -1;
    if (open_services(&s, 0, 0, 0)) {
        UINT count = 0;
        if (SUCCEEDED(SLOT(s.internal, 3, HRESULT (STDMETHODCALLTYPE *)(void *, UINT *))
            (s.internal, &count))) result = (int)count;
    }
    close_services(&s);
    return result;
}

EXPORT int GetCurrentDesktopNumber(void) {
    Services s;
    int result = -1;
    if (open_services(&s, 0, 0, 0)) {
        void *desktop = NULL;
        HRESULT hr = SLOT(s.internal, 6, HRESULT (STDMETHODCALLTYPE *)(void *, void **))
            (s.internal, &desktop);
        if (SUCCEEDED(hr) && desktop) {
            GUID id = {0};
            if (SUCCEEDED(SLOT(desktop, 4, HRESULT (STDMETHODCALLTYPE *)(void *, GUID *))
                (desktop, &id))) result = index_of(s.internal, &id);
        }
        RELEASE(desktop);
    }
    close_services(&s);
    return result;
}

EXPORT int GetWindowDesktopNumber(HWND hwnd) {
    if (!hwnd) return -1;
    Services s;
    int result = -1;
    if (open_services(&s, 1, 0, 0)) {
        GUID id = {0};
        if (SUCCEEDED(SLOT(s.manager, 4, HRESULT (STDMETHODCALLTYPE *)(void *, HWND, GUID *))
            (s.manager, hwnd, &id))) result = index_of(s.internal, &id);
    } else if (!hwnd) return -1;
    close_services(&s);
    return result;
}

EXPORT int IsWindowOnCurrentVirtualDesktop(HWND hwnd) {
    Services s;
    int result = -1;
    if (hwnd && open_services(&s, 1, 0, 0)) {
        BOOL current = FALSE;
        if (SUCCEEDED(SLOT(s.manager, 3, HRESULT (STDMETHODCALLTYPE *)(void *, HWND, BOOL *))
            (s.manager, hwnd, &current))) result = !!current;
    } else if (!hwnd) return -1;
    close_services(&s);
    return result;
}

EXPORT int GoToDesktopNumber(int index) {
    Services s;
    int result = -1;
    if (index < 0) return -1;
    if (open_services(&s, 0, 0, 0)) {
        void *desktop = desktop_at(s.internal, index);
        if (desktop) {
            if (SUCCEEDED(SLOT(s.internal, 9, HRESULT (STDMETHODCALLTYPE *)(void *, void *))
                (s.internal, desktop))) result = 1;
            RELEASE(desktop);
        }
    }
    close_services(&s);
    return result;
}

EXPORT int MoveWindowToDesktopNumber(HWND hwnd, int index) {
    Services s;
    int result = -1;
    if (!hwnd || index < 0) return -1;
    if (open_services(&s, 0, 1, 0)) {
        void *desktop = desktop_at(s.internal, index), *view = NULL;
        if (desktop && SUCCEEDED(SLOT(s.views, 6, HRESULT (STDMETHODCALLTYPE *)(void *, HWND, void **))
            (s.views, hwnd, &view)) && view) {
            if (SUCCEEDED(SLOT(s.internal, 4, HRESULT (STDMETHODCALLTYPE *)(void *, void *, void *))
                (s.internal, view, desktop))) result = 1;
        }
        RELEASE(view);
        RELEASE(desktop);
    }
    close_services(&s);
    return result;
}

/* Additional VirtualDesktopAccessor exports. Out COM objects are owned here. */
EXPORT GUID GetDesktopIdByNumber(int index) {
    GUID id = {0};
    Services s;
    if (open_services(&s, 0, 0, 0)) {
        void *desktop = desktop_at(s.internal, index);
        if (desktop) {
            if (FAILED(SLOT(desktop, 4, HRESULT (STDMETHODCALLTYPE *)(void *, GUID *))
                (desktop, &id))) memset(&id, 0, sizeof id);
            RELEASE(desktop);
        }
    }
    close_services(&s);
    return id;
}

EXPORT int GetDesktopNumberById(GUID id) {
    Services s;
    int result = -1;
    if (open_services(&s, 0, 0, 0)) result = index_of(s.internal, &id);
    close_services(&s);
    return result;
}

EXPORT GUID GetWindowDesktopId(HWND hwnd) {
    GUID id = {0};
    if (!hwnd) return id;
    Services s;
    if (open_services(&s, 1, 0, 0)) {
        if (FAILED(SLOT(s.manager, 4, HRESULT (STDMETHODCALLTYPE *)(void *, HWND, GUID *))
            (s.manager, hwnd, &id))) memset(&id, 0, sizeof id);
    }
    close_services(&s);
    return id;
}

EXPORT int IsWindowOnDesktopNumber(HWND hwnd, int index) {
    if (!hwnd || index < 0 || index >= GetDesktopCount()) return -1;
    int current = GetWindowDesktopNumber(hwnd);
    return current < 0 ? -1 : current == index;
}

/* Win32 already defines CreateDesktopA/W; export that DLL ABI name separately. */
#pragma comment(linker, "/EXPORT:CreateDesktop=VDACreateDesktop")
EXPORT int VDACreateDesktop(void) {
    Services s;
    int result = -1;
    if (open_services(&s, 0, 0, 0)) {
        void *desktop = NULL;
        HRESULT hr = SLOT(s.internal, 11, HRESULT (STDMETHODCALLTYPE *)(void *, void **))
            (s.internal, &desktop);
        if (SUCCEEDED(hr) && desktop) {
            GUID id = {0};
            if (SUCCEEDED(SLOT(desktop, 4, HRESULT (STDMETHODCALLTYPE *)(void *, GUID *))
                (desktop, &id))) result = index_of(s.internal, &id);
        }
        RELEASE(desktop);
    }
    close_services(&s);
    return result;
}

EXPORT int RemoveDesktop(int index, int fallback_index) {
    Services s;
    int result = -1;
    if (index < 0 || fallback_index < 0 || index == fallback_index) return -1;
    if (open_services(&s, 0, 0, 0)) {
        void *desktop = desktop_at(s.internal, index);
        void *fallback = desktop_at(s.internal, fallback_index);
        if (desktop && fallback && SUCCEEDED(SLOT(s.internal, 13,
            HRESULT (STDMETHODCALLTYPE *)(void *, void *, void *))
            (s.internal, desktop, fallback))) result = 1;
        RELEASE(desktop);
        RELEASE(fallback);
    }
    close_services(&s);
    return result;
}

EXPORT int MoveDesktop(int index, int target) {
    Services s;
    int result = -1;
    if (index < 0 || target < 0 || target >= GetDesktopCount()) return -1;
    if (open_services(&s, 0, 0, 0)) {
        void *desktop = desktop_at(s.internal, index);
        if (desktop && SUCCEEDED(SLOT(s.internal, 12,
            HRESULT (STDMETHODCALLTYPE *)(void *, void *, UINT))
            (s.internal, desktop, (UINT)target))) result = 1;
        RELEASE(desktop);
    }
    close_services(&s);
    return result;
}

EXPORT int SetDesktopName(int index, const char *utf8) {
    if (!utf8) return -1;
    int length = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8, -1, NULL, 0);
    if (length <= 0) return -1;
    WCHAR *wide = HeapAlloc(GetProcessHeap(), 0, (size_t)length * sizeof *wide);
    if (!wide) return -1;
    int result = -1;
    if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8, -1, wide, length) > 0) {
        HSTRING name = NULL;
        if (SUCCEEDED(WindowsCreateString(wide, (UINT32)length - 1, &name))) {
            Services s;
            if (open_services(&s, 0, 0, 0)) {
                void *desktop = desktop_at(s.internal, index);
                if (desktop && SUCCEEDED(SLOT(s.internal, 16,
                    HRESULT (STDMETHODCALLTYPE *)(void *, void *, HSTRING))
                    (s.internal, desktop, name))) result = 1;
                RELEASE(desktop);
            }
            close_services(&s);
            WindowsDeleteString(name);
        }
    }
    HeapFree(GetProcessHeap(), 0, wide);
    return result;
}

EXPORT int GetDesktopName(int index, char *utf8, size_t capacity) {
    if (!utf8 || !capacity) return -1;
    Services s;
    int result = 0;
    if (open_services(&s, 0, 0, 0)) {
        void *desktop = desktop_at(s.internal, index);
        if (desktop) {
            HSTRING name = NULL;
            if (SUCCEEDED(SLOT(desktop, 5,
                HRESULT (STDMETHODCALLTYPE *)(void *, HSTRING *))
                (desktop, &name))) {
                UINT32 len = 0;
                const WCHAR *wide = WindowsGetStringRawBuffer(name, &len);
                int bytes = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS,
                    wide, (int)len, NULL, 0, NULL, NULL);
                if ((len == 0 || bytes > 0) && (size_t)bytes + 1 <= capacity &&
                    WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS,
                        wide, (int)len, utf8, bytes, NULL, NULL) == bytes) {
                    utf8[bytes] = '\0';
                    result = 1;
                } else result = -1;
            }
            WindowsDeleteString(name);
            RELEASE(desktop);
        }
    }
    close_services(&s);
    return result;
}

static void *view_for_hwnd(Services *s, HWND hwnd) {
    void *view = NULL;
    if (!hwnd || FAILED(SLOT(s->views, 6,
        HRESULT (STDMETHODCALLTYPE *)(void *, HWND, void **))
        (s->views, hwnd, &view))) { RELEASE(view); return NULL; }
    return view;
}

static int pin_window_action(HWND hwnd, int slot, int query) {
    if (!hwnd) return -1;
    Services s;
    int result = -1;
    if (open_services(&s, 0, 1, 1)) {
        void *view = view_for_hwnd(&s, hwnd);
        if (view) {
            unsigned char pinned = 0; /* Upstream IVirtualDesktopPinnedApps uses bool*. */
            HRESULT hr = query
                ? SLOT(s.pinned, slot, HRESULT (STDMETHODCALLTYPE *)(void *, void *, unsigned char *))
                    (s.pinned, view, &pinned)
                : SLOT(s.pinned, slot, HRESULT (STDMETHODCALLTYPE *)(void *, void *))
                    (s.pinned, view);
            if (SUCCEEDED(hr)) result = query ? !!pinned : 1;
            RELEASE(view);
        }
    }
    close_services(&s);
    return result;
}

EXPORT int IsPinnedWindow(HWND hwnd) { return pin_window_action(hwnd, 6, 1); }
EXPORT int PinWindow(HWND hwnd) { return pin_window_action(hwnd, 7, 0); }
EXPORT int UnPinWindow(HWND hwnd) { return pin_window_action(hwnd, 8, 0); }

static int pin_app_action(HWND hwnd, int slot, int query) {
    if (!hwnd) return -1;
    Services s;
    int result = -1;
    if (open_services(&s, 0, 1, 1)) {
        void *view = view_for_hwnd(&s, hwnd);
        if (view) {
            WCHAR *app_id = NULL;
            if (SUCCEEDED(SLOT(view, 17,
                HRESULT (STDMETHODCALLTYPE *)(void *, WCHAR **))
                (view, &app_id)) && app_id) {
                unsigned char pinned = 0;
                HRESULT hr = query
                    ? SLOT(s.pinned, slot, HRESULT (STDMETHODCALLTYPE *)(void *, WCHAR *, unsigned char *))
                        (s.pinned, app_id, &pinned)
                    : SLOT(s.pinned, slot, HRESULT (STDMETHODCALLTYPE *)(void *, WCHAR *))
                        (s.pinned, app_id);
                if (SUCCEEDED(hr)) result = query ? !!pinned : 1;
            }
            CoTaskMemFree(app_id);
            RELEASE(view);
        }
    }
    close_services(&s);
    return result;
}

EXPORT int IsPinnedApp(HWND hwnd) { return pin_app_action(hwnd, 3, 1); }
EXPORT int PinApp(HWND hwnd) { return pin_app_action(hwnd, 4, 0); }
EXPORT int UnPinApp(HWND hwnd) { return pin_app_action(hwnd, 5, 0); }

/* No proxies are cached, so there is nothing to reset after Explorer restarts. */
EXPORT void RestartVirtualDesktopAccessor(void) {}
