commit 7149f7bc4d0d14e07821a0b73ce451fa7fc4688b
parent 3f611e89a92b4e763822a4c76c824cb39878dd20
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Sun, 18 Oct 2026 19:32:10 +0530
parent 3f611e89a92b4e763822a4c76c824cb39878dd20
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Sun, 18 Oct 2026 19:32:10 +0530
Build dwhkd with a C virtual desktop plugin
36 files changed, 1636 insertions(+), 547 deletions(-)
A
|
410
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
251
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
89
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
139
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
diff --git a/.gitattributes b/.gitattributes @@ -0,0 +1 @@ +plugins/vd/plugin.dll -text
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml @@ -1,66 +0,0 @@ -name: Build -on: - workflow_dispatch: -permissions: - contents: write -jobs: - Windows: - runs-on: windows-latest - defaults: - run: - shell: msys2 {0} - steps: - - name: Install dependencies - uses: msys2/setup-msys2@v2 - with: - msystem: MINGW64 - update: true - install: >- - mingw-w64-x86_64-toolchain - mingw-w64-x86_64-gcc - mingw-w64-x86_64-binutils - - name: Checkout - uses: actions/checkout@v2 - with: - submodules: true - - - name: Build - run : | - gcc main.c -mwindows -o main - mkdir release - cp main.exe release - cp VirtualDesktopAccessor.dll release - - name: Publish artifacts - uses: actions/upload-artifact@v2 - with: - name: release-windows - path: | - release/main.exe - release/VirtualDesktopAccessor.dll - Release: - needs: [Windows] - runs-on: ubuntu-latest - strategy: - matrix: - build: [windows] - - steps: - - name: Checkout - uses: actions/checkout@v2 - - - uses: actions/download-artifact@v2 - - name: Zip artifacts - run: | - zip -r release-${{matrix.build}}.zip release-${{matrix.build}} - - name: Create release - uses: softprops/action-gh-release@v1 - with: - files: | - release-${{matrix.build}}.zip - body: | - Dispatch Build of sxhkd-win32. - prerelease: true - tag_name: 1.0.3 - name: Release 1.0.3 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
diff --git a/.gitignore b/.gitignore @@ -1,5 +1,4 @@ /.vscode -a.exe -main.o -sxhkd-win32.exe +/build/ *.exe +/plugins/smoke/plugin.dll
diff --git a/Makefile b/Makefile @@ -1,22 +1,64 @@ -DEBUG = -DDEBUG -CFLAGS = -w -Wall -Os ${DEBUG} -LDFLAGS = -s -mwindows -CC = gcc +# Run with busybox make from an x64 Visual Studio Developer Command Prompt. +CC = cl +CFLAGS = /nologo /std:c11 /O2 /W3 /D_CRT_SECURE_NO_WARNINGS -SRC = main.c -OBJ = ${SRC:.c=.o} +all: dwhkd.exe plugins/vd/plugin.dll -all: options sxhkd-win32 +build/.ready: + busybox mkdir -p build + busybox touch build/.ready -options: - @echo sxhkd-win32 build options: - @echo "CFLAGS = ${CFLAGS}" - @echo "LDFLAGS = ${LDFLAGS}" - @echo "CC = ${CC}" +build/main.obj: main.c config.c actions.c actions.h debug.h plugin.h build/.ready + $(CC) $(CFLAGS) /c /Fo:build/main.obj main.c -sxhkd-win32: ${OBJ} - @echo "${CC} -o $@" - @${CC} -o $@ ${OBJ} ${LDFLAGS} +dwhkd.exe: build/main.obj + link.exe /nologo /SUBSYSTEM:WINDOWS /OUT:$@ build/main.obj user32.lib shell32.lib + +build/vda.obj: libs/virtualdesktopaccessor/VirtualDesktopAccessor.c libs/virtualdesktopaccessor/virtualdesktopaccessor.h build/.ready + $(CC) $(CFLAGS) /c /Fo:build/vda.obj libs/virtualdesktopaccessor/VirtualDesktopAccessor.c + +build/notifications.obj: libs/virtualdesktopaccessor/notifications.c libs/virtualdesktopaccessor/virtualdesktopaccessor.h build/.ready + $(CC) $(CFLAGS) /c /Fo:build/notifications.obj libs/virtualdesktopaccessor/notifications.c + +build/vd_plugin.obj: plugins/vd/plugin.c plugin.h libs/virtualdesktopaccessor/virtualdesktopaccessor.h build/.ready + $(CC) $(CFLAGS) /c /Fo:build/vd_plugin.obj plugins/vd/plugin.c + +plugins/vd/plugin.dll: build/vda.obj build/notifications.obj build/vd_plugin.obj + link.exe /nologo /DLL /OUT:$@ /IMPLIB:build/vd.lib build/vda.obj build/notifications.obj build/vd_plugin.obj ole32.lib runtimeobject.lib user32.lib + +build/config_test.obj: tests/config_test.c config.c build/.ready + $(CC) $(CFLAGS) /c /Fo:build/config_test.obj tests/config_test.c + +build/config_test.exe: build/config_test.obj + link.exe /nologo /OUT:$@ build/config_test.obj user32.lib + +build/smoke_plugin.obj: tests/plugin_smoke.c plugin.h build/.ready + $(CC) $(CFLAGS) /DBUILD_PLUGIN /c /Fo:build/smoke_plugin.obj tests/plugin_smoke.c + +plugins/smoke/plugin.dll: build/smoke_plugin.obj + busybox mkdir -p plugins/smoke + link.exe /nologo /DLL /OUT:$@ /IMPLIB:build/smoke.lib build/smoke_plugin.obj user32.lib + +build/plugin_smoke.obj: tests/plugin_smoke.c plugin.h build/.ready + $(CC) $(CFLAGS) /c /Fo:build/plugin_smoke.obj tests/plugin_smoke.c + +build/plugin_smoke.exe: build/plugin_smoke.obj + link.exe /nologo /OUT:$@ build/plugin_smoke.obj user32.lib + +test: all build/config_test.exe plugins/smoke/plugin.dll build/plugin_smoke.exe + build/config_test.exe + build/plugin_smoke.exe + +build/vd_smoke.obj: tests/vd_smoke.c libs/virtualdesktopaccessor/virtualdesktopaccessor.h build/.ready + $(CC) $(CFLAGS) /c /Fo:build/vd_smoke.obj tests/vd_smoke.c + +plugins/vd/smoke.exe: build/vd_smoke.obj + link.exe /nologo /OUT:$@ build/vd_smoke.obj user32.lib + +test-vd: all plugins/vd/smoke.exe + busybox sh -c 'cd plugins/vd && ./smoke.exe' clean: - rm -f ${OBJ} sxhkd-win32 + busybox rm -rf build dwhkd.exe plugins/vd/smoke.exe plugins/smoke/plugin.dll + +.PHONY: all test test-vd clean
diff --git a/README.md b/README.md @@ -1,81 +1,42 @@ -# sxhkd-win32 -Sxhkd impl for Windows with Optional UNIX like workspace support through Native VirtualDesktops! - -# Instructions -- Local Enviornment Method - - Edit config.h and actions.h according to what you want - - Build using `make all` or `make` - - Copy the produced `sxhkd-win32.exe` to your location of choice - - Run `make clean` in the working directory to clean it -- Github Actions Method (Easier) - - Fork the repository - - Change config.h or any other code as you want - - Go to actions tab and dispatch the build workflow - - Download the built exe and dll from releases, Enjoy! - -# Virtual Desktop Features -- Please see [VD-Action.md](./VD-action.md). -- Note that the VirtualDesktopAccessor DLL used right now is broken on some newer builds of Windows, if other hotkeys are working, then you might wanna download the latest release of VirtualDesktopAccessor.dll from [here](https://github.com/Ciantic/VirtualDesktopAccessor). -- The optimal way of using VDA with sxhkd is after setting the taskbar as hidden and toggling explorer by Alt+E (see config), this prevents any weird flickering behaviour that the taskbar has when VDs are switched too fast -- PS: You can use Bing Wallpaper and set on every VD for a truly awesome VD experience! - -# Sample config.h - -```c -#define MODKEY (MOD_ALT) -// options: MOD_WIN | MOD_CTRL | MOD_SHIFT | MOD_ALT -// can be combined by binary OR operator - -// Use MODKEY | MOD_SHIFT for mod + shift -// VK_RETURN == RETURN KEY on Keyboard -// VK_TAB == TAB KEY on Keyboard - -// command, argument -static const char *termcmd[] = {NULL, "wt.exe", NULL }; -static const char *adminCmd[] = {"runas", "wt.exe", NULL}; -static const char *vscode[] = {NULL, "code", "D:/code"}; -static const char *codeforces[] = {"open", "https://codeforces.com", NULL}; -static const char *leetcode[] = {"open", "https://leetcode.com", NULL}; -static const char *explorer[] = {NULL, "explorer.exe", NULL}; -static const char *taskManager[] = {NULL, "Taskmgr.exe", NULL}; -static const char *adbConnect[] = {NULL, "D:/win32/ADB-Connect/adb-tcpip-connect.exe", NULL}; -static const char *scrcpy[] = {NULL, "D:/win32/ADB-Connect/launch-scrcpy.vbs", NULL}; - -#define NUMKEY(x) \ - {MODKEY, x+'0', GoToDesktopNumberW, {.i= x ? x : 10}}, \ - {MODKEY|MOD_SHIFT, x+'0', MoveWindowToDesktopNumberW, {.i= x ? x : 10}} - -static Key keys[] = { - /* modifier key function argument */ - { MODKEY, 'B', test, {0} }, - { MODKEY, 'O', spawn, {.v = vscode} }, - { MODKEY, VK_RETURN, spawn, {.v = termcmd } }, - { MODKEY | MOD_SHIFT, VK_RETURN, spawn, {.v = adminCmd } }, - { MODKEY, 'C', spawn, {.v = codeforces } }, - { MODKEY, 'L', spawn, {.v = leetcode } }, - { MODKEY | MOD_SHIFT, 'E', toggleexplorer, {0} }, - { MODKEY, 'Q', killForeground, {0} }, - { MODKEY | MOD_SHIFT, 'Q', killMacForeground, {0} }, - { MODKEY, 'E', spawn, {.v = explorer}}, - { MODKEY | MOD_SHIFT, 'Q', quit, {0} }, - { MODKEY, 'T', spawn, {.v = taskManager } }, - { MODKEY, 'D', spawn, {.v = adbConnect } }, - { MODKEY, 'F', spawn, {.v = scrcpy } }, - #ifdef VDA_FEATURES - NUMKEY(1), - NUMKEY(2), - NUMKEY(3), - NUMKEY(4), - NUMKEY(5), - NUMKEY(6), - NUMKEY(7), - NUMKEY(8), - NUMKEY(9), - NUMKEY(0), - #endif -}; +# dwhkd + +A general-purpose Windows hotkey daemon forked from [theSoberSobber/sxhkd-win32](https://github.com/theSoberSobber/sxhkd-win32). It keeps the original `RegisterHotKey`/`WM_HOTKEY` approach, but uses a config file instead of compiled-in bindings. No hotkeys are built in; the original desktop actions are available as optional config commands. + +## Configure and build + +From an **x64 Visual Studio Developer Command Prompt**, build with `busybox make` (requires [BusyBox for Windows](https://frippery.org/busybox/) on `PATH`). This invokes MSVC `cl.exe` and `link.exe`; no MSYS, Cygwin, MinGW, or Rust is needed. Run `busybox make test` for parser/plugin checks, and `busybox make test-vd` for live virtual-desktop COM checks on a supported Windows 11 desktop. Copy [dwhkdrc.example](dwhkdrc.example) to `%APPDATA%\dwhkd\dwhkdrc` (create the directory), or run `dwhkd.exe -c C:\path\to\dwhkdrc`. A valid config is required; restart after edits. + +The format is inspired by [baskerville/shkd](https://github.com/baskerville/shkd): a hotkey line followed by one or more indented plugin, built-in, or Windows `cmd.exe /C` commands. Commands run in order; a nonzero result stops the remaining commands. Separate case-insensitive names with spaces or `+`; `#` lines are comments. The last definition of a hotkey wins. Supported modifiers: `alt`, `ctrl`/`control`, `shift`, `meta`/`super`/`win`. Supported keys: letters, digits, F1–F24, `return`/`enter`, `tab`, `space`, `escape`, `backspace`, `delete`, `insert`, `home`, `end`, `pageup`, `pagedown`, arrows, `printscreen`, `pause`, named punctuation (`minus`, `equal`, `comma`, `period`, `slash`, `semicolon`, `apostrophe`, `backslash`, `bracketleft`, `bracketright`, `grave`), and `=N` (Windows virtual-key code 1–255, **not** a Linux keycode). + +Built-in actions: `:toggle-explorer`, `:close-window`, `:force-close-window`, `:quit`, and the debug-only `:test`. Virtual-desktop actions live in the [C plugin](plugins/vd/README.md): `:vd goto-desktop N`, `:vd move-to-desktop N`, `:vd pin-app`, `:vd unpin-app`, and `:vd app-pin-status`. A [manual test config](dwhkdrc.manual) binds app pinning and desktop switching for live checks. Desktop numbers are 1–10 (`0` also means 10). `busybox make` builds `plugins/vd/plugin.dll`; when distributing it, include the original [MIT notice](libs/virtualdesktopaccessor/LICENSE.txt). + +## Plugins + +A config command `:name action arguments` loads `plugins/name/plugin.dll` next to the executable. The host loads each **referenced** DLL once at startup, checks `sxhkd_plugin_abi()` against version 1, then calls `sxhkd_plugin_invoke(const char *action, const char *arguments)` on each matching hotkey. The function returns **0 on success**, nonzero on failure. The plugin parses the text arguments and obtains runtime values (such as `GetForegroundWindow()`) itself. It can export any action names it chooses: **adding actions or plugins does not require recompiling the host**. See [`plugin.h`](plugin.h) and the [working test plugin](tests/plugin_smoke.c) (`BUILD_PLUGIN` branch) for the C ABI: export `int sxhkd_plugin_abi(void)` returning `SXHKD_PLUGIN_ABI`, and `int sxhkd_plugin_invoke(const char *, const char *)`. Build your DLL as `plugins/<name>/plugin.dll`; no host rebuild is needed. The `sxhkd_plugin_*` export names remain unchanged for plugin ABI compatibility despite the project rename. Plugin names and action names are single whitespace-delimited tokens containing only letters, digits, hyphens, and underscores; the remaining argument text may contain spaces. No paths or arbitrary DLLs are accepted. A missing or incompatible referenced plugin stops startup; only load DLLs you trust. The host still owns the few built-in actions listed above. + +### Notes for plugin authors + +Return **0 for success**, nonzero for failure. A hotkey can list multiple indented commands; the host calls each in order and stops when one fails. Plugin actions should perform their work **without hardcoded message boxes, toasts, or notifications**. Users decide whether and how to show feedback by adding their own notification command after the action: + +```text +ctrl + alt + shift + f7 + :vd pin-app + your-notifier.exe "App pinned" +``` + +The notifier runs only if `pin-app` returns 0. Shell commands are launched asynchronously, so only launch success—not the shell command's eventual exit code—controls the next step. `:vd app-pin-status` returns 0 when the foreground app is pinned and nonzero otherwise; it does not show UI. The [manual test config](dwhkdrc.manual) leaves feedback to you. + +### Compared with AutoHotkey `DllCall` + +Both can run native DLL code **in-process**, without launching an executable for each hotkey. Their formats are **not the same**: + +```text +AutoHotkey: DllCall("plugin.dll\MoveWindowToDesktopNumber", "Ptr", hwnd, "Int", 1, "Int") +This config: :vd move-to-desktop 2 ``` -# TODO -- Installer (or start menu + program files) -- Scheduler +AutoHotkey names a DLL export and supplies typed argument/value pairs (here an `HWND` pointer and a zero-based desktop index). Our Vim-like `:` means **dispatch a managed command instead of a shell command**: `vd` selects a plugin loaded once at startup, `move-to-desktop` is the plugin's action name, and `2` is passed as text. The plugin obtains the live `HWND`, converts the user-facing number to a zero-based index, and makes the typed call in C. `:` does **not** call an arbitrary DLL export or specify argument types; it is only syntax for selecting a built-in or plugin action. Plugins are native code, **not sandboxed**—the prefix does not make an untrusted DLL safe. See [AutoHotkey's DllCall documentation](https://www.autohotkey.com/docs/v2/lib/DllCall.htm). + +shkd's `release` bindings, modes, Linux-only keys, and live reload are not supported. Windows cannot register a shortcut already claimed by another application; registration errors go to stderr. Commands run as your user, so only use config files you trust. + +The Windows message-window approach comes from the original sxhkd-win32. [`config.c`](config.c) is an independent Windows parser inspired by [shkd by Bastien Dejean](https://github.com/baskerville/shkd) (© 2012); **no shkd source code is vendored**. The original sxhkd-win32 has no license file: obtain permission before redistributing this fork. The adapted C library keeps the original author's [MIT license and notice](libs/virtualdesktopaccessor/LICENSE.txt) in `libs/virtualdesktopaccessor/`.
diff --git a/RunOnStartup.bat b/RunOnStartup.bat @@ -1,47 +0,0 @@ -@echo off - -REM Check if running with administrative privileges -net session >nul 2>&1 -if %errorlevel% neq 0 ( - echo This script requires administrative privileges. Please run this script as an administrator. - pause - exit /b 1 -) - -REM Prompt the user to enter the name of the executable -set /p exeName=Enter the name of the executable (without extension): - -REM Get the absolute path of the directory where this script is located -for %%i in ("%~dp0.") do set "scriptDir=%%~fi" - -REM Create the full path to the executable -set "exePath=%scriptDir%\%exeName%.exe" - -echo User Input Executable Path: %exePath% - -REM Check if the executable exists -if not exist "%exePath%" ( - echo Error: The specified executable does not exist. - pause - exit /b 1 -) - -REM Create the registry entry for startup -set "registryKey=HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run" -set "registryValue=sxhkd-win32" -set "registryData=%scriptDir%\%exeName%.exe" - -echo Adding Registry Key %registryKey%\%registryValue% with value as %registryData% -REM Add the registry entry -reg add "%registryKey%" /v "%registryValue%" /t REG_SZ /d "%registryData%" /f >nul - -REM Check if the registry entry was added successfully -if %errorlevel% neq 0 ( - echo Error: Failed to add the registry entry. - pause - exit /b 1 -) - -echo Startup entry added successfully. -pause -exit /b- \ No newline at end of file
diff --git a/VD-action.md b/VD-action.md @@ -1,9 +0,0 @@ -# VD-Action -- Native - - https://stackoverflow.com/a/55542867 - - https://github.com/Ciantic/VirtualDesktopAccessor/blob/master/VirtualDesktopAccessor/dllmain.h#L40 - - https://www.codeproject.com/Articles/13601/COM-in-plain-C - - https://learn.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-cocreateinstance - -- [DLL Based](https://github.com/Ciantic/VirtualDesktopAccessor) - - Current Implementationc- \ No newline at end of file
diff --git a/VD/VD.c b/VD/VD.c @@ -1,34 +0,0 @@ -HWND topmost = NULL; - -BOOL CALLBACK CurrVDTopMostFinder(HWND hwnd, LPARAM lParam) { - char windowTitle[256]; - GetWindowTextA(hwnd, windowTitle, sizeof(windowTitle)); - if (IsWindowVisible(hwnd) && IsWindowOnCurrentVirtualDesktopFunc(hwnd) && windowTitle[0] != '\0') { - printf("windowTitle: %s %d\n", windowTitle); - topmost = hwnd; - return FALSE; - } - return TRUE; -} - -HWND GetTopmostWindowOnCurrentVD(){ - topmost=NULL; - EnumWindows(CurrVDTopMostFinder, 0); - return topmost; -} - -void MoveWindowToDesktopNumberW(const Arg* arg){ - printf("%d\n", arg->i - 1); - HWND fgwhwnd = (HWND)GetForegroundWindow(); - MoveWindowToDesktopNumberFunc(fgwhwnd, arg->i - 1); - lastActive[arg->i - 1] = fgwhwnd; - // now who to focus on this desktop? focus NEEDS to shifted right now otherwise movewindow - // can be called again with the same foreground window that isn't even ahead right now - SetForegroundWindow(GetTopmostWindowOnCurrentVD()); -} - -void GoToDesktopNumberW(const Arg* arg){ - lastActive[GetCurrentDesktopFunc()] = GetForegroundWindow(); - GoToDesktopNumberFunc((arg->i - 1 + 10)%10); - SetForegroundWindow(lastActive[(arg->i - 1 + 10)%10]); -}- \ No newline at end of file
diff --git a/VD/VD.h b/VD/VD.h @@ -1,2 +0,0 @@ -static void GoToDesktopNumberW(const Arg* arg); -static void MoveWindowToDesktopNumberW(const Arg* arg);- \ No newline at end of file
diff --git a/VirtualDesktopAccessor.dll b/VirtualDesktopAccessor.dll Binary files differ.
diff --git a/actions.c b/actions.c @@ -35,8 +35,4 @@ void killMacForeground(const Arg* arg) { CloseHandle(hProcess); } -#ifdef VDA_FEATURES -#include "VD/VD.c" -#endif - /* Actions End here */
diff --git a/actions.h b/actions.h @@ -1,12 +1,6 @@ -#define VDA_FEATURES - static void test(const Arg* arg); static void quit(const Arg* arg); static void spawn(const Arg* arg); static void toggleexplorer(const Arg* arg); static void killForeground(const Arg* arg); static void killMacForeground(const Arg* arg); - -#ifdef VDA_FEATURES -#include "VD/VD.h" -#endif- \ No newline at end of file
diff --git a/config.c b/config.c @@ -0,0 +1,216 @@ +/* shkd-style configuration for Windows RegisterHotKey. + * Syntax inspired by https://github.com/baskerville/shkd (Bastien Dejean). + * This is an independent Win32 implementation, not vendored shkd code. + */ +#include <ctype.h> +#include <errno.h> +#include <limits.h> +#include <string.h> + +enum { SHELL_COMMAND, PLUGIN, TOGGLE_EXPLORER, CLOSE_WINDOW, FORCE_CLOSE_WINDOW, QUIT, TEST }; + +typedef struct { + unsigned int mod, key; + char *command; + int action; + char *plugin_name, *plugin_action, *plugin_args; + size_t plugin_index; +} Binding; + +static Binding *bindings; +static size_t binding_count; + +static char *trim(char *s) { + while (isspace((unsigned char)*s)) s++; + char *end = s + strlen(s); + while (end > s && isspace((unsigned char)end[-1])) *--end = '\0'; + return s; +} + +static char *copy_string(const char *s) { + size_t n = strlen(s) + 1; + char *copy = malloc(n); + if (copy) memcpy(copy, s, n); + return copy; +} + +static int same(const char *a, const char *b) { + while (*a && *b && tolower((unsigned char)*a) == tolower((unsigned char)*b)) a++, b++; + return *a == *b; +} + +static unsigned int key_name(const char *name) { + if (name[0] && !name[1]) { + int c = toupper((unsigned char)name[0]); + if ((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) return c; + } + struct { const char *name; unsigned int code; } names[] = { + {"return", VK_RETURN}, {"enter", VK_RETURN}, {"tab", VK_TAB}, + {"space", VK_SPACE}, {"spacebar", VK_SPACE}, {"escape", VK_ESCAPE}, + {"esc", VK_ESCAPE}, {"backspace", VK_BACK}, {"delete", VK_DELETE}, + {"insert", VK_INSERT}, {"home", VK_HOME}, {"end", VK_END}, + {"pageup", VK_PRIOR}, {"pagedown", VK_NEXT}, {"left", VK_LEFT}, + {"right", VK_RIGHT}, {"up", VK_UP}, {"down", VK_DOWN}, + {"printscreen", VK_SNAPSHOT}, {"pause", VK_PAUSE}, + {"minus", VK_OEM_MINUS}, {"equal", VK_OEM_PLUS}, + {"comma", VK_OEM_COMMA}, {"period", VK_OEM_PERIOD}, + {"slash", VK_OEM_2}, {"semicolon", VK_OEM_1}, + {"apostrophe", VK_OEM_7}, {"backslash", VK_OEM_5}, + {"bracketleft", VK_OEM_4}, {"bracketright", VK_OEM_6}, + {"grave", VK_OEM_3} + }; + for (size_t i = 0; i < sizeof names / sizeof names[0]; i++) + if (same(name, names[i].name)) return names[i].code; + if (tolower((unsigned char)name[0]) == 'f' && isdigit((unsigned char)name[1])) { + char *end; + long n = strtol(name + 1, &end, 10); + if (!*end && n >= 1 && n <= 24) return VK_F1 + n - 1; + } + if (name[0] == '=') { + char *end; + long n = strtol(name + 1, &end, 10); + if (end != name + 1 && !*end && n > 0 && n <= 255) return (unsigned int)n; + } + return 0; +} + +static int parse_hotkey(char *line, unsigned int *mod, unsigned int *key) { + *mod = *key = 0; + for (char *token = strtok(line, " +\t\r\n"); token; token = strtok(NULL, " +\t\r\n")) { + if (same(token, "alt")) *mod |= MOD_ALT; + else if (same(token, "ctrl") || same(token, "control")) *mod |= MOD_CONTROL; + else if (same(token, "shift")) *mod |= MOD_SHIFT; + else if (same(token, "meta") || same(token, "super") || same(token, "win")) *mod |= MOD_WIN; + else { + unsigned int code = key_name(token); + if (!code || *key) return 0; + *key = code; + } + } + return *key != 0; +} + +static int plugin_char(unsigned char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || c == '-' || c == '_'; +} + +static int parse_action(const char *command) { + if (command[0] != ':') return SHELL_COMMAND; + if (same(command, ":toggle-explorer")) return TOGGLE_EXPLORER; + if (same(command, ":close-window")) return CLOSE_WINDOW; + if (same(command, ":force-close-window")) return FORCE_CLOSE_WINDOW; + if (same(command, ":quit")) return QUIT; + if (same(command, ":test")) return TEST; + const char *name = command + 1; + const char *space = strpbrk(name, " \t"); + if (!space || space == name || space - name > 63) return -1; + const char *action = space + strspn(space, " \t"); + const char *end = strpbrk(action, " \t"); + if (!end) end = action + strlen(action); + if (end == action || end - action > 63) return -1; + for (const char *p = name; p < space; p++) + if (!plugin_char((unsigned char)*p)) return -1; + for (const char *p = action; p < end; p++) + if (!plugin_char((unsigned char)*p)) return -1; + return PLUGIN; +} + +static void free_bindings(void) { + for (size_t i = 0; i < binding_count; i++) free(bindings[i].command); + free(bindings); + bindings = NULL; + binding_count = 0; +} + +/* Consecutive indented lines for a hotkey run in order. The last definition + * of a hotkey replaces its previous command group. */ +static int load_config(const char *path) { + FILE *file = fopen(path, "r"); + if (!file) { + fprintf(stderr, "dwhkd: cannot open %s: %s\n", path, strerror(errno)); + return 0; + } + char line[8192]; + unsigned int mod = 0, key = 0; + int has_command = 0; + size_t lineno = 0; + int ok = 1; + while (fgets(line, sizeof line, file)) { + lineno++; + if (!strchr(line, '\n') && !feof(file)) { + fprintf(stderr, "%s:%zu: line too long\n", path, lineno); + int c; + while ((c = fgetc(file)) != '\n' && c != EOF) {} + key = 0; has_command = 0; ok = 0; + continue; + } + int indented = isspace((unsigned char)line[0]); + char *value = trim(line); + if (!*value || *value == '#') continue; + if (!indented) { + if (key && !has_command) { + fprintf(stderr, "%s:%zu: hotkey without command\n", path, lineno - 1); + ok = 0; + } + if (!parse_hotkey(value, &mod, &key)) { + fprintf(stderr, "%s:%zu: unsupported hotkey\n", path, lineno); + key = 0; ok = 0; + } + has_command = 0; + } else if (key) { + if (strncmp(value, "->[", 3) == 0) { + fprintf(stderr, "%s:%zu: modes are not supported\n", path, lineno); + key = 0; ok = 0; + continue; + } + int action = parse_action(value); + if (action < 0) { + fprintf(stderr, "%s:%zu: unknown action\n", path, lineno); + key = 0; ok = 0; + continue; + } + if (binding_count >= INT_MAX) { ok = 0; break; } + char *command = copy_string(value); + Binding *next = command ? realloc(bindings, (binding_count + 1) * sizeof *bindings) : NULL; + if (!next) { free(command); ok = 0; break; } + bindings = next; + if (!has_command) { + /* The last hotkey definition replaces its entire earlier group. */ + for (size_t i = 0; i < binding_count;) { + if (bindings[i].key == key && bindings[i].mod == mod) { + free(bindings[i].command); + memmove(&bindings[i], &bindings[i + 1], + (binding_count - i - 1) * sizeof *bindings); + binding_count--; + } else i++; + } + } + Binding binding = {.mod = mod, .key = key, .command = command, .action = action}; + if (action == PLUGIN) { + char *name = command + 1; + char *action_name = strpbrk(name, " \t"); + *action_name++ = '\0'; + while (*action_name == ' ' || *action_name == '\t') action_name++; + char *args = strpbrk(action_name, " \t"); + if (args) { + *args++ = '\0'; + while (*args == ' ' || *args == '\t') args++; + } + binding.plugin_name = name; + binding.plugin_action = action_name; + binding.plugin_args = args ? args : ""; + } + bindings[binding_count++] = binding; + has_command = 1; + } else { + fprintf(stderr, "%s:%zu: command without hotkey\n", path, lineno); + ok = 0; + } + } + if (ferror(file)) ok = 0; + if (key && !has_command) { fprintf(stderr, "%s: hotkey without command\n", path); ok = 0; } + fclose(file); + if (!ok) free_bindings(); + return ok; +}
diff --git a/config.h b/config.h @@ -1,52 +0,0 @@ -#define MODKEY (MOD_ALT) -// options: MOD_WIN | MOD_CTRL | MOD_SHIFT | MOD_ALT -// can be combined by binary OR operator - -// Use MODKEY | MOD_SHIFT for mod + shift -// VK_RETURN == RETURN KEY on Keyboard -// VK_TAB == TAB KEY on Keyboard - -// command, argument -static const char *termcmd[] = {NULL, "wt.exe", NULL }; -static const char *adminCmd[] = {"runas", "wt.exe", NULL}; -static const char *vscode[] = {NULL, "code", "D:/code"}; -static const char *codeforces[] = {"open", "https://codeforces.com", NULL}; -static const char *leetcode[] = {"open", "https://leetcode.com", NULL}; -static const char *explorer[] = {NULL, "explorer.exe", NULL}; -static const char *taskManager[] = {NULL, "Taskmgr.exe", NULL}; -static const char *adbConnect[] = {NULL, "D:/win32/ADB-Connect/adb-tcpip-connect.exe", NULL}; -static const char *scrcpy[] = {NULL, "D:/win32/ADB-Connect/launch-scrcpy.vbs", NULL}; - -#define NUMKEY(x) \ - {MODKEY, x+'0', GoToDesktopNumberW, {.i= x ? x : 10}}, \ - {MODKEY|MOD_SHIFT, x+'0', MoveWindowToDesktopNumberW, {.i= x ? x : 10}} - -static Key keys[] = { - /* modifier key function argument */ - { MODKEY, 'B', test, {0} }, - { MODKEY, 'O', spawn, {.v = vscode} }, - { MODKEY, VK_RETURN, spawn, {.v = termcmd } }, - { MODKEY | MOD_SHIFT, VK_RETURN, spawn, {.v = adminCmd } }, - { MODKEY, 'C', spawn, {.v = codeforces } }, - { MODKEY, 'L', spawn, {.v = leetcode } }, - { MODKEY | MOD_SHIFT, 'E', toggleexplorer, {0} }, - { MODKEY, 'Q', killForeground, {0} }, - { MODKEY | MOD_SHIFT, 'Q', killMacForeground, {0} }, - { MODKEY, 'E', spawn, {.v = explorer}}, - { MODKEY | MOD_SHIFT, 'Q', quit, {0} }, - { MODKEY, 'T', spawn, {.v = taskManager } }, - { MODKEY, 'D', spawn, {.v = adbConnect } }, - { MODKEY, 'F', spawn, {.v = scrcpy } }, - #ifdef VDA_FEATURES - NUMKEY(1), - NUMKEY(2), - NUMKEY(3), - NUMKEY(4), - NUMKEY(5), - NUMKEY(6), - NUMKEY(7), - NUMKEY(8), - NUMKEY(9), - NUMKEY(0), - #endif -};
diff --git a/dwhkdrc.example b/dwhkdrc.example @@ -0,0 +1,17 @@ +# Lines without indentation are hotkeys; indented lines are commands. +# Copy to %APPDATA%\dwhkd\dwhkdrc or pass -c PATH. +alt + return + start wt.exe + +alt + e + start explorer.exe + +ctrl + shift + f12 + echo hello > "%TEMP%\shkd-example.txt" + +# Optional virtual desktop actions require plugins/vd/plugin.dll. +alt + 1 + :vd goto-desktop 1 + +alt + shift + 1 + :vd move-to-desktop 1
diff --git a/dwhkdrc.manual b/dwhkdrc.manual @@ -0,0 +1,21 @@ +# Manual app-pinning and Explorer-restart test. Focus an app window first. +ctrl + alt + shift + f7 + :vd pin-app +# Add an indented notifier command here if you want feedback after success. +# your-notifier.exe "App pinned" + +ctrl + alt + shift + f8 + :vd unpin-app + +ctrl + alt + shift + f9 + :vd app-pin-status +# Status is silent: add your own indented notification command if desired. + +ctrl + alt + shift + f1 + :vd goto-desktop 1 + +ctrl + alt + shift + f2 + :vd goto-desktop 2 + +ctrl + alt + shift + f12 + :quit
diff --git a/libs/virtualdesktopaccessor/LICENSE.txt b/libs/virtualdesktopaccessor/LICENSE.txt @@ -0,0 +1,18 @@ +Copyright (c) 2015-2023 Jari Otto Oskari Pennanen + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+ \ No newline at end of file
diff --git a/libs/virtualdesktopaccessor/README.md b/libs/virtualdesktopaccessor/README.md @@ -0,0 +1,11 @@ +# VirtualDesktopAccessor C port + +[`VirtualDesktopAccessor.c`](VirtualDesktopAccessor.c), [`notifications.c`](notifications.c), and [`virtualdesktopaccessor.h`](virtualdesktopaccessor.h) adapt the virtual-desktop COM code from [Ciantic/VirtualDesktopAccessor](https://github.com/Ciantic/VirtualDesktopAccessor). **Original author: Jari Otto Oskari Pennanen (© 2015–2023).** Keep the original [MIT license and copyright notice](LICENSE.txt) with the source and binaries containing it. The library has no hotkey action names; those live in [`plugins/vd/plugin.c`](../../plugins/vd/plugin.c). + +The DLL exports the upstream desktop/window queries and movement functions, desktop IDs, UTF-8 names, creation/removal/reordering, window/app pinning, notification registration, and `RestartVirtualDesktopAccessor`. C signatures are in the header. `VDACreateDesktop()` is the C identifier because Win32 already defines `CreateDesktopA/W`; its **DLL export is `CreateDesktop`**. Indices are zero-based. Most operations return `1` on success, `0` for a false query (or an unavailable desktop name), and `-1` on error; ID queries return a zero GUID on error. `GetDesktopName` needs an output buffer including the terminating NUL; `SetDesktopName` takes UTF-8. `RestartVirtualDesktopAccessor` is a no-op because this implementation opens fresh COM proxies for each call. + +`RegisterPostMessageHook(hwnd, message)` posts a desktop-switch notification to each registered window (`wParam` = old index, `lParam` = new index). It returns `1` or `-1`. `UnregisterPostMessageHook(hwnd)` removes that window. **Unregister all listeners before unloading the DLL**; COM callbacks run on a background thread. If Explorer refuses to unregister a callback, the DLL retains a module reference rather than unloading callback code still in use. The notification worker attempts to reconnect after Explorer restarts, but missed transitions are not replayed. + +Build from an x64 Visual Studio Developer Command Prompt with `busybox make`; it uses `cl.exe`/`link.exe` and produces `plugins/vd/plugin.dll` without Rust. `busybox make test-vd` checks exports, ID/name reads, and notification registration on a live desktop. Optional checks in the same prompt: `set VDA_TEST_MOVE=1 && busybox make test-vd` moves and pins/unpins a temporary test window; `set VDA_TEST_MUTATE=1 && busybox make test-vd` creates, names, and removes a temporary desktop; `set VDA_TEST_SWITCH=1 && busybox make test-vd` switches to the already-current desktop; `set VDA_TEST_NOTIFY=1 && busybox make test-vd` briefly switches to another desktop and back, checking the posted event. Move, pin-window, temporary-desktop, and notification-delivery checks passed locally on Windows 11 25H2 build 26200.9711. App pinning, cross-desktop window movement/focus, and Explorer-restart recovery have **not** been verified. The mutation test attempts removal even after a failed assertion; check for a leftover `dwhkd-port-smoke` desktop if it fails. + +These Explorer COM interfaces are **undocumented and version-sensitive**. Layouts follow upstream's Windows 11 24H2 build 26100.2605+ implementation and may break after Windows updates. The public `IVirtualDesktopManager` only provides window queries/movement; the other APIs are not Rust-only, but are not stable public Windows APIs either.
diff --git a/libs/virtualdesktopaccessor/VirtualDesktopAccessor.c b/libs/virtualdesktopaccessor/VirtualDesktopAccessor.c @@ -0,0 +1,410 @@ +/* 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, ¤t))) 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) {}
diff --git a/libs/virtualdesktopaccessor/notifications.c b/libs/virtualdesktopaccessor/notifications.c @@ -0,0 +1,251 @@ +/* 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); +}
diff --git a/libs/virtualdesktopaccessor/virtualdesktopaccessor.h b/libs/virtualdesktopaccessor/virtualdesktopaccessor.h @@ -0,0 +1,40 @@ +/* VirtualDesktopAccessor C port; derived from Ciantic/VirtualDesktopAccessor. + * Copyright (c) 2015-2023 Jari Otto Oskari Pennanen. See LICENSE.txt. + */ +#ifndef VIRTUALDESKTOPACCESSOR_H +#define VIRTUALDESKTOPACCESSOR_H +#include <windows.h> +#include <stddef.h> +#ifdef VDA_BUILD_DLL +#define VDA_API __declspec(dllexport) +#else +#define VDA_API +#endif + +VDA_API int GetDesktopCount(void); +VDA_API int GetCurrentDesktopNumber(void); +VDA_API int GetWindowDesktopNumber(HWND hwnd); +VDA_API int IsWindowOnCurrentVirtualDesktop(HWND hwnd); +VDA_API int GoToDesktopNumber(int zero_based_index); +VDA_API int MoveWindowToDesktopNumber(HWND hwnd, int zero_based_index); +VDA_API GUID GetDesktopIdByNumber(int zero_based_index); +VDA_API int GetDesktopNumberById(GUID desktop_id); +VDA_API GUID GetWindowDesktopId(HWND hwnd); +VDA_API int IsWindowOnDesktopNumber(HWND hwnd, int zero_based_index); +/* C identifier differs from Win32's CreateDesktopA macro; DLL export is CreateDesktop. */ +VDA_API int VDACreateDesktop(void); +VDA_API int RemoveDesktop(int zero_based_index, int fallback_index); +VDA_API int MoveDesktop(int zero_based_index, int new_index); +VDA_API int SetDesktopName(int zero_based_index, const char *utf8); +VDA_API int GetDesktopName(int zero_based_index, char *utf8, size_t capacity); +VDA_API int IsPinnedWindow(HWND hwnd); +VDA_API int PinWindow(HWND hwnd); +VDA_API int UnPinWindow(HWND hwnd); +VDA_API int IsPinnedApp(HWND hwnd); +VDA_API int PinApp(HWND hwnd); +VDA_API int UnPinApp(HWND hwnd); +VDA_API int RegisterPostMessageHook(HWND hwnd, UINT message); +VDA_API void UnregisterPostMessageHook(HWND hwnd); +VDA_API void RestartVirtualDesktopAccessor(void); + +#endif
diff --git a/main.c b/main.c @@ -1,175 +1,203 @@ #include <windows.h> -#include <winuser.h> -#include <stdlib.h> -#include <stdio.h> #include <shellapi.h> -#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> -#define NAME "sxhkd-win32" -#define LENGTH(x) (sizeof x / sizeof x[0]) +#define NAME "dwhkd" typedef union { - int i; - unsigned int ui; - float f; - void *v; + int i; + unsigned int ui; + float f; + void *v; } Arg; -typedef struct { - unsigned int mod; - unsigned int key; - void (*func)(const Arg *); - const Arg arg; -} Key; - #include "debug.h" #include "actions.h" -#include "config.h" - -HWND dwmhwnd; - -#ifdef VDA_FEATURES -HMODULE VDA; - -typedef int(*GoToDesktopNumber)(int); -typedef int(*MoveWindowToDesktopNumber)(HWND, int); -typedef int(*GetCurrentDesktop)(); -typedef int(*GetWindowDesktopNumber)(HWND); -typedef int(*GetCurrentDesktopNumber)(); -typedef int(*IsWindowOnCurrentVirtualDesktop)(HWND); +#include "config.c" +#include "plugin.h" -GetCurrentDesktop GetCurrentDesktopFunc; -MoveWindowToDesktopNumber MoveWindowToDesktopNumberFunc; -GoToDesktopNumber GoToDesktopNumberFunc; -GetWindowDesktopNumber GetWindowDesktopNumberFunc; -GetCurrentDesktopNumber GetCurrentDesktopNumberFunc; -IsWindowOnCurrentVirtualDesktop IsWindowOnCurrentVirtualDesktopFunc; +static HWND dwmhwnd; +typedef struct { + char *name; + HMODULE dll; + sxhkd_plugin_invoke_fn invoke; +} Plugin; +static Plugin *plugins; +static size_t plugin_count; + +static void unload_plugins(void) { + for (size_t i = 0; i < plugin_count; i++) { + if (plugins[i].dll) FreeLibrary(plugins[i].dll); + free(plugins[i].name); + } + free(plugins); + plugins = NULL; + plugin_count = 0; +} -HWND lastActive[10]; // 0 to 9 index -#endif +static int load_plugins(void) { + if (!binding_count) return 1; + plugins = calloc(binding_count, sizeof *plugins); + if (!plugins) return 0; + char path[MAX_PATH]; + DWORD n = GetModuleFileNameA(NULL, path, sizeof path); + if (!n || n >= sizeof path) return 0; + char *slash = strrchr(path, '\\'); + if (!slash) return 0; + size_t remaining = sizeof path - (slash + 1 - path); + for (size_t i = 0; i < binding_count; i++) { + Binding *binding = &bindings[i]; + if (binding->action != PLUGIN) continue; + size_t j = 0; + for (; j < plugin_count; j++) + if (same(binding->plugin_name, plugins[j].name)) break; + if (j == plugin_count) { + int length = snprintf(slash + 1, remaining, "plugins\\%s\\plugin.dll", binding->plugin_name); + if (length < 0 || (size_t)length >= remaining) return 0; + Plugin *plugin = &plugins[plugin_count++]; + plugin->name = copy_string(binding->plugin_name); + if (!plugin->name) return 0; + plugin->dll = LoadLibraryExA(path, NULL, + LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); + if (!plugin->dll) { + fprintf(stderr, "Cannot load %s (error %lu)\n", path, GetLastError()); + return 0; + } + sxhkd_plugin_abi_fn abi = (sxhkd_plugin_abi_fn)GetProcAddress(plugin->dll, "sxhkd_plugin_abi"); + plugin->invoke = (sxhkd_plugin_invoke_fn)GetProcAddress(plugin->dll, "sxhkd_plugin_invoke"); + if (!abi || !plugin->invoke || abi() != SXHKD_PLUGIN_ABI) { + fprintf(stderr, "Incompatible plugin: %s\n", path); + return 0; + } + } + binding->plugin_index = j; + } + return 1; +} #include "actions.c" -void cleanup() { - for (int i = 0; i < LENGTH(keys); i++) UnregisterHotKey(dwmhwnd, i + 1); - DestroyWindow(dwmhwnd); - #ifdef VDA_FEATURES - FreeLibrary(VDA); - #endif +static int run_command(const char *command) { + const char *shell = getenv("COMSPEC"); + if (!shell || !*shell) shell = "cmd.exe"; + char *parameters = malloc(strlen(command) + 4); + if (!parameters) return -1; + sprintf(parameters, "/C %s", command); + HINSTANCE launched = ShellExecuteA(NULL, "open", shell, parameters, NULL, SW_HIDE); + free(parameters); + return (INT_PTR)launched > 32 ? 0 : -1; } -void die(const char *errstr, ...) { - va_list ap; - va_start(ap, errstr); - dbg(errstr, ap); - va_end(ap); - cleanup(); - exit(EXIT_FAILURE); +static int run_binding(const Binding *binding) { + Arg arg = {0}; + switch (binding->action) { + case PLUGIN: { + int result = plugins[binding->plugin_index].invoke(binding->plugin_action, binding->plugin_args); + if (result) fprintf(stderr, "Plugin %s failed: %s\n", binding->plugin_name, binding->plugin_action); + return result; + } + case TOGGLE_EXPLORER: toggleexplorer(&arg); break; + case CLOSE_WINDOW: killForeground(&arg); break; + case FORCE_CLOSE_WINDOW: killMacForeground(&arg); break; + case QUIT: quit(&arg); return 1; /* Do not run later commands after quitting. */ + case TEST: test(&arg); break; + default: return run_command(binding->command); + } + return 0; } -LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - switch (msg) { - case WM_CREATE: - break; - case WM_CLOSE: - cleanup(); - break; - case WM_DESTROY: - PostQuitMessage(0); - break; - case WM_HOTKEY: - if (wParam > 0 && wParam <= LENGTH(keys)) { - dbg("\nHotkey was pressed!\n"); - keys[wParam - 1].func(&(keys[wParam - 1].arg)); - } - break; - default: - return DefWindowProc(hwnd, msg, wParam, lParam); - } - return 0; +static void run_sequence(size_t first) { + unsigned int mod = bindings[first].mod, key = bindings[first].key; + for (size_t i = first; i < binding_count && bindings[i].mod == mod && + bindings[i].key == key; i++) + if (run_binding(&bindings[i])) break; } - -void setup(HINSTANCE hInstance) { - WNDCLASSEX winClass; - - winClass.cbSize = sizeof(WNDCLASSEX); - winClass.style = 0; - winClass.lpfnWndProc = WndProc; - winClass.cbClsExtra = 0; - winClass.cbWndExtra = 0; - winClass.hInstance = hInstance; - winClass.hIcon = NULL; - winClass.hIconSm = NULL; - winClass.hCursor = NULL; - winClass.hbrBackground = NULL; - winClass.lpszMenuName = NULL; - winClass.lpszClassName = NAME; - - if (!RegisterClassEx(&winClass)) die("Error registering window class\n"); - dwmhwnd = CreateWindowEx(0, NAME, NAME, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, hInstance, NULL); - if (!dwmhwnd) die("Error creating window\n"); - for (int i = 0; i < LENGTH(keys); i++) RegisterHotKey(dwmhwnd, i + 1, keys[i].mod, keys[i].key); +static LRESULT CALLBACK window_proc(HWND hwnd, UINT message, WPARAM id, LPARAM data) { + switch (message) { + case WM_HOTKEY: + if (id > 0 && id <= binding_count) run_sequence(id - 1); + return 0; + case WM_CLOSE: + DestroyWindow(hwnd); + return 0; + case WM_DESTROY: + PostQuitMessage(0); + return 0; + default: + return DefWindowProcA(hwnd, message, id, data); + } } -#ifdef VDA_FEATURES -BOOL CALLBACK initEnumCall(HWND hwnd, LPARAM lParam) { - char windowTitle[256]; - GetWindowTextA(hwnd, windowTitle, sizeof(windowTitle)); - if (IsWindowVisible(hwnd) && windowTitle[0] != '\0') { - if(lastActive[GetWindowDesktopNumberFunc(hwnd)]!=NULL) return TRUE; - printf("windowTitle: %s %d\n", windowTitle, GetWindowDesktopNumberFunc(hwnd)); - lastActive[GetWindowDesktopNumberFunc(hwnd)]=hwnd; +int WINAPI WinMain(HINSTANCE instance, HINSTANCE previous, LPSTR command_line, int show) { + char default_path[MAX_PATH]; + const char *path; + if (__argc > 1) { + if (__argc != 3 || strcmp(__argv[1], "-c")) { + MessageBoxA(NULL, "Usage: dwhkd [-c CONFIG_FILE]", NAME, MB_OK | MB_ICONERROR); + return 1; + } + path = __argv[2]; + } else { + DWORD length = GetEnvironmentVariableA("APPDATA", default_path, sizeof default_path); + if (!length || length >= sizeof default_path || + length + strlen("\\dwhkd\\dwhkdrc") >= sizeof default_path) { + MessageBoxA(NULL, "APPDATA is unavailable; specify a config with -c.", NAME, MB_OK | MB_ICONERROR); + return 1; + } + strcat(default_path, "\\dwhkd\\dwhkdrc"); + path = default_path; + } + if (!load_config(path)) { + char message[MAX_PATH + 100]; + snprintf(message, sizeof message, "Cannot load %s. See stderr for details.\nUse -c to specify a config file.", path); + MessageBoxA(NULL, message, NAME, MB_OK | MB_ICONERROR); + return 1; } - return TRUE; -} -HWND initLastActive(){ - EnumWindows(initEnumCall, 0); - return topmost; + if (!load_plugins()) { + MessageBoxA(NULL, "Could not load plugin; check stderr for details.", NAME, MB_OK | MB_ICONERROR); + unload_plugins(); + free_bindings(); + return 1; + } + WNDCLASSEXA cls = {0}; + cls.cbSize = sizeof cls; + cls.lpfnWndProc = window_proc; + cls.hInstance = instance; + cls.lpszClassName = NAME; + if (!RegisterClassExA(&cls)) { + MessageBoxA(NULL, "Could not register window class.", NAME, MB_OK | MB_ICONERROR); + unload_plugins(); + free_bindings(); + return 1; + } + dwmhwnd = CreateWindowExA(0, NAME, NAME, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, instance, NULL); + if (!dwmhwnd) { + MessageBoxA(NULL, "Could not create message window.", NAME, MB_OK | MB_ICONERROR); + unload_plugins(); + free_bindings(); + return 1; + } + for (size_t i = 0; i < binding_count; i++) { + if (i && bindings[i].mod == bindings[i - 1].mod && bindings[i].key == bindings[i - 1].key) + continue; + if (!RegisterHotKey(dwmhwnd, (int)i + 1, bindings[i].mod, bindings[i].key)) + fprintf(stderr, "%s: hotkey %zu unavailable (error %lu)\n", path, i + 1, GetLastError()); + } + MSG msg; + while (GetMessageA(&msg, NULL, 0, 0) > 0) { + TranslateMessage(&msg); + DispatchMessageA(&msg); + } + for (size_t i = 0; i < binding_count; i++) { + if (i && bindings[i].mod == bindings[i - 1].mod && bindings[i].key == bindings[i - 1].key) + continue; + UnregisterHotKey(dwmhwnd, (int)i + 1); + } + free_bindings(); + unload_plugins(); + return (int)msg.wParam; } -#endif - -int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { - -#ifdef DEBUG - extern char ** __argv; - extern int __argc; - - if (AttachConsole(ATTACH_PARENT_PROCESS)) { - freopen("CONOUT$", "wb", stdout); - freopen("CONOUT$", "wb", stderr); - } -#endif - - dbg("Hello!! : ))\n"); - #ifdef VDA_FEATURES - char* libName = "\\VirtualDesktopAccessor.dll"; - TCHAR exeFullPath[MAX_PATH + 1] = { 0 }; - GetModuleFileName(NULL, exeFullPath, MAX_PATH); - char* lastSlash = strrchr(exeFullPath, '\\'); - if (lastSlash != NULL) *(lastSlash + 1) = '\0'; - strcat_s(exeFullPath, sizeof exeFullPath, libName); - HINSTANCE VDA = LoadLibrary(exeFullPath); - if (VDA == NULL) printf("Failed to load the DLL, VD Features will not work\n"); - MoveWindowToDesktopNumberFunc = (MoveWindowToDesktopNumber)GetProcAddress(VDA, "MoveWindowToDesktopNumber"); - GoToDesktopNumberFunc = (GoToDesktopNumber)GetProcAddress(VDA, "GoToDesktopNumber"); - GetCurrentDesktopFunc = (GetCurrentDesktop)GetProcAddress(VDA, "GetCurrentDesktopNumber"); - GetWindowDesktopNumberFunc = (GetWindowDesktopNumber)GetProcAddress(VDA, "GetWindowDesktopNumber"); - GetCurrentDesktopNumberFunc = (GetCurrentDesktopNumber)GetProcAddress(VDA, "GetCurrentDesktopNumber"); - IsWindowOnCurrentVirtualDesktopFunc = (IsWindowOnCurrentVirtualDesktop)GetProcAddress(VDA, "IsWindowOnCurrentVirtualDesktop"); - for(int i=0; i<10; i++) lastActive[i]=NULL; - // init with topmost windows of all VDs is essential for when not launched at startup - initLastActive(); - #endif - MSG msg; - setup(hInstance); - - while (GetMessage(&msg, NULL, 0, 0) > 0) { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - cleanup(); - - return msg.wParam; -}- \ No newline at end of file
diff --git a/old-scripts/clean.bat b/old-scripts/clean.bat @@ -1,2 +0,0 @@ -@echo off -del a.exe
diff --git a/old-scripts/compile.bat b/old-scripts/compile.bat @@ -1,2 +0,0 @@ -@echo off -gcc ./main.c -DDEBUG -mwindows
diff --git a/old-scripts/kill.bat b/old-scripts/kill.bat @@ -1,2 +0,0 @@ -@echo off -taskkill /f /im a.exe
diff --git a/old-scripts/remove-startup.bat b/old-scripts/remove-startup.bat @@ -1,19 +0,0 @@ -@echo off -set /p "username=Enter your username: " - -REM Check if the username variable is not empty -if not "%username%"=="" ( - REM Remove files from the destination folder - del "C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\VirtualDesktopAccessor.dll" /f /q - del "C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\sxhkd-win32.exe" /f /q - - if %errorlevel% equ 0 ( - echo Files removed successfully from the Startup folder for user %username%. - ) else ( - echo Error: Unable to remove files from the Startup folder. - ) -) else ( - echo Error: Username cannot be empty. -) - -pause
diff --git a/old-scripts/run.bat b/old-scripts/run.bat @@ -1,2 +0,0 @@ -@echo off -start /w a.exe
diff --git a/old-scripts/startup.bat b/old-scripts/startup.bat @@ -1,19 +0,0 @@ -@echo off -set /p "username=Enter your username: " - -REM Check if the username variable is not empty -if not "%username%"=="" ( - REM Copy files to the destination folder - copy "VirtualDesktopAccessor.dll" "C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" - copy "sxhkd-win32.exe" "C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" - - if %errorlevel% equ 0 ( - echo Files copied successfully to Startup folder for user %username%. - ) else ( - echo Error: Unable to copy files to Startup folder. - ) -) else ( - echo Error: Username cannot be empty. -) - -pause
diff --git a/plugin.h b/plugin.h @@ -0,0 +1,10 @@ +/* Versioned C ABI for plugins/<name>/plugin.dll (64-bit Windows). */ +#ifndef SXHKD_PLUGIN_H +#define SXHKD_PLUGIN_H +#define SXHKD_PLUGIN_ABI 1 +/* Export both names with C linkage; return 0 on invoke success, nonzero on error. + * Arguments are raw bytes from the config (often UTF-8, not validated). + * The plugin owns parsing and obtains live HWND or other values when invoked. */ +typedef int (__cdecl *sxhkd_plugin_abi_fn)(void); +typedef int (__cdecl *sxhkd_plugin_invoke_fn)(const char *action, const char *arguments); +#endif
diff --git a/plugins/vd/README.md b/plugins/vd/README.md @@ -0,0 +1,9 @@ +# Virtual desktop plugin + +The host reads `:vd goto-desktop 2`, `:vd move-to-desktop 2`, `:vd pin-app`, `:vd unpin-app`, or `:vd app-pin-status`, loads `plugins/vd/plugin.dll` **once**, and calls its `sxhkd_plugin_invoke` export on each keypress. `plugins/vd/plugin.c` owns the action names, argument validation, foreground `HWND` lookup and focus tracking. `libs/virtualdesktopaccessor/VirtualDesktopAccessor.c` calls the undocumented Windows COM interfaces; no shell or child process runs for these actions. After a move, focus falls back to the first visible, titled window found on the current desktop (the original project's focus policy); this may not be the window you last used. + +Config desktop numbers are **1–10** (`0` also means 10); the DLL internally uses zero-based indices. Build with `busybox make` from an x64 Visual Studio Developer Command Prompt at the repository root, which builds this DLL at `plugins/vd/plugin.dll`. Keep this directory layout relative to `dwhkd.exe` and include the original [MIT notice](../../libs/virtualdesktopaccessor/LICENSE.txt) when distributing it. + +The generic host/plugin ABI, rules for adding your own plugin, and error handling are documented in the [top-level README](../../README.md#plugins). The plugin's version and `invoke` exports use [`plugin.h`](../../plugin.h). The DLL also exports the library's low-level naming, pinning, notification, and desktop-management APIs. The `:vd` adapter exposes the five actions above. App-pinning actions use the foreground window and show no UI. `app-pin-status` returns 0 only when the app is pinned; add a separate user-defined notification command if you want feedback. The host does not depend on the library export names. + +This plugin currently targets **Windows 11 24H2 build 26100.2605 or later**. The interface layouts are undocumented and may change after Windows updates. See the [C library's notes and smoke tests](../../libs/virtualdesktopaccessor/README.md). The COM layout and export behavior were adapted under MIT from [Ciantic/VirtualDesktopAccessor](https://github.com/Ciantic/VirtualDesktopAccessor).
diff --git a/plugins/vd/plugin.c b/plugins/vd/plugin.c @@ -0,0 +1,89 @@ +/* Desktop action adapter: this logic belongs to the plugin, not the hotkey host. */ +#include <windows.h> +#include <stdlib.h> +#include <string.h> +#include "../../plugin.h" +#include "../../libs/virtualdesktopaccessor/virtualdesktopaccessor.h" + +static HWND last_active[10]; +static HWND topmost; +static int initialized; + +static BOOL CALLBACK remember_window(HWND hwnd, LPARAM unused) { + (void)unused; + char title[256]; + GetWindowTextA(hwnd, title, sizeof title); + if (IsWindowVisible(hwnd) && title[0]) { + int index = GetWindowDesktopNumber(hwnd); + if (index >= 0 && index < 10 && !last_active[index]) last_active[index] = hwnd; + } + return TRUE; +} + +static BOOL CALLBACK find_current_window(HWND hwnd, LPARAM unused) { + (void)unused; + char title[256]; + GetWindowTextA(hwnd, title, sizeof title); + if (IsWindowVisible(hwnd) && title[0] && IsWindowOnCurrentVirtualDesktop(hwnd) == 1) { + topmost = hwnd; + return FALSE; + } + return TRUE; +} + +/* Returns config desktop number converted to the DLL's zero-based index. */ +static int parse_desktop(const char *args) { + if (!args || !*args) return -1; + char *end; + long value = strtol(args, &end, 10); + if (end == args || *end || value < 0 || value > 10) return -1; + return value ? (int)value - 1 : 9; +} + +__declspec(dllexport) int sxhkd_plugin_abi(void) { + if (!initialized) { + EnumWindows(remember_window, 0); + initialized = 1; + } + return SXHKD_PLUGIN_ABI; +} + +__declspec(dllexport) int sxhkd_plugin_invoke(const char *action, const char *arguments) { + if (!action) return -1; + if (strcmp(action, "pin-app") == 0 || strcmp(action, "unpin-app") == 0 || + strcmp(action, "app-pin-status") == 0) { + if (!arguments || *arguments) return -1; + HWND foreground = GetForegroundWindow(); + int result = !foreground ? -1 : strcmp(action, "pin-app") == 0 + ? PinApp(foreground) : strcmp(action, "unpin-app") == 0 + ? UnPinApp(foreground) : IsPinnedApp(foreground); + /* Status succeeds only when pinned; callers choose their own feedback. */ + return result == 1 ? 0 : -1; + } + int index = parse_desktop(arguments); + if (index < 0) return -1; + if (strcmp(action, "goto-desktop") == 0) { + int current = GetCurrentDesktopNumber(); + if (current < 0 || current >= 10) return -1; + if (current == index) return 0; + last_active[current] = GetForegroundWindow(); + if (GoToDesktopNumber(index) != 1) return -1; + if (last_active[index] && IsWindow(last_active[index]) && + GetWindowDesktopNumber(last_active[index]) == index) + SetForegroundWindow(last_active[index]); + return 0; + } + if (strcmp(action, "move-to-desktop") == 0) { + HWND foreground = GetForegroundWindow(); + if (!foreground) return -1; + if (GetCurrentDesktopNumber() == index && IsWindowOnCurrentVirtualDesktop(foreground) == 1) + return 0; + if (MoveWindowToDesktopNumber(foreground, index) != 1) return -1; + last_active[index] = foreground; + topmost = NULL; + EnumWindows(find_current_window, 0); + if (topmost) SetForegroundWindow(topmost); + return 0; + } + return -1; +}
diff --git a/plugins/vd/plugin.dll b/plugins/vd/plugin.dll Binary files differ.
diff --git a/tests/config_test.c b/tests/config_test.c @@ -0,0 +1,61 @@ +#include <windows.h> +#include <assert.h> +#include <stdio.h> +#include <stdlib.h> +#include "../config.c" + +int main(void) { + const char *path = "config-test.tmp"; + FILE *file = fopen(path, "w"); + assert(file); + fputs("# comment\nalt + shift + return\n echo first +1\n echo obsolete\n" + "ctrl + f12\n echo second\n" + "alt + shift + return\n echo replacement\n :vd pin-app\n :vd app-pin-status\n" + "win + =65\n echo numeric\n" + "alt + 1\n :vd goto-desktop 1\n" + "alt + shift + 0\n :vd move-to-desktop 0\n" + "ctrl + alt + f11\n :quit\n", file); + fclose(file); + assert(load_config(path)); + assert(binding_count == 8); + assert(bindings[0].key == VK_F12 && bindings[0].mod == MOD_CONTROL); + assert(bindings[1].key == VK_RETURN && bindings[1].mod == (MOD_ALT | MOD_SHIFT)); + assert(strcmp(bindings[1].command, "echo replacement") == 0); + assert(bindings[2].action == PLUGIN && strcmp(bindings[2].plugin_action, "pin-app") == 0); + assert(bindings[3].action == PLUGIN && strcmp(bindings[3].plugin_action, "app-pin-status") == 0); + assert(bindings[4].key == 'A' && bindings[4].mod == MOD_WIN); + assert(bindings[5].action == PLUGIN && strcmp(bindings[5].plugin_name, "vd") == 0); + assert(strcmp(bindings[5].plugin_action, "goto-desktop") == 0); + assert(strcmp(bindings[5].plugin_args, "1") == 0); + assert(bindings[6].action == PLUGIN && strcmp(bindings[6].plugin_action, "move-to-desktop") == 0); + assert(strcmp(bindings[6].plugin_args, "0") == 0); + assert(bindings[7].action == QUIT); + free_bindings(); + + file = fopen(path, "w"); + assert(file); + fputs("alt + release + a\n echo unsupported\n", file); + fclose(file); + assert(!load_config(path)); + assert(binding_count == 0); + file = fopen(path, "w"); + assert(file); + fputs("alt + a\nalt + b\n echo b\n", file); + fclose(file); + assert(!load_config(path)); + assert(binding_count == 0); + file = fopen(path, "w"); + assert(file); + fputs("alt + 1\n :../evil run now\n", file); + fclose(file); + assert(!load_config(path)); + assert(binding_count == 0); + file = fopen(path, "w"); + assert(file); + fputs("alt + 1\n :vd.move-to-desktop 2\n", file); + fclose(file); + assert(!load_config(path)); + assert(binding_count == 0); + remove(path); + return 0; +}
diff --git a/tests/plugin_smoke.c b/tests/plugin_smoke.c @@ -0,0 +1,64 @@ +#include <windows.h> +#include <stdio.h> +#include <string.h> +#include "../plugin.h" + +#ifdef BUILD_PLUGIN +__declspec(dllexport) int sxhkd_plugin_abi(void) { return SXHKD_PLUGIN_ABI; } +__declspec(dllexport) int sxhkd_plugin_invoke(const char *action, const char *args) { + if (strcmp(action, "ping") != 0) return -1; + HANDLE event = OpenEventA(EVENT_MODIFY_STATE, FALSE, args); + if (!event) return -1; + int ok = SetEvent(event); + CloseHandle(event); + return ok ? 0 : -1; +} +#else +int main(void) { + char config[MAX_PATH], temp[MAX_PATH], command[MAX_PATH * 3], name[80], second[84], skipped[84]; + if (!GetTempPathA(sizeof temp, temp) || !GetTempFileNameA(temp, "shk", 0, config)) return 1; + snprintf(name, sizeof name, "Local\\sxhkd-plugin-smoke-%lu-%lu", + GetCurrentProcessId(), GetTickCount()); + snprintf(second, sizeof second, "%s-2", name); + snprintf(skipped, sizeof skipped, "%s-3", name); + HANDLE event = CreateEventA(NULL, TRUE, FALSE, name); + HANDLE next = CreateEventA(NULL, TRUE, FALSE, second); + HANDLE not_run = CreateEventA(NULL, TRUE, FALSE, skipped); + FILE *file = fopen(config, "w"); + if (!event || !next || !not_run || !file) return 1; + fprintf(file, "alt + f24\n :smoke ping %s\n :smoke ping %s\n" + " :smoke unknown\n :smoke ping %s\n", name, second, skipped); + fclose(file); + snprintf(command, sizeof command, "\"%s\\dwhkd.exe\" -c \"%s\"", ".", config); + STARTUPINFOA si = {.cb = sizeof si}; + PROCESS_INFORMATION pi; + if (!CreateProcessA(NULL, command, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) return 1; + HWND hwnd = NULL; + for (int tries = 0; tries < 40 && !hwnd; tries++) { + HWND candidate = NULL; + while ((candidate = FindWindowExA(HWND_MESSAGE, candidate, "dwhkd", NULL))) { + DWORD pid = 0; + GetWindowThreadProcessId(candidate, &pid); + if (pid == pi.dwProcessId) { hwnd = candidate; break; } + } + if (!hwnd) Sleep(50); + } + int ok = hwnd && PostMessageA(hwnd, WM_HOTKEY, 1, 0) && + WaitForSingleObject(event, 2000) == WAIT_OBJECT_0 && + WaitForSingleObject(next, 2000) == WAIT_OBJECT_0; + if (ok) { + SendMessageA(hwnd, WM_NULL, 0, 0); /* Wait until the hotkey handler has finished. */ + ok = WaitForSingleObject(not_run, 0) == WAIT_TIMEOUT; + } + if (hwnd) PostMessageA(hwnd, WM_CLOSE, 0, 0); + if (WaitForSingleObject(pi.hProcess, 2000) != WAIT_OBJECT_0) TerminateProcess(pi.hProcess, 1); + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + CloseHandle(event); + CloseHandle(next); + CloseHandle(not_run); + DeleteFileA(config); + printf("plugin dispatch: %s\n", ok ? "ok" : "failed"); + return ok ? 0 : 1; +} +#endif
diff --git a/tests/vd_smoke.c b/tests/vd_smoke.c @@ -0,0 +1,139 @@ +#include <windows.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include "../plugin.h" +#include "../libs/virtualdesktopaccessor/virtualdesktopaccessor.h" + +typedef int (*NoArg)(void); +typedef int (*WithIndex)(int); +typedef int (*WithWindow)(HWND); +typedef int (*MoveDesktopWindow)(HWND, int); + +int main(void) { + HMODULE dll = LoadLibraryA("plugin.dll"); + if (!dll) { fprintf(stderr, "DLL load failed: %lu\n", GetLastError()); return 1; } + NoArg count = (NoArg)GetProcAddress(dll, "GetDesktopCount"); + NoArg current = (NoArg)GetProcAddress(dll, "GetCurrentDesktopNumber"); + WithIndex go = (WithIndex)GetProcAddress(dll, "GoToDesktopNumber"); + if (!count || !current || !go || + !GetProcAddress(dll, "GetWindowDesktopNumber") || + !GetProcAddress(dll, "IsWindowOnCurrentVirtualDesktop") || + !GetProcAddress(dll, "MoveWindowToDesktopNumber")) { + fprintf(stderr, "Missing export\n"); + FreeLibrary(dll); + return 1; + } + sxhkd_plugin_abi_fn abi = (sxhkd_plugin_abi_fn)GetProcAddress(dll, "sxhkd_plugin_abi"); + sxhkd_plugin_invoke_fn invoke = (sxhkd_plugin_invoke_fn)GetProcAddress(dll, "sxhkd_plugin_invoke"); + if (!abi || !invoke || abi() != SXHKD_PLUGIN_ABI || + invoke("unknown", "1") == 0 || invoke("move-to-desktop", "invalid") == 0 || + invoke("pin-app", "unexpected") == 0 || invoke("app-pin-status", "unexpected") == 0) + return 1; + const char *exports[] = { + "GetDesktopIdByNumber", "GetDesktopNumberById", "GetWindowDesktopId", + "GetDesktopName", "SetDesktopName", "IsPinnedWindow", "PinWindow", + "UnPinWindow", "IsPinnedApp", "PinApp", "UnPinApp", + "IsWindowOnDesktopNumber", "CreateDesktop", "RemoveDesktop", "MoveDesktop", + "RegisterPostMessageHook", "UnregisterPostMessageHook", "RestartVirtualDesktopAccessor" + }; + for (size_t i = 0; i < sizeof exports / sizeof exports[0]; i++) { + if (!GetProcAddress(dll, exports[i])) { + fprintf(stderr, "Missing export: %s\n", exports[i]); + return 1; + } + } + int n = count(), index = current(); + printf("desktops: %d; current: %d\n", n, index); + if (n <= 0 || index < 0 || index >= n || go(-1) != -1 || go(n) != -1) { + fprintf(stderr, "COM interface unavailable or invalid result (requires Windows 11 24H2+)\n"); + return 1; + } + GUID (*id_by_number)(int) = (GUID (*)(int))GetProcAddress(dll, "GetDesktopIdByNumber"); + int (*number_by_id)(GUID) = (int (*)(GUID))GetProcAddress(dll, "GetDesktopNumberById"); + int (*get_name)(int, char *, size_t) = (int (*)(int, char *, size_t))GetProcAddress(dll, "GetDesktopName"); + char name[512]; + if (number_by_id(id_by_number(index)) != index || get_name(index, name, sizeof name) != 1) + return 1; + printf("desktop name: %s\n", name); + WithWindow window_number = (WithWindow)GetProcAddress(dll, "GetWindowDesktopNumber"); + GUID (*window_id)(HWND) = (GUID (*)(HWND))GetProcAddress(dll, "GetWindowDesktopId"); + WithWindow pinned_window = (WithWindow)GetProcAddress(dll, "IsPinnedWindow"); + GUID zero = {0}; + GUID invalid = window_id(NULL); + if (window_number(NULL) != -1 || memcmp(&invalid, &zero, sizeof zero) || + pinned_window(NULL) != -1) return 1; + HWND listener = CreateWindowExA(0, "STATIC", "notification smoke", 0, + 0, 0, 0, 0, HWND_MESSAGE, NULL, GetModuleHandleA(NULL), NULL); + int (*subscribe)(HWND, UINT) = (int (*)(HWND, UINT))GetProcAddress(dll, "RegisterPostMessageHook"); + void (*unsubscribe)(HWND) = (void (*)(HWND))GetProcAddress(dll, "UnregisterPostMessageHook"); + if (!listener || subscribe(listener, WM_APP + 10) != 1) return 1; + int notification_ok = 1; + if (getenv("VDA_TEST_NOTIFY") && n > 1) { + int target = index == 0 ? 1 : 0; + if (go(target) != 1) notification_ok = 0; + Sleep(700); + MSG message; + int received = 0; + while (PeekMessageW(&message, listener, WM_APP + 10, WM_APP + 10, PM_REMOVE)) + if (message.wParam == (WPARAM)index && message.lParam == (LPARAM)target) + received = 1; + if (go(index) != 1 || !received) notification_ok = 0; + } + unsubscribe(listener); + DestroyWindow(listener); + if (!notification_ok) { fprintf(stderr, "Desktop switch notification failed\n"); return 1; } + if (getenv("VDA_TEST_MUTATE")) { + int (*create)(void) = (int (*)(void))GetProcAddress(dll, "CreateDesktop"); + int (*remove_desktop)(int, int) = (int (*)(int, int))GetProcAddress(dll, "RemoveDesktop"); + int (*move_desktop)(int, int) = (int (*)(int, int))GetProcAddress(dll, "MoveDesktop"); + int (*set_name)(int, const char *) = (int (*)(int, const char *))GetProcAddress(dll, "SetDesktopName"); + int added = create(); + if (added < 0) { fprintf(stderr, "CreateDesktop failed\n"); return 1; } + char renamed[128]; + int ok = count() == n + 1 && + set_name(added, "dwhkd-port-smoke") == 1 && + get_name(added, renamed, sizeof renamed) == 1 && + strcmp(renamed, "dwhkd-port-smoke") == 0 && + move_desktop(added, added) == 1; + /* Always attempt cleanup even when validation fails. */ + int removed = remove_desktop(added, index); + if (!ok || removed != 1 || count() != n) return 1; + } + if (getenv("VDA_BENCH")) { + DWORD start = GetTickCount(); + for (int i = 0; i < 50; i++) if (count() < 1) return 1; + printf("50 desktop-count calls: %lu ms\n", GetTickCount() - start); + } + if (getenv("VDA_TEST_MOVE")) { + WithWindow window_index = (WithWindow)GetProcAddress(dll, "GetWindowDesktopNumber"); + WithWindow visible = (WithWindow)GetProcAddress(dll, "IsWindowOnCurrentVirtualDesktop"); + MoveDesktopWindow move = (MoveDesktopWindow)GetProcAddress(dll, "MoveWindowToDesktopNumber"); + HWND window = CreateWindowExA(0, "STATIC", "VDA smoke window", WS_OVERLAPPEDWINDOW, + 20, 20, 200, 100, NULL, NULL, GetModuleHandleA(NULL), NULL); + if (!window) return 1; + ShowWindow(window, SW_SHOWNOACTIVATE); + Sleep(300); + int before = window_index(window), on_current = visible(window); + int moved = move(window, index); + int (*is_pinned)(HWND) = (int (*)(HWND))GetProcAddress(dll, "IsPinnedWindow"); + int (*pin)(HWND) = (int (*)(HWND))GetProcAddress(dll, "PinWindow"); + int (*unpin)(HWND) = (int (*)(HWND))GetProcAddress(dll, "UnPinWindow"); + int was_pinned = is_pinned(window); + int pin_result = pin(window); + int now_pinned = is_pinned(window); + int unpin_result = unpin(window); /* Always try to restore before destroying. */ + printf("test window: desktop %d, current %d, move %d, pin %d/%d/%d\n", + before, on_current, moved, pin_result, now_pinned, unpin_result); + DestroyWindow(window); + if (before != index || on_current != 1 || moved != 1 || was_pinned != 0 || + pin_result != 1 || now_pinned != 1 || unpin_result != 1) return 1; + } + if (getenv("VDA_TEST_SWITCH") && go(index) != 1) { + fprintf(stderr, "Switching to current desktop failed\n"); + FreeLibrary(dll); + return 1; + } + FreeLibrary(dll); + return 0; +}
diff --git a/toggleWinKey.bat b/toggleWinKey.bat @@ -1,27 +0,0 @@ -@echo off ->nul 2>&1 net file || goto :notAdmin - -REM Continue with the script since it's running as admin -REM Get the current value of the registry key -for /f "tokens=3" %%a in ('reg query "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer" /v "NoWinKeys" 2^>nul ^| findstr /i "NoWinKeys"') do ( - set "currentValue=%%a" -) - -REM Toggle the value of NoWinKeys -if "%currentValue%"=="0x1" ( - reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer" /v "NoWinKeys" /t REG_DWORD /d 0 /f >nul - echo The value of NoWinKeys is now 0 -) else ( - reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer" /v "NoWinKeys" /t REG_DWORD /d 1 /f >nul - echo The value of NoWinKeys is now 1 -) - -echo Please restart your computer for changes to take place - -pause -exit /b - -:notAdmin -echo This script requires administrative privileges. -echo Please run the script as an administrator. -pause
: nply/dwhkd