From 5ca0b28737e09e2d51b45c604e25cfe72a0b9e80 Mon Sep 17 00:00:00 2001 From: kecsou Date: Sat, 31 Oct 2026 17:18:37 +0100 Subject: [PATCH 1/5] Rewrite the native addon in Rust, prebuilt for 15 targets - Replace the C/C++ N-API addon (libX11 + libXmu) with Rust: napi-rs 3 for the bindings, x11rb for the X11 protocol. No system libraries or compiler are needed at install time. - Ship prebuilt binaries in the package (prebuilds/-[-musl]), picked at runtime: Linux glibc 2.17+ (x64, arm64, arm, ppc64le, s390x, riscv64), Linux musl (x64, arm64, arm), FreeBSD x64, macOS x64/arm64, Windows x64/ia32/arm64. - Same JS API; fixes from 1.x: promises reject with Error objects, getWindowsBy* return [] instead of throwing, close*Sync return true, win_icon_name is set, transitions animate y, no double free in getActiveWindow. - Regression tests: Rust unit tests, an API suite (exports, validation, error messages, binary loader) and an X11 suite that drives a real WM with its own fixture windows. - CI cross-builds every Linux target with cargo-zigbuild and tests it in a container of that arch (QEMU when needed), builds and tests FreeBSD in a VM, runs the API suite on macOS and Windows, and publishes on v* tags. - TypeScript 7. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/c-cpp.yml | 23 - .github/workflows/ci.yml | 158 +++ .gitignore | 9 +- .npmignore | 20 - README.md | 71 +- binding.gyp | 22 - libwmctrl/Makefile | 29 - libwmctrl/libwmctrl.gyp | 16 - libwmctrl/src/desktop.c | 261 ----- libwmctrl/src/get-active-window.c | 43 - libwmctrl/src/screen.c | 20 - libwmctrl/src/utils.c | 741 -------------- libwmctrl/src/window-edit.c | 672 ------------ libwmctrl/src/window-manager.c | 98 -- libwmctrl/src/window-move-resize-transition.c | 172 ---- libwmctrl/src/window-move-resize.c | 143 --- libwmctrl/src/window-properties.c | 420 -------- libwmctrl/src/window.c | 168 --- libwmctrl/src/wmctrl.h | 261 ----- libwmctrl/test/test.c | 414 -------- native/.cargo/config.toml | 3 + native/Cargo.lock | 437 ++++++++ native/Cargo.toml | 25 + native/build.rs | 3 + native/examples/fixture.rs | 65 ++ native/src/lib.rs | 293 ++++++ native/src/wm.rs | 959 ++++++++++++++++++ package.json | 56 +- scripts/build-native.js | 28 + src/debug.js | 18 - src/index.ts | 39 +- src/napi/active-window-by-id.cpp | 59 -- src/napi/active-windows-by-className.cpp | 66 -- src/napi/active-windows-by-pid.cpp | 60 -- src/napi/allow-all-sizes-window.cpp | 60 -- src/napi/close-window-by-id.cpp | 59 -- src/napi/close-windows-by-className.cpp | 61 -- src/napi/close-windows-by-pid.cpp | 59 -- src/napi/create_window_js.cpp | 152 --- src/napi/get-active-window.cpp | 65 -- src/napi/get-window-by-id.cpp | 71 -- src/napi/get-window-list.cpp | 87 -- src/napi/get-windows-by-className.cpp | 86 -- src/napi/get-windows-by-pid.cpp | 82 -- src/napi/getScreen.cpp | 80 -- src/napi/minimize-window.cpp | 60 -- src/napi/move-resize-window.cpp | 85 -- src/napi/raise-window.cpp | 62 -- src/napi/update-window-state.cpp | 121 --- src/napi/window-move-resize-transition.cpp | 64 -- src/napi/wmctrl-napi.hpp | 77 -- src/napi/wmctrl-utils.cpp | 95 -- src/napi/wmctrl.cpp | 60 -- src/test.ts | 258 ----- src/test/api.test.ts | 161 +++ src/test/x11.test.ts | 459 +++++++++ src/unit-test/active-window-by-Id.ts | 51 - src/unit-test/active-windows-by-className.ts | 52 - src/unit-test/active-windows-by-pid.ts | 51 - src/unit-test/all.ts | 17 - src/unit-test/allow-all-sizes-window.ts | 34 - src/unit-test/closeWindowById.ts | 48 - src/unit-test/closeWindowsByClassName.ts | 18 - src/unit-test/closeWindowsByPid.ts | 18 - src/unit-test/get-active-window.ts | 43 - src/unit-test/get-screen.ts | 46 - src/unit-test/get-windows-by-ClassName.ts | 39 - src/unit-test/get-windows-by-pid.ts | 41 - src/unit-test/minimize-window.ts | 20 - .../move-resize-transition-window.ts | 27 - src/unit-test/move-resize-window.ts | 23 - src/unit-test/raise-window.ts | 25 - src/unit-test/update-window-state.ts | 22 - src/unit-test/utils.ts | 21 - tsconfig.json | 18 +- yarn.lock | 151 ++- 76 files changed, 2854 insertions(+), 6147 deletions(-) delete mode 100644 .github/workflows/c-cpp.yml create mode 100644 .github/workflows/ci.yml delete mode 100644 .npmignore delete mode 100644 binding.gyp delete mode 100644 libwmctrl/Makefile delete mode 100644 libwmctrl/libwmctrl.gyp delete mode 100644 libwmctrl/src/desktop.c delete mode 100644 libwmctrl/src/get-active-window.c delete mode 100644 libwmctrl/src/screen.c delete mode 100644 libwmctrl/src/utils.c delete mode 100644 libwmctrl/src/window-edit.c delete mode 100644 libwmctrl/src/window-manager.c delete mode 100644 libwmctrl/src/window-move-resize-transition.c delete mode 100644 libwmctrl/src/window-move-resize.c delete mode 100644 libwmctrl/src/window-properties.c delete mode 100644 libwmctrl/src/window.c delete mode 100644 libwmctrl/src/wmctrl.h delete mode 100644 libwmctrl/test/test.c create mode 100644 native/.cargo/config.toml create mode 100644 native/Cargo.lock create mode 100644 native/Cargo.toml create mode 100644 native/build.rs create mode 100644 native/examples/fixture.rs create mode 100644 native/src/lib.rs create mode 100644 native/src/wm.rs create mode 100644 scripts/build-native.js delete mode 100644 src/debug.js delete mode 100644 src/napi/active-window-by-id.cpp delete mode 100644 src/napi/active-windows-by-className.cpp delete mode 100644 src/napi/active-windows-by-pid.cpp delete mode 100644 src/napi/allow-all-sizes-window.cpp delete mode 100644 src/napi/close-window-by-id.cpp delete mode 100644 src/napi/close-windows-by-className.cpp delete mode 100644 src/napi/close-windows-by-pid.cpp delete mode 100644 src/napi/create_window_js.cpp delete mode 100644 src/napi/get-active-window.cpp delete mode 100644 src/napi/get-window-by-id.cpp delete mode 100644 src/napi/get-window-list.cpp delete mode 100644 src/napi/get-windows-by-className.cpp delete mode 100644 src/napi/get-windows-by-pid.cpp delete mode 100644 src/napi/getScreen.cpp delete mode 100644 src/napi/minimize-window.cpp delete mode 100644 src/napi/move-resize-window.cpp delete mode 100644 src/napi/raise-window.cpp delete mode 100644 src/napi/update-window-state.cpp delete mode 100644 src/napi/window-move-resize-transition.cpp delete mode 100644 src/napi/wmctrl-napi.hpp delete mode 100644 src/napi/wmctrl-utils.cpp delete mode 100644 src/napi/wmctrl.cpp delete mode 100644 src/test.ts create mode 100644 src/test/api.test.ts create mode 100644 src/test/x11.test.ts delete mode 100644 src/unit-test/active-window-by-Id.ts delete mode 100644 src/unit-test/active-windows-by-className.ts delete mode 100644 src/unit-test/active-windows-by-pid.ts delete mode 100644 src/unit-test/all.ts delete mode 100644 src/unit-test/allow-all-sizes-window.ts delete mode 100644 src/unit-test/closeWindowById.ts delete mode 100644 src/unit-test/closeWindowsByClassName.ts delete mode 100644 src/unit-test/closeWindowsByPid.ts delete mode 100644 src/unit-test/get-active-window.ts delete mode 100644 src/unit-test/get-screen.ts delete mode 100644 src/unit-test/get-windows-by-ClassName.ts delete mode 100644 src/unit-test/get-windows-by-pid.ts delete mode 100644 src/unit-test/minimize-window.ts delete mode 100644 src/unit-test/move-resize-transition-window.ts delete mode 100644 src/unit-test/move-resize-window.ts delete mode 100644 src/unit-test/raise-window.ts delete mode 100644 src/unit-test/update-window-state.ts delete mode 100644 src/unit-test/utils.ts diff --git a/.github/workflows/c-cpp.yml b/.github/workflows/c-cpp.yml deleted file mode 100644 index e323326..0000000 --- a/.github/workflows/c-cpp.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: C/C++ CI - -on: - push: - branches: [ master ] - pull_request: - branches: [ master ] - -jobs: - build: - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v2 - - name: configure - run: ./configure - - name: make - run: make - - name: make check - run: make check - - name: make distcheck - run: make distcheck diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..424992d --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,158 @@ +name: CI + +on: + push: + branches: [master] + tags: ["v*"] + pull_request: + +jobs: + # TypeScript 7's compiler is not built for every target: compile once, test everywhere. + dist: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 22 + - uses: dtolnay/rust-toolchain@stable + with: + components: clippy + - run: yarn install --frozen-lockfile && yarn build + - run: cargo clippy --all-targets -- -D warnings && cargo test --lib + working-directory: native + - uses: actions/upload-artifact@v7 + with: + name: dist + path: dist/ + + # Cross-built with zig against old glibc releases, then tested in a container of the target arch + # (QEMU when it is not the runner's) with Xvfb and openbox. + linux: + needs: dist + runs-on: ${{ matrix.runner || 'ubuntu-24.04' }} + strategy: + fail-fast: false + matrix: + include: + - { dir: linux-x64, target: x86_64-unknown-linux-gnu.2.17, platform: linux/amd64, image: node:22-bookworm-slim } + - { dir: linux-arm64, target: aarch64-unknown-linux-gnu.2.17, platform: linux/arm64, image: node:22-bookworm-slim, runner: ubuntu-24.04-arm } + - { dir: linux-arm, target: armv7-unknown-linux-gnueabihf.2.17, platform: linux/arm/v7, image: node:22-bookworm-slim } + - { dir: linux-ppc64, target: powerpc64le-unknown-linux-gnu.2.19, platform: linux/ppc64le, image: node:22-bookworm-slim } + # No official Node image for these: Debian's own nodejs package. + - { dir: linux-s390x, target: s390x-unknown-linux-gnu.2.17, platform: linux/s390x, image: "debian:trixie-slim" } + - { dir: linux-riscv64, target: riscv64gc-unknown-linux-gnu.2.27, platform: linux/riscv64, image: "debian:trixie-slim" } + - { dir: linux-x64-musl, target: x86_64-unknown-linux-musl, platform: linux/amd64, image: node:22-alpine } + - { dir: linux-arm64-musl, target: aarch64-unknown-linux-musl, platform: linux/arm64, image: node:22-alpine, runner: ubuntu-24.04-arm } + - { dir: linux-arm-musl, target: armv7-unknown-linux-musleabihf, platform: linux/arm/v7, image: node:22-alpine } + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 22 + - uses: dtolnay/rust-toolchain@stable + - uses: mlugg/setup-zig@v2 + with: + version: 0.16.0 # the glibc floors above are what this zig can provide + - uses: taiki-e/install-action@v2 + with: + tool: cargo-zigbuild + - run: node scripts/build-native.js --zig --target ${{ matrix.target }} --dir ${{ matrix.dir }} + - uses: actions/download-artifact@v8 + with: + name: dist + path: dist + - uses: docker/setup-qemu-action@v4 + - run: > + docker run --rm --init --platform ${{ matrix.platform }} -v "$PWD:/repo" -w /repo + -e WMCTRLJS_FIXTURE=fixtures/${{ matrix.dir }}/fixture ${{ matrix.image }} sh -ec ' + if command -v apk; then apk add --no-cache xvfb-run openbox; + else apt-get update && apt-get install -y --no-install-recommends xvfb xauth openbox $(command -v node >/dev/null || echo nodejs); fi; + xvfb-run -a sh -c "openbox & node --test dist/test/*.test.js"' + - uses: actions/upload-artifact@v7 + with: + name: prebuild-${{ matrix.dir }} + path: prebuilds/ + + # Builds and tests in a FreeBSD VM. + freebsd: + needs: dist + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v7 + - uses: actions/download-artifact@v8 + with: + name: dist + path: dist + - uses: vmactions/freebsd-vm@v1.5.9 + with: + usesh: true + prepare: pkg install -y rust node22 xorg-vfbserver openbox + run: | + set -e + node scripts/build-native.js + Xvfb :99 -nolisten tcp & sleep 2 + DISPLAY=:99 openbox & + DISPLAY=:99 WMCTRLJS_FIXTURE=fixtures/freebsd-x64/fixture node --test dist/test/*.test.js + - uses: actions/upload-artifact@v7 + with: + name: prebuild-freebsd-x64 + path: prebuilds/ + + # No X server on these runners: the X11 suite skips itself, the API suite still loads and calls the binary. + others: + needs: dist + runs-on: ${{ matrix.runner }} + strategy: + fail-fast: false + matrix: + include: + - { dir: darwin-arm64, target: aarch64-apple-darwin, runner: macos-latest, node: arm64 } + - { dir: darwin-x64, target: x86_64-apple-darwin, runner: macos-latest, node: x64 } + - { dir: win32-x64, target: x86_64-pc-windows-msvc, runner: windows-latest, node: x64 } + - { dir: win32-ia32, target: i686-pc-windows-msvc, runner: windows-latest, node: x86 } + - { dir: win32-arm64, target: aarch64-pc-windows-msvc, runner: windows-11-arm, node: arm64 } + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 22 + architecture: ${{ matrix.node }} + - uses: dtolnay/rust-toolchain@stable + - run: node scripts/build-native.js --target ${{ matrix.target }} --dir ${{ matrix.dir }} + - uses: actions/download-artifact@v8 + with: + name: dist + path: dist + - run: node --test dist/test/api.test.js dist/test/x11.test.js + - uses: actions/upload-artifact@v7 + with: + name: prebuild-${{ matrix.dir }} + path: prebuilds/ + + publish: + if: startsWith(github.ref, 'refs/tags/v') + needs: [linux, freebsd, others] + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 22 + registry-url: https://registry.npmjs.org + - uses: actions/download-artifact@v8 + with: + name: dist + path: dist + - uses: actions/download-artifact@v8 + with: + pattern: prebuild-* + path: prebuilds + merge-multiple: true + - run: test "$(ls prebuilds/*/wmctrljs.node | wc -l)" -eq 15 + - run: npm publish --provenance --access public + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/.gitignore b/.gitignore index ffd59f1..4bdcee5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,8 @@ node_modules -*.out -*.so -*.o -*.a build .vscode package-lock.json -dist \ No newline at end of file +dist +prebuilds +native/target +fixtures diff --git a/.npmignore b/.npmignore deleted file mode 100644 index ef0c63d..0000000 --- a/.npmignore +++ /dev/null @@ -1,20 +0,0 @@ -tsconfig.json -.vscode -.*.swp -._* -.DS_Store -.git -.hg -.npmrc -.lock-wscript -.svn -.wafpickle-* -config.gypi -CVS -npm-debug.log -node_modules -*.a -*.out -build -dist/unit-test -src/unit-test \ No newline at end of file diff --git a/README.md b/README.md index bdf93eb..6f284dd 100644 --- a/README.md +++ b/README.md @@ -1,27 +1,58 @@ # wmctrljs -Be carefull this package can be use only on a linux X11 machine. +Native window management for Node.js on Linux X11 (works under XWayland too): `wmctrl` and more, without spawning a process. -You also need packages like libx11-dev, libxmu-dev +The native part is written in Rust ([napi-rs](https://napi.rs) + [x11rb](https://github.com/psychon/x11rb)). It talks the X11 protocol directly, so it needs no `libX11`/`libXmu`. Prebuilt binaries for every target below ship inside the npm package, and the right one is picked at runtime. Installing compiles nothing and needs no system packages. -## Update your indexes -`sudo apt update` +| OS | Architectures | Tested in CI | +|----|---------------|--------------| +| Linux, glibc 2.17+ (2.19+ on ppc64le, 2.27+ on riscv64) | x64, arm64, arm (armv7), ppc64le, s390x, riscv64 | full suite against Xvfb + openbox (QEMU for non-native arches) | +| Linux, musl (Alpine) | x64, arm64, arm (armv7) | full suite against Xvfb + openbox | +| FreeBSD | x64 | full suite against Xvfb + openbox, in a VM | +| macOS (XQuartz) | x64, arm64 | API suite only (no X server on the runners) | +| Windows (an X server such as VcXsrv, `DISPLAY=host:0`) | x64, ia32, arm64 | API suite only | -## Install your unbuntu packages -`sudo apt install libx11-dev -y` - -`sudo apt install libxmu-dev -y` - -## Install wmctrljs package +## Install `npm install wmctrljs` ## Description -Wmctrljs is an adaptation of wmctrl command and more, with that library you can easily manage your windows very fastly beacause wmctrls does'nt make a fork of wmctrl process but directly call X11 library using N-API. +Every function exists in two flavours: `xxxSync` runs on the calling thread, `xxx` returns a promise and runs on the libuv thread pool. + +Errors are `Error` objects whose message looks like `[functionName] NO_WINDOW_FOUND (24)`. + +## Upgrading from 1.x -To do that wmctrls has access to an addon natif using `N-API` for scalability between nodejs version. +The JS API is unchanged. The behaviour changes below are fixes: -An implementation of async/IO is available, then it is possible to call each function on a `V8` different thread wich will highly improve performance results +- No system packages are needed anymore (`libx11-dev`, `libxmu-dev`, node-gyp, a C++ compiler). +- Promises now reject with `Error` objects instead of strings. The message is the same. +- `getWindowsByPid*` / `getWindowsByClassName*` return `[]` when nothing matches instead of throwing `NO_WINDOW_FOUND`. Their windows now include `frame_extents`, and `getWindowsByPid(0)` no longer matches windows that have no pid. +- `closeWindowsByPidSync` / `closeWindowsByClassNameSync` return `true` on success. They used to throw even when they worked. +- Windows now carry `win_icon_name` (it was declared but never set). The `Aspect` type now says `numerator` / `denominator`, which is what was always returned. +- `windowMoveResizeTransition` really animates y (it used to step it with x) and starts from the window's absolute position. +- The 1.x C addon double-freed memory in `getActiveWindow()` and could crash the process. That is gone. + +## Development + +Requirements: Node.js 18+, a Rust toolchain, and for tests an X server with an EWMH window manager (for example `xvfb` + `openbox`). + +```sh +yarn install +yarn build:native # cargo build -> prebuilds/-/wmctrljs.node (+ the test fixture window) +yarn build # TypeScript 7 +xvfb-run -a sh -c 'openbox & yarn test' +cd native && cargo test --lib # Rust unit tests, no X server needed +``` + +Cross builds use [cargo-zigbuild](https://github.com/rust-cross/cargo-zigbuild) (and zig): `node scripts/build-native.js --zig --target aarch64-unknown-linux-gnu.2.17 --dir linux-arm64`. + +Three suites guard against regressions: +- Rust unit tests: property decoding, window JSON, size hints, gravity flags, transitions, error codes. +- `api.test`: exports, argument validation and error messages of every function, and the binary loader. Runs without X. +- `x11.test`: every function against a real window manager. It spawns its own fixture windows (`native/examples/fixture.rs`) and only ever acts on those. It is skipped when `DISPLAY` is unset. + +CI builds and tests the 15 targets above, and publishes to npm when a `v*` tag is pushed. ## Window @@ -43,6 +74,7 @@ interface Window { win_geometry:Geometry|undefined; wm_normal_hints_supplied:number; + wm_hints_supplied:number; WM_NORMAL_HINTS:XSizeHints|undefined; WM_HINTS:XSizeHints|undefined; desktop_number:number; @@ -74,6 +106,13 @@ interface Geometry { ``` wmctrljs also provide you XSizeHints propertis based on Xutils.h structure. +```TS +interface Aspect { + numerator:number + denominator:number +} +``` + ```TS interface XSizeHints { //Based on Xutils.h flags:number /* marks which fields in this structure are defined */ @@ -152,13 +191,13 @@ function getActiveWindowSync():Window function getActiveWindow():Promise ``` -Get a list of window with the pid provided, if this pid doesn't match with any window a not found exception is throw +Get a list of window with the pid provided, an empty list if no window matches ```TS function getWindowsByPidSync(win_pid:number):Window[] function getWindowsByPid(win_pid:number):Promise ``` -Get a list of window with the class provided, it has the same issue as `getWindowsByPidSync` +Get a list of window with the class provided (`instance.Class`, e.g. `xeyes.XEyes`), an empty list if no window matches ```TS function getWindowsByClassNameSync(win_class_name:string):Window[] function getWindowsByClassName(win_class_name:string):Promise @@ -206,7 +245,7 @@ function windowMoveResizeTransition(win_id:number, win_gravity:number, win_x:num ``` Here the `await_time` is the duration between all window's positions and dimensions, and `pad` allow you to control the number of step it will have. -Because of the duration of this animation it is available only with an `AsyncWorker`. +Because of the duration of this animation it is only available as a promise. Make some action on window's states diff --git a/binding.gyp b/binding.gyp deleted file mode 100644 index 0561b8c..0000000 --- a/binding.gyp +++ /dev/null @@ -1,22 +0,0 @@ -{ - "targets":[ - { - "target_name":"wmctrl", - "cflags!": [ "-fno-exceptions" ], - "cflags_cc!": [ "-fno-exceptions" ], - "sources": [ - " `./src/napi/${f}`).join(` `)')" - ], - "include_dirs": [ - " `./src/${f}`).join(` `)')" - ] - }] - ] - } - ] -} \ No newline at end of file diff --git a/libwmctrl/src/desktop.c b/libwmctrl/src/desktop.c deleted file mode 100644 index db82949..0000000 --- a/libwmctrl/src/desktop.c +++ /dev/null @@ -1,261 +0,0 @@ -#include "./wmctrl.h" - -/** - * state = 1 ON - * state = 0 OFF - * **/ -int showing_desktop (Display *disp, unsigned long state) { - return client_msg(disp, DefaultRootWindow(disp), "_NET_SHOWING_DESKTOP", - state, 0, 0, 0, 0); -} - -//_NET_CURRENT_DESKTOP -int switch_desktop (Display *disp, unsigned long target) { - return client_msg(disp, DefaultRootWindow(disp), "_NET_CURRENT_DESKTOP", target, 0, 0, 0, 0); -} -/* -static int longest_str (gchar **strv) { - size_t max = 0; - size_t i = 0; - - while (strv && strv[i]) { - if (strlen(strv[i]) > max) { - max = strlen(strv[i]); - } - i++; - } - - return max; -}*/ - -//_NET_NUMBER_OF_DESKTOPS -int change_number_of_desktops (Display *disp, unsigned long n) { - return client_msg(disp, DefaultRootWindow(disp), "_NET_NUMBER_OF_DESKTOPS", - n, 0, 0, 0, 0); -} -/* -int list_desktops (Display *disp) { - unsigned long *num_desktops = NULL; - unsigned long *cur_desktop = NULL; - unsigned long desktop_list_size = 0; - unsigned long *desktop_geometry = NULL; - unsigned long desktop_geometry_size = 0; - gchar **desktop_geometry_str = NULL; - unsigned long *desktop_viewport = NULL; - unsigned long desktop_viewport_size = 0; - gchar **desktop_viewport_str = NULL; - unsigned long *desktop_workarea = NULL; - unsigned long desktop_workarea_size = 0; - gchar **desktop_workarea_str = NULL; - gchar *list = NULL; - unsigned long i; - unsigned long id; - Window root = DefaultRootWindow(disp); - int ret = EXIT_FAILURE; - gchar **names = NULL; - - if (! (num_desktops = (unsigned long *)get_property(disp, root, - XA_CARDINAL, "_NET_NUMBER_OF_DESKTOPS", NULL))) { - if (! (num_desktops = (unsigned long *)get_property(disp, root, - XA_CARDINAL, "_WIN_WORKSPACE_COUNT", NULL))) { - fputs("Cannot get number of desktops properties. " - "(_NET_NUMBER_OF_DESKTOPS or _WIN_WORKSPACE_COUNT)" - "\n", stderr); - goto cleanup; - } - } - - if (! (cur_desktop = (unsigned long *)get_property(disp, root, - XA_CARDINAL, "_NET_CURRENT_DESKTOP", NULL))) { - if (! (cur_desktop = (unsigned long *)get_property(disp, root, - XA_CARDINAL, "_WIN_WORKSPACE", NULL))) { - fputs("Cannot get current desktop properties. " - "(_NET_CURRENT_DESKTOP or _WIN_WORKSPACE property)" - "\n", stderr); - goto cleanup; - } - } - - if ((list = get_property(disp, root, - XInternAtom(disp, "UTF8_STRING", False), - "_NET_DESKTOP_NAMES", &desktop_list_size)) == NULL) { - if ((list = get_property(disp, root, - XA_STRING, - "_WIN_WORKSPACE_NAMES", &desktop_list_size)) == NULL) { - printf("Cannot get desktop names properties. " - "(_NET_DESKTOP_NAMES or _WIN_WORKSPACE_NAMES)" - "\n"); - // ignore the error - list the desktops without names - } - } - - // common size of all desktops - if (! (desktop_geometry = (unsigned long *)get_property(disp, DefaultRootWindow(disp), - XA_CARDINAL, "_NET_DESKTOP_GEOMETRY", &desktop_geometry_size))) { - printf("Cannot get common size of all desktops (_NET_DESKTOP_GEOMETRY).\n"); - } - - // desktop viewport - if (! (desktop_viewport = (unsigned long *)get_property(disp, DefaultRootWindow(disp), - XA_CARDINAL, "_NET_DESKTOP_VIEWPORT", &desktop_viewport_size))) { - printf("Cannot get common size of all desktops (_NET_DESKTOP_VIEWPORT).\n"); - } - - // desktop workarea - if (! (desktop_workarea = (unsigned long *)get_property(disp, DefaultRootWindow(disp), - XA_CARDINAL, "_NET_WORKAREA", &desktop_workarea_size))) { - if (! (desktop_workarea = (unsigned long *)get_property(disp, DefaultRootWindow(disp), - XA_CARDINAL, "_WIN_WORKAREA", &desktop_workarea_size))) { - printf("Cannot get _NET_WORKAREA property.\n"); - } - } - - // prepare the array of desktop names - names = g_malloc0(*num_desktops * sizeof(char *)); - if (list) { - id = 0; - names[id++] = list; - for (i = 0; i < desktop_list_size; i++) { - if (list[i] == '\0') { - if (id >= *num_desktops) { - break; - } - names[id++] = list + i + 1; - } - } - } - - // prepare desktop geometry strings - desktop_geometry_str = g_malloc0((*num_desktops + 1) * sizeof(char *)); - if (desktop_geometry && desktop_geometry_size > 0) { - if (desktop_geometry_size == 2 * sizeof(*desktop_geometry)) { - // only one value - use it for all desktops - printf("WM provides _NET_DESKTOP_GEOMETRY value common for all desktops.\n"); - for (i = 0; i < *num_desktops; i++) { - desktop_geometry_str[i] = g_strdup_printf("%lux%lu", - desktop_geometry[0], desktop_geometry[1]); - } - } - else { - // seperate values for desktops of different size - printf("WM provides separate _NET_DESKTOP_GEOMETRY value for each desktop.\n"); - for (i = 0; i < *num_desktops; i++) { - if (i < desktop_geometry_size / sizeof(*desktop_geometry) / 2) { - desktop_geometry_str[i] = g_strdup_printf("%lux%lu", - desktop_geometry[i*2], desktop_geometry[i*2+1]); - } - else { - desktop_geometry_str[i] = g_strdup("N/A"); - } - } - } - } - else { - for (i = 0; i < *num_desktops; i++) { - desktop_geometry_str[i] = g_strdup("N/A"); - } - } - - // prepare desktop viewport strings - desktop_viewport_str = g_malloc0((*num_desktops + 1) * sizeof(char *)); - if (desktop_viewport && desktop_viewport_size > 0) { - if (desktop_viewport_size == 2 * sizeof(*desktop_viewport)) { - // only one value - use it for current desktop - printf("WM provides _NET_DESKTOP_VIEWPORT value only for the current desktop.\n"); - for (i = 0; i < *num_desktops; i++) { - if (i == *cur_desktop) { - desktop_viewport_str[i] = g_strdup_printf("%lu,%lu", - desktop_viewport[0], desktop_viewport[1]); - } - else { - desktop_viewport_str[i] = g_strdup("N/A"); - } - } - } - else { - // seperate values for each of desktops - for (i = 0; i < *num_desktops; i++) { - if (i < desktop_viewport_size / sizeof(*desktop_viewport) / 2) { - desktop_viewport_str[i] = g_strdup_printf("%lu,%lu", - desktop_viewport[i*2], desktop_viewport[i*2+1]); - } - else { - desktop_viewport_str[i] = g_strdup("N/A"); - } - } - } - } - else { - for (i = 0; i < *num_desktops; i++) { - desktop_viewport_str[i] = g_strdup("N/A"); - } - } - - // prepare desktop workarea strings - desktop_workarea_str = g_malloc0((*num_desktops + 1) * sizeof(char *)); - if (desktop_workarea && desktop_workarea_size > 0) { - if (desktop_workarea_size == 4 * sizeof(*desktop_workarea)) { - // only one value - use it for current desktop - printf("WM provides _NET_WORKAREA value only for the current desktop.\n"); - for (i = 0; i < *num_desktops; i++) { - if (i == *cur_desktop) { - desktop_workarea_str[i] = g_strdup_printf("%lu,%lu %lux%lu", - desktop_workarea[0], desktop_workarea[1], - desktop_workarea[2], desktop_workarea[3]); - } - else { - desktop_workarea_str[i] = g_strdup("N/A"); - } - } - } - else { - // seperate values for each of desktops - for (i = 0; i < *num_desktops; i++) { - if (i < desktop_workarea_size / sizeof(*desktop_workarea) / 4) { - desktop_workarea_str[i] = g_strdup_printf("%lu,%lu %lux%lu", - desktop_workarea[i*4], desktop_workarea[i*4+1], - desktop_workarea[i*4+2], desktop_workarea[i*4+3]); - } - else { - desktop_workarea_str[i] = g_strdup("N/A"); - } - } - } - } - else { - for (i = 0; i < *num_desktops; i++) { - desktop_workarea_str[i] = g_strdup("N/A"); - } - } - - // print the list - for (i = 0; i < *num_desktops; i++) { - gchar *out = get_output_str(names[i]); - printf("%-2d %c DG: %-*s VP: %-*s WA: %-*s %s\n", i, i == *cur_desktop ? '*' : '-', - longest_str(desktop_geometry_str), desktop_geometry_str[i], - longest_str(desktop_viewport_str), desktop_viewport_str[i], - longest_str(desktop_workarea_str), desktop_workarea_str[i], - out ? out : "N/A"); - g_free(out); - } - - printf("Total number of desktops: %lu\n", *num_desktops); - printf("Current desktop ID (counted from zero): %lu\n", *cur_desktop); - - ret = EXIT_SUCCESS; - goto cleanup; - -cleanup: - g_free(names); - g_free(num_desktops); - g_free(cur_desktop); - g_free(desktop_geometry); - g_strfreev(desktop_geometry_str); - g_free(desktop_viewport); - g_strfreev(desktop_viewport_str); - g_free(desktop_workarea); - g_strfreev(desktop_workarea_str); - g_free(list); - - return ret; -}*/ \ No newline at end of file diff --git a/libwmctrl/src/get-active-window.c b/libwmctrl/src/get-active-window.c deleted file mode 100644 index 15d1c20..0000000 --- a/libwmctrl/src/get-active-window.c +++ /dev/null @@ -1,43 +0,0 @@ -#include "wmctrl.h" - -struct window_info *get_active_window(Display *disp, enum STATES *st) { - char *prop; - unsigned long size; - Window ret = (Window)0; - bool displayProvided = true; - struct window_info *wi = NULL; - - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) { - *st = CAN_NOT_OPEN_DISPLAY; - return NULL; - } - - prop = get_property(disp, DefaultRootWindow(disp), XA_WINDOW, - "_NET_ACTIVE_WINDOW", &size); - - if (prop) { - ret = *((Window*)prop); - if (ret) { - wi = create_window_info(disp, ret, NULL); - if (!wi) - *st = CAN_NOT_ALLOCATE_MEMORY; - *st = CLIENT_LIST_GET; - } - else - *st = NO_WINDOW_ACTIVE_FOR_NOW; - - free(prop); - } - else { - *st = CAN_NOT_ACTIVATE_WINDOW; - } - - if (!displayProvided) - XCloseDisplay(disp); - return wi; -} \ No newline at end of file diff --git a/libwmctrl/src/screen.c b/libwmctrl/src/screen.c deleted file mode 100644 index 18a9c75..0000000 --- a/libwmctrl/src/screen.c +++ /dev/null @@ -1,20 +0,0 @@ -#include "wmctrl.h" - -Screen *get_screen(Display *disp, enum STATES *st) { - if (!disp) - disp = XOpenDisplay(NULL); - - if (!disp) { - *st = CAN_NOT_OPEN_DISPLAY; - return NULL; - } - - Screen *sc = DefaultScreenOfDisplay(disp); - *st = SCREEN_GET; - - return sc; -} - -void free_screen(Screen *sc) { - XCloseDisplay(sc->display); -} \ No newline at end of file diff --git a/libwmctrl/src/utils.c b/libwmctrl/src/utils.c deleted file mode 100644 index 41492ab..0000000 --- a/libwmctrl/src/utils.c +++ /dev/null @@ -1,741 +0,0 @@ -#include "./wmctrl.h" - -bool init_wmctrl_lib() { - XInitThreads(); - XSetErrorHandler(handler_x11_error); - return true; -} - -void free_window_cache(struct window_cache *wc) { - if (wc->win_class) - free(wc->win_class); - free(wc); -} - -void free_window_cache_list(struct window_cache_list *wcl) { - struct window_cache *heap = wcl->heap; - struct window_cache *tmp; - while (heap) { - tmp = heap; - heap = heap->next; - free_window_cache(tmp); - } - free(wcl); -} - -struct window_cache_list *init_window_list_cache() { - struct window_cache_list *wcl = malloc(sizeof(struct window_cache_list)); - - if (!wcl) - return NULL; - - wcl->heap = NULL; - wcl->size = 0; - - return wcl; -} - -struct window_cache *init_window_cache(Window win, const char *win_class, unsigned long win_pid) { - struct window_cache *wc = malloc(sizeof(struct window_cache)); - if (!wc) - return NULL; - - wc->win_id = win; - wc->win_class = win_class ? strdup(win_class) : NULL; - wc->win_pid = win_pid ? win_pid : 0; - wc->dead_time = clock(); - wc->next = NULL; - - return wc; -} - -struct window_cache *get_window_cache_by_id(struct window_cache_list *wcl, Window win) { - struct window_cache *wc = NULL; - - if (!wcl->heap) - return NULL; - - wc = wcl->heap; - - while (wc) { - if (wc->win_id == win) - return wc; - wc = wc->next; - } - - return NULL; -} - -void add_window_cache(struct window_cache_list *wcl, Window win, const char *win_class, unsigned long win_pid) { - struct window_cache *heap; - struct window_cache *wc; - - if (!wcl) - return; - - if (!wcl->heap) { - wcl->heap = init_window_cache(win, win_class, win_pid); - if (!wcl->heap) - return; - wcl->size++; - return; - } - - wc = init_window_cache(win, win_class, win_pid); - if (!wc) - return; - - heap = wcl->heap; - while (heap->next) { - - if (heap->win_id == win) { - - if (!heap->win_class && win_class) - heap->win_class = strdup(win_class); - - if (!heap->win_pid && win_pid) - heap->win_pid = win_pid; - - return; - } - heap = heap->next; - } - - heap->next = wc; - wcl->size++; -} - -int handler_x11_error(Display *d, XErrorEvent *e) { - return 0; -} - -char *get_error_message(enum STATES st) { - char msg[512]; - switch (st) { - case CAN_NOT_OPEN_DISPLAY: - sprintf(msg, "CAN_NOT_OPEN_DISPLAY (%d)", st); - break; - case CAN_NOT_CLOSE_DISPLAY: - sprintf(msg, "CAN_NOT_CLOSE_DISPLAY (%d)", st); - break; - case CAN_NOT_ACTIVATE_WINDOW: - sprintf(msg, "CAN_NOT_ACTIVATE_WINDOW (%d)", st); - break; - case CAN_NOT_CHANGE_VIEWPORT: - sprintf(msg, "CAN_NOT_CHANGE_VIEWPORT (%d)", st); - break; - case CAN_NOT_CHANGE_GEOMETRY: - sprintf(msg, "CAN_NOT_CHANGE_GEOMETRY (%d)", st); - break; - case CAN_NOT_CLOSE_WINDOW: - sprintf(msg, "CAN_NOT_CLOSE_WINDOW (%d)", st); - break; - case CAN_NOT_SET_WINDOW_ICON_NAME: - sprintf(msg, "CAN_NOT_SET_WINDOW_ICON_NAME (%d)", st); - break; - case CAN_NOT_SET_WINDOW_TITLE: - sprintf(msg, "CAN_NOT_SET_WINDOW_TITLE (%d)", st); - break; - case CAN_NOT_SET_WINDOW_STATE: - sprintf(msg, "CAN_NOT_SET_WINDOW_STATE (%d)", st); - break; - case NO_WINDOW_FOUND: - sprintf(msg, "NO_WINDOW_FOUND (%d)", st); - break; - case CAN_NOT_MOVE_RESIZE_WINDOW: - sprintf(msg, "CAN_NOT_MOVE_RESIZE_WINDOW (%d)", st); - break; - case NO_WINDOW_ACTIVE_FOR_NOW: - sprintf(msg, "NO_WINDOW_ACTIVE_FOR_NOW (%d)", st); - break; - case TOO_MANY_WINDOW_OPENED: - sprintf(msg, "TOO_MANY_WINDOW_OPENED (%d)", st); - break; - case CAN_NOT_MINIMIZE_WINDOW: - sprintf(msg, "CAN_NOT_MINIMIZE_WINDOW (%d)", st); - break; - case CAN_NOT_GET_WINDOW_ATTRIBUTES: - sprintf(msg, "CAN_NOT_GET_WINDOW_ATTRIBUTES (%d)", st); - break; - default: - sprintf(msg, "Unexpected error (%d)", st); - break; - } - return strdup(msg); -} - -void initializeWindowInfo(struct window_info *wi) { - if (!wi) { - return; - } - - wi->win_client_machine = NULL; - wi->win_class = NULL; - wi->win_types = NULL; - wi->win_actions = NULL; - wi->win_states = NULL; - wi->win_name = NULL; - wi->win_visible_name = NULL; - wi->win_icon_name = NULL; - wi->win_visible_icon_name = NULL; - wi->win_geometry = NULL; - wi->net_wm_strut = NULL; - wi->WM_NORMAL_HINTS = NULL; - wi->WM_HINTS = NULL; - wi->frame_extents = NULL; - - wi->win_id = 0; - wi->win_pid = 0; - wi->desktop_number = 0; - wi->showing_desktop = 0; - wi->nbr_type = 0; - wi->nbr_action = 0; - wi->nbr_state = 0; - wi->wm_normal_hints_supplied = 0; - wi->wm_hints_supplied = 0; - wi->nbr_net_wm_strut = 0; -} - -struct window_info *create_empty_window_info() { - struct window_info *wi = malloc(sizeof(struct window_info)); - if (!wi) { - return NULL; - } - - initializeWindowInfo(wi); - return wi; -} - -struct window_info *create_window_info(Display *disp, Window win, enum STATES *st) { - struct window_info *wi; - bool displayProvided = true; - - if (!disp) { - disp = XOpenDisplay(NULL); - if (!disp) { - if (st) - *st = CAN_NOT_OPEN_DISPLAY; - } - displayProvided = false; - } - - wi = create_empty_window_info(); - if (!wi) { - *st = NO_WINDOW_FOUND; - return NULL; - } - - fill_window_info(disp, wi, win); - - if (!displayProvided) { - XCloseDisplay(disp); - } - - if (st) - *st = WINDOW_PROPERTY_GET; - - return wi; -} - -void fill_window_info(Display *disp, struct window_info *wi, Window win) { - if (!disp || !wi) { - return; - } - - wi->win_id = win; - wi->win_pid = get_window_pid(disp, win); - wi->desktop_number = get_window_desktop(disp, win); - wi->showing_desktop = get_window_shwing_desktop(disp, win); - wi->win_client_machine = get_window_client_machine(disp, win); - wi->win_class = get_window_class(disp, win); - wi->win_types = get_window_types(disp, win, &wi->nbr_type); - wi->win_actions = get_window_allowed_actions(disp, win, &wi->nbr_action); - wi->win_states = get_window_states(disp, win, &wi->nbr_state); - wi->win_name = get_window_name(disp, win); - wi->win_visible_name = get_window_visible_name(disp, win); - wi->win_icon_name = get_window_icon_name(disp, win); - wi->win_visible_icon_name = get_window_visible_icon_name(disp, win); - wi->win_geometry = get_window_geometry(disp, win); - wi->frame_extents = get_window_frame_extents(disp, win); - wi->WM_NORMAL_HINTS = XAllocSizeHints(); - XGetWMNormalHints(disp, win, wi->WM_NORMAL_HINTS, &wi->wm_normal_hints_supplied); - wi->WM_HINTS = XAllocSizeHints(); - - //XGetWMSizeHints(disp, win, wi->WM_HINTS, &wi->wm_hints_supplied, PAllHints); - //wi->net_wm_strut = get_window_net_wm_strut(disp, win, &wi->nbr_net_wm_strut); -} - -void copy_window_info(struct window_info *dest_wi, struct window_info *src_wi) { - dest_wi->win_id = src_wi->win_id; - dest_wi->win_pid = src_wi->win_pid; - dest_wi->desktop_number = src_wi->desktop_number; - dest_wi->showing_desktop = src_wi->showing_desktop; - - dest_wi->win_client_machine = src_wi->win_client_machine ? strdup(src_wi->win_client_machine) : NULL; - dest_wi->win_class = src_wi->win_class ? strdup(src_wi->win_class) : NULL; - - if (src_wi->win_types) { - size_t size = sizeof(struct type_desc) * src_wi->nbr_type; - dest_wi->win_types = malloc(size); - if (dest_wi->win_types) { - for (size_t i = 0; i < src_wi->nbr_type; i++) { - struct type_desc *win_types = dest_wi->win_types + i; - win_types->flag = strdup((src_wi->win_types+i)->flag); - win_types->number = (src_wi->win_types+i)->number; - } - dest_wi->nbr_type = src_wi->nbr_type; - } - } - else { - dest_wi->win_types = NULL; - } - - if (src_wi->win_actions) { - size_t size = sizeof(struct action_desc) * src_wi->nbr_action; - dest_wi->win_actions = malloc(size); - if (dest_wi->win_actions) { - for (size_t i = 0; i < src_wi->nbr_action; i++) { - struct action_desc *win_actions = dest_wi->win_actions + i; - win_actions->flag = strdup((src_wi->win_actions+i)->flag); - win_actions->number = (src_wi->win_actions+i)->number; - } - dest_wi->nbr_action = src_wi->nbr_action; - } - } - else { - dest_wi->win_actions = NULL; - } - - if (src_wi->win_states) { - size_t size = sizeof(struct state_desc) * src_wi->nbr_state; - dest_wi->win_states = malloc(size); - if (dest_wi->win_states) { - for (size_t i = 0; i < src_wi->nbr_state; i++) { - struct state_desc *win_states = dest_wi->win_states + i; - win_states->flag = strdup((src_wi->win_states+i)->flag); - win_states->number = (src_wi->win_states+i)->number; - } - dest_wi->nbr_state = src_wi->nbr_state; - } - } - else { - dest_wi->win_states = NULL; - } - - dest_wi->win_name = src_wi->win_name ? strdup(src_wi->win_name) : NULL; - dest_wi->win_visible_name = src_wi->win_visible_name ? strdup(src_wi->win_visible_name) : NULL; - dest_wi->win_icon_name = src_wi->win_icon_name ? strdup(src_wi->win_icon_name) : NULL; - dest_wi->win_visible_icon_name = src_wi->win_visible_icon_name ? strdup(src_wi->win_visible_icon_name) : NULL; - - if (src_wi->win_geometry) { - dest_wi->win_geometry = malloc(sizeof(struct geometry)); - if (dest_wi->win_geometry) { - memcpy(dest_wi->win_geometry, src_wi->win_geometry, sizeof(struct geometry)); - } - } - else { - dest_wi->win_geometry = NULL; - } - if (src_wi->WM_NORMAL_HINTS) { - XSizeHints *sh = XAllocSizeHints(); - memcpy(sh, src_wi->WM_NORMAL_HINTS, sizeof(XSizeHints)); - dest_wi->WM_NORMAL_HINTS = sh; - } - else { - dest_wi->WM_NORMAL_HINTS = NULL; - } - - dest_wi->wm_normal_hints_supplied = src_wi->wm_normal_hints_supplied; - - if (src_wi->WM_HINTS) { - XSizeHints *sh = XAllocSizeHints(); - memcpy(sh, src_wi->WM_HINTS, sizeof(XSizeHints)); - dest_wi->WM_HINTS = sh; - } - else - dest_wi->WM_HINTS = NULL; - dest_wi->wm_hints_supplied = src_wi->wm_hints_supplied; - if (src_wi->net_wm_strut) { - size_t size = sizeof(Atom) * src_wi->nbr_net_wm_strut; - dest_wi->net_wm_strut = malloc(size); - if (dest_wi->net_wm_strut) { - memcpy(dest_wi->net_wm_strut, src_wi->net_wm_strut, size); - dest_wi->nbr_net_wm_strut = src_wi->nbr_net_wm_strut; - } - } -} - -void free_window_info_properties(struct window_info *wi) { - if (!wi) { - return; - } - - if (wi->win_client_machine) { - free(wi->win_client_machine); - wi->win_client_machine = NULL; - } - - if (wi->win_class) { - free(wi->win_class); - wi->win_class = NULL; - } - - if (wi->win_types) { - for (size_t i = 0; i < wi->nbr_type; i++) { - struct type_desc *desc = (wi->win_types + i); - char *flag = desc->flag; - if (flag) { - free(flag); - } - } - free(wi->win_types); - wi->win_types = NULL; - } - - if (wi->win_actions) { - for (size_t i = 0; i < wi->nbr_action; i++) { - struct action_desc* desc = wi->win_actions + i; - if (desc) { - char *flag = desc->flag; - if (flag) { - free(flag); - } - } - } - free(wi->win_actions); - wi->win_actions = NULL; - } - - if (wi->win_states) { - for (size_t i = 0; i < wi->nbr_state; i++) { - struct state_desc *desc = (wi->win_states + i); - if (desc) { - char *flag = desc->flag; - if (flag) { - free(flag); - } - } - } - free(wi->win_states); - wi->win_states = NULL; - } - - if (wi->win_name) { - free(wi->win_name); - wi->win_name = NULL; - } - - if (wi->win_visible_name) { - free(wi->win_visible_name); - wi->win_visible_name = NULL; - } - - if (wi->win_icon_name) { - free(wi->win_icon_name); - wi->win_icon_name = NULL; - } - - if (wi->win_visible_icon_name) { - free(wi->win_visible_icon_name); - wi->win_visible_icon_name = NULL; - } - - if (wi->win_geometry) { - free(wi->win_geometry); - wi->win_geometry = NULL; - } - - if (wi->WM_NORMAL_HINTS) { - XFree(wi->WM_NORMAL_HINTS); - wi->WM_NORMAL_HINTS = NULL; - } - - if (wi->WM_HINTS) { - XFree(wi->WM_HINTS); - wi->WM_HINTS = NULL; - } - - if (wi->net_wm_strut) { - free(wi->net_wm_strut); - wi->net_wm_strut = NULL; - } - - if (wi->frame_extents) { - free(wi->frame_extents); - wi->frame_extents = NULL; - } -} - -void free_window_info(struct window_info *wi) { - if (!wi) { - return; - } - free_window_info_properties(wi); - free(wi); -} - -static struct window_list *create_window_list(Display *disp, Window *windows, size_t size) { - Window win = 0; - struct window_info *wi; - struct window_list *wl; - - if (!windows) { - return NULL; - } - - wl = malloc(sizeof(struct window_list)); - if (!wl) { - return NULL; - } - - wl->client_list = malloc(sizeof(struct window_info) * size); - if (!wl->client_list) { - free(wl); - return NULL; - } - - for (size_t i = 0; i < size; i++) { - win = windows[i]; - wi = wl->client_list + i; - initializeWindowInfo(wi); - fill_window_info(disp, wi, win); - } - - wl->client_list_size = size; - return wl; -} - -struct window_list *list_windows(Display *disp, enum STATES *st) { - Window *client_list; - size_t client_list_size; - struct window_list *wl; - bool displayProvided = true; - - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) { - if (st) { - *st = CAN_NOT_OPEN_DISPLAY; - } - return NULL; - } - - client_list = get_client_list(disp, &client_list_size); - if (client_list == NULL) { - if (st) { - *st = CAN_NOT_GET_CLIENT_LIST; - } - return NULL; - } - - client_list_size /= sizeof(Window); - wl = create_window_list(disp, client_list, client_list_size); - - if (!wl) { - if (st) { - *st = CAN_NOT_ALLOCATE_MEMORY; - } - return NULL; - } - free(client_list); - - if (st) { - *st = CLIENT_LIST_GET; - } - - if (!displayProvided) { - XCloseDisplay(disp); - } - - return wl; -} - -void free_window_list(struct window_list *wl) { - if (!wl) { - return; - } - - for (size_t i = 0;i < wl->client_list_size; i++) { - free_window_info_properties(wl->client_list + i); - } - - if (wl->client_list) { - free(wl->client_list); - } - - free(wl); -} - -void print_window_info(struct window_info *wi) { - printf("\n"); - printf("| WIN_ID: %ld\n", wi->win_id); - - if (wi->win_pid) - printf("| Pid: %ld\n", wi->win_pid); - - if (wi->win_class) - printf("| Class: %s\n", wi->win_class); - - if (wi->win_name) - printf("| Name: %s\n", wi->win_name); - - if (wi->win_visible_name) - printf("| Visible_NAME: %s\n", wi->win_visible_name); - - if (wi->win_icon_name) - printf("| ICON_NAME:%s\n", wi->win_icon_name); - - if (wi->win_visible_icon_name) - printf("| VISIBLE_ICON_NAME:%s\n", wi->win_visible_icon_name); - - if (wi->desktop_number) - printf("| Desktop: %ld\n", wi->desktop_number); - - if (wi->nbr_type > 0) { - printf("| Types: %ld\n", wi->nbr_type); - for (size_t i = 0; i < wi->nbr_type; i++) { - char *flag = (wi->win_types+i)->flag; - Atom number = (wi->win_types+i)->number; - printf("| \t%s:%ld\n", flag, number); - } - } - - if (wi->nbr_action > 0) { - printf("| Allowed actions: %ld\n", wi->nbr_action); - for (size_t i = 0; i < wi->nbr_action; i++) { - char *flag = (wi->win_actions+i)->flag; - Atom number = (wi->win_actions+i)->number; - printf("| \t%s:%ld\n", flag, number); - } - } - - if (wi->nbr_state > 0) { - printf("| States: %ld\n", wi->nbr_state); - for (size_t i = 0; i < wi->nbr_state; i++) { - char *flag = (wi->win_states+i)->flag; - Atom number = (wi->win_states+i)->number; - printf("| \t%s:%ld\n", flag, number); - } - } - - if( wi->win_client_machine) - printf("| CLIENT_MACHINE: %s\n", wi->win_client_machine); - - if (wi->win_geometry) { - printf("| Geometry: \n"); - printf("| \twidth: %d\n", wi->win_geometry->width); - printf("| \theight: %d\n", wi->win_geometry->height); - printf("| \tx: %d\n", wi->win_geometry->x); - printf("| \ty: %d\n", wi->win_geometry->y); - } - - if (wi->WM_NORMAL_HINTS) { - printf("| WM_NORMAL_HINTS: \n"); - printf("| \twin_gravity: %d\n", wi->WM_NORMAL_HINTS->win_gravity); - printf("| \theight: %d\n", wi->WM_NORMAL_HINTS->height); - printf("| \twidth: %d\n", wi->WM_NORMAL_HINTS->width); - printf("| \tx: %d\n", wi->WM_NORMAL_HINTS->x); - printf("| \ty: %d\n", wi->WM_NORMAL_HINTS->y); - printf("| \tbase_width: %d\n", wi->WM_NORMAL_HINTS->base_width); - printf("| \tbase_height: %d\n", wi->WM_NORMAL_HINTS->base_height); - printf("| \tmin_width: %d\n", wi->WM_NORMAL_HINTS->min_width); - printf("| \tmin_height: %d\n", wi->WM_NORMAL_HINTS->min_height); - printf("| \tmin_aspect:\n"); - printf("| \t\tnumerator:%d\n", wi->WM_NORMAL_HINTS->min_aspect.x); - printf("| \t\tdenominator:%d\n", wi->WM_NORMAL_HINTS->min_aspect.y); - printf("| \tmax_width: %d\n", wi->WM_NORMAL_HINTS->max_width); - printf("| \tmax_height: %d\n", wi->WM_NORMAL_HINTS->max_height); - printf("| \tmax_aspect:\n"); - printf("| \t\tnumerator:%d\n", wi->WM_NORMAL_HINTS->max_aspect.x); - printf("| \t\tdenominator:%d\n", wi->WM_NORMAL_HINTS->max_aspect.y); - printf("| \twidth_inc: %d\n", wi->WM_NORMAL_HINTS->width_inc); - printf("| \theight_inc: %d\n", wi->WM_NORMAL_HINTS->height_inc); - } - - if (wi->WM_HINTS) { - printf("| WM_HINTS: \n"); - printf("| \twin_gravity: %d\n", wi->WM_HINTS->win_gravity); - printf("| \theight: %d\n", wi->WM_HINTS->height); - printf("| \twidth: %d\n", wi->WM_HINTS->width); - printf("| \tx: %d\n", wi->WM_HINTS->x); - printf("| \ty: %d\n", wi->WM_HINTS->y); - printf("| \tbase_width: %d\n", wi->WM_HINTS->base_width); - printf("| \tbase_height: %d\n", wi->WM_HINTS->base_height); - printf("| \tmin_width: %d\n", wi->WM_HINTS->min_width); - printf("| \tmin_height: %d\n", wi->WM_HINTS->min_height); - printf("| \tmin_aspect:\n"); - printf("| \t\tnumerator:%d\n", wi->WM_HINTS->min_aspect.x); - printf("| \t\tdenominator:%d\n", wi->WM_HINTS->min_aspect.y); - printf("| \tmax_width: %d\n", wi->WM_HINTS->max_width); - printf("| \tmax_height: %d\n", wi->WM_HINTS->max_height); - printf("| \tmax_aspect:\n"); - printf("| \t\tnumerator:%d\n", wi->WM_HINTS->max_aspect.x); - printf("| \t\tdenominator:%d\n", wi->WM_HINTS->max_aspect.y); - printf("| \twidth_inc: %d\n", wi->WM_HINTS->width_inc); - printf("| \theight_inc: %d\n", wi->WM_HINTS->height_inc); - } - - if (wi->net_wm_strut) { - //printf("TEST----- %ld\n", wi->nbr_net_wm_strut); - for (size_t i = 0; i < wi->nbr_net_wm_strut; i++) - printf("%ld\n", wi->net_wm_strut[i]); - //printf("TEST-----\n"); - } - printf("\n"); -} - -char *get_output_str(char *str) { - char *out; - - if (str == NULL) { - return NULL; - } - out = strdup(str); - return out; -} - -Window *get_client_list(Display *disp, unsigned long *size) { - Window *client_list = NULL; - client_list = (Window *)get_property(disp, DefaultRootWindow(disp), XA_WINDOW, "_NET_CLIENT_LIST", size); - - if (client_list == NULL) { - client_list = (Window *)get_property(disp, DefaultRootWindow(disp), XA_CARDINAL, "_WIN_CLIENT_LIST", size); - if (client_list == NULL) { - fputs("Cannot get client list properties. \n (_NET_CLIENT_LIST or _WIN_CLIENT_LIST) \n", stderr); - *size = 0; - return NULL; - } - } - return client_list; -} - -bool client_msg(Display *disp, Window win, char *msg, - unsigned long data0, unsigned long data1, - unsigned long data2, unsigned long data3, - unsigned long data4) { - XEvent event; - long mask = SubstructureRedirectMask | SubstructureNotifyMask; - - event.xclient.type = ClientMessage; - event.xclient.serial = 0; - event.xclient.send_event = true; - event.xclient.message_type = XInternAtom(disp, msg, false); - event.xclient.window = win; - event.xclient.format = 32; - event.xclient.data.l[0] = data0; - event.xclient.data.l[1] = data1; - event.xclient.data.l[2] = data2; - event.xclient.data.l[3] = data3; - event.xclient.data.l[4] = data4; - - if (XSendEvent(disp, DefaultRootWindow(disp), false, mask, &event)) { - return true; - } - else { - fprintf(stderr, "Cannot send %s event.\n", msg); - return false; - } -} \ No newline at end of file diff --git a/libwmctrl/src/window-edit.c b/libwmctrl/src/window-edit.c deleted file mode 100644 index 135504b..0000000 --- a/libwmctrl/src/window-edit.c +++ /dev/null @@ -1,672 +0,0 @@ -#include "./wmctrl.h" - -static bool activate_window(Display *disp, Window win, - bool switch_desktop) { - unsigned long *desktop; - /* desktop ID */ - if ((desktop = (unsigned long *)get_property(disp, win, - XA_CARDINAL, "_NET_WM_DESKTOP", NULL)) == NULL) { - if ((desktop = (unsigned long *)get_property(disp, win, - XA_CARDINAL, "_WIN_WORKSPACE", NULL)) == NULL) { - return false; - } - } - - if (switch_desktop && desktop) { - if (client_msg(disp, DefaultRootWindow(disp), - "_NET_CURRENT_DESKTOP", - *desktop, 0, 0, 0, 0) != True) { - return false; - } - } - - XMapRaised(disp, win); - if (desktop) - free(desktop); - - return client_msg(disp, win, "_NET_ACTIVE_WINDOW", - 0, 0, 0, 0, 0); -} - -//ACTIVE SECTION -enum STATES active_window_by_id(Display *disp, Window wid) { - bool res; - bool displayProvided = true; - - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) - return CAN_NOT_OPEN_DISPLAY; - - res = activate_window(disp, wid, false); - - if (!displayProvided) - XCloseDisplay(disp); - - return res ? WINDOW_ACTIVATED : CAN_NOT_ACTIVATE_WINDOW; -} - -enum STATES active_windows_by_pid(Display *disp, unsigned long pid) { - size_t size; - Window win; - unsigned long current_pid; - struct window_cache *wc; - enum STATES st; - Window *windows; - struct window_cache_list *wcl = init_window_list_cache(); - bool displayProvided = true; - bool window_found = false; - - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) - return CAN_NOT_OPEN_DISPLAY; - - windows = get_client_list(disp, &size); - - if (!windows) - return CAN_NOT_GET_CLIENT_LIST; - - size /= sizeof(Window); - if (!windows) { - if (!displayProvided) - XCloseDisplay(disp); - return CAN_NOT_ALLOCATE_MEMORY; - } - - for (size_t i = 0; i < size; i++) { - win = windows[i]; - wc = get_window_cache_by_id(wcl, win); - - if (wc && wc->win_pid) { - current_pid = wc->win_pid; - } - else { - current_pid = get_window_pid(disp, win); - if (current_pid) { - add_window_cache(wcl, win, NULL, current_pid); - } - else { - continue; - } - } - - if (current_pid == pid) { - st = active_window_by_id(disp, win); - if (st != WINDOW_ACTIVATED) - return CAN_NOT_ACTIVATE_WINDOW; - XSync(disp, False); - window_found = true; - } - } - - free(windows); - free_window_cache_list(wcl); - if (!displayProvided) - XCloseDisplay(disp); - - if (!window_found) - return NO_WINDOW_FOUND; - - return WINDOWS_ACTIVATED; -} - -enum STATES active_windows_by_class_name(Display *disp, const char *class_name) { - size_t size; - Window win; - Window *windows; - char *current_class_name; - struct window_cache *wc; - enum STATES st; - struct window_cache_list *wcl = init_window_list_cache(); - bool displayProvided = true; - bool window_found = false; - - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) - return CAN_NOT_OPEN_DISPLAY; - - windows = get_client_list(disp, &size); - - if (!windows) - return CAN_NOT_GET_CLIENT_LIST; - - if (!wcl) - return CAN_NOT_ALLOCATE_MEMORY; - - size /= sizeof(Window); - if (!windows) { - if (!displayProvided) - XCloseDisplay(disp); - return CAN_NOT_ALLOCATE_MEMORY; - } - - for (size_t i = 0; i < size; i++) { - win = windows[i]; - wc = get_window_cache_by_id(wcl, win); - if (wc && wc->win_class) - current_class_name = strdup(wc->win_class); - else { - current_class_name = get_window_class(disp, win); - if (current_class_name) - add_window_cache(wcl, win, current_class_name, 0); - else { - continue; - } - } - - if (strcmp(current_class_name, class_name) == 0) { - st = active_window_by_id(disp, win); - if (st != WINDOW_ACTIVATED) - return CAN_NOT_ACTIVATE_WINDOW; - XSync(disp, False); - window_found = true; - } - - free(current_class_name); - } - - free(windows); - free_window_cache_list(wcl); - if (!displayProvided) - XCloseDisplay(disp); - - if (!window_found) - return NO_WINDOW_FOUND; - - return WINDOWS_ACTIVATED; -} - -//CLOSE SECTION -enum STATES close_window_by_id(Display *disp, Window win) { - bool res; - bool displayProvided = true; - - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) - return CAN_NOT_OPEN_DISPLAY; - - res = client_msg(disp, win, "_NET_CLOSE_WINDOW", - 0, 0, 0, 0, 0); - - if (!displayProvided) - XCloseDisplay(disp); - - return res ? WINDOW_CLOSED : CAN_NOT_CLOSE_WINDOW; -} - -static enum STATES close_windows_by(Display *disp, char mode, const void *data) { - unsigned long size; - unsigned long current_pid; - unsigned long pid; - const char *class_name; - char *current_class_name; - Window win; - struct window_cache *wc; - struct window_cache_list *wcl = init_window_list_cache(); - Window *windows = get_client_list(disp, &size); - bool win_found = false; - - if (!wcl) { - if (windows) - free(windows); - return CAN_NOT_ALLOCATE_MEMORY; - } - - if (!windows) { - free_window_cache_list(wcl); - return CAN_NOT_GET_CLIENT_LIST; - } - - if (!size) { - free(windows); - free_window_cache_list(wcl); - return CAN_NOT_GET_CLIENT_LIST; - } - - size /= sizeof(Window); - - switch (mode) { - case 'p': { - pid = *((unsigned long*) data); - for (size_t i = 0; i < size; i++) { - win = windows[i]; - wc = get_window_cache_by_id(wcl, win); - if (wc && wc->win_pid) - current_pid = wc->win_pid; - else { - current_pid = get_window_pid(disp, win); - if (current_pid) - add_window_cache(wcl, win, NULL, current_pid); - else - continue; - } - - if (pid == current_pid) { - close_window_by_id(disp, win); - XSync(disp, False); - free(windows); - windows = get_client_list(disp, &size); - size /= sizeof(Window); - - i = 0; - win_found = true; - - if (!windows) - return CAN_NOT_GET_CLIENT_LIST; - } - } - break; - } - case 'c': { - class_name = data; - for (size_t i = 0; i < size; i++) { - win = windows[i]; - wc = get_window_cache_by_id(wcl, win); - if (wc && wc->win_class) - current_class_name = strdup(wc->win_class); - else { - current_class_name = get_window_class(disp, win); - if (current_class_name) - add_window_cache(wcl, win, current_class_name, 0); - else - continue; - } - - if (strcmp(class_name, current_class_name) == 0) { - close_window_by_id(disp, win); - XSync(disp, False); - free(windows); - windows = get_client_list(disp, &size); - size /= sizeof(Window); - - i = 0; - win_found = true; - } - free(current_class_name); - } - break; - } - } - free(windows); - free_window_cache_list(wcl); - - if (!win_found) - return NO_WINDOW_FOUND; - - return WINDOWS_CLOSED; -} - -enum STATES close_windows_by_pid(Display *disp, unsigned long pid) { - bool displayProvided = true; - enum STATES st; - - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) - return CAN_NOT_OPEN_DISPLAY; - - st = close_windows_by(disp, 'p', &pid); - - if (!displayProvided) - XCloseDisplay(disp); - - return st; -} - -enum STATES close_windows_by_class_name(Display *disp, const char *class_name) { - enum STATES st; - bool displayProvided = true; - - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) - return CAN_NOT_OPEN_DISPLAY; - - st = close_windows_by(disp, 'c',class_name); - - if (!displayProvided) - XCloseDisplay(disp); - - return st; -} - -//EDIT PROPERTIES SECTION -enum STATES window_set_icon_name(Display *disp, Window win, const char *_net_wm_icon_name) { - int res; - bool displayProvided = true; - - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) - return CAN_NOT_OPEN_DISPLAY; - - res = XChangeProperty(disp, win, XInternAtom(disp, "_NET_WM_ICON_NAME", False), - XInternAtom(disp, "UTF8_STRING", False), 8, PropModeReplace, - (const unsigned char *)_net_wm_icon_name, strlen(_net_wm_icon_name)); - - if (!displayProvided) - XCloseDisplay(disp); - - return res ? WINDOW_ICON_NAME_SET : CAN_NOT_SET_WINDOW_ICON_NAME; -} - -enum STATES window_set_title(Display *disp, Window win, const char *_net_wm_name) { - int res; - bool displayProvided = true; - - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) - return CAN_NOT_OPEN_DISPLAY; - - res = XChangeProperty(disp, win, XInternAtom(disp, "_NET_WM_NAME", False), - XInternAtom(disp, "UTF8_STRING", False), 8, PropModeReplace, - (const unsigned char *)_net_wm_name, strlen(_net_wm_name)); - - if (!displayProvided) - XCloseDisplay(disp); - - return res ? WINDOW_TITLE_SET : CAN_NOT_SET_WINDOW_TITLE; -} - -/** - * action _NET_WM_STATE_REMOVE | _NET_WM_STATE_ADD | _NET_WM_STATE_TOGGLE - * prop1, prop2: modal_sticky | maximized_vert | maximized_horz | - shaded | skip_taskbar | skip_pager | hidden | fullscreen | above -**/ -enum STATES window_state(Display *disp, Window win, unsigned long action, - char *prop1_str, char *prop2_str) { - bool res; - bool displayProvided = true; - char *uppercase_prop1; - char *uppercase_prop2; - char *tmp_prop1; - char *tmp_prop2; - Atom prop1; - Atom prop2; - - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) - return CAN_NOT_OPEN_DISPLAY; - - uppercase_prop1 = strdup(prop1_str); - for (size_t i = 0; uppercase_prop1[i]; i++) - uppercase_prop1[i] = toupper(uppercase_prop1[i]); - - tmp_prop1 = malloc(sizeof(char) * (strlen(uppercase_prop1) + 64)); - sprintf(tmp_prop1, "_NET_WM_STATE_%s", uppercase_prop1); - - prop1 = XInternAtom(disp, tmp_prop1, False); - free(uppercase_prop1); - free(tmp_prop1); - - prop2 = 0; - if (strcmp(prop2_str, "") != 0) { - uppercase_prop2 = strdup(prop2_str); - for (size_t i = 0; uppercase_prop2[i]; i++) - uppercase_prop2[i] = toupper(uppercase_prop2[i]); - tmp_prop2 = malloc(sizeof(char) * (strlen(prop2_str) + 64)); - sprintf(tmp_prop2, "_NET_WM_STATE_%s", uppercase_prop2); - - prop2 = XInternAtom(disp, tmp_prop2, False); - free(uppercase_prop2); - free(tmp_prop2); - } - - res = client_msg(disp, win, "_NET_WM_STATE", - action, (unsigned long)prop1, (unsigned long)prop2, 0, 0); - - if (!displayProvided) - XCloseDisplay(disp); - - return res ? WINDOW_STATE_SET : CAN_NOT_SET_WINDOW_STATE; -} - -enum STATES change_viewport (Display *disp, unsigned long x, unsigned long y) { - bool res; - bool displayProvided = true; - - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) - return CAN_NOT_OPEN_DISPLAY; - - res = client_msg(disp, DefaultRootWindow(disp), "_NET_DESKTOP_VIEWPORT", - x, y, 0, 0, 0); - - if (!displayProvided) - XCloseDisplay(disp); - - return res ? VIEWPORT_CHANGED : CAN_NOT_CHANGE_VIEWPORT; -} - -enum STATES change_geometry(Display *disp, unsigned long x, unsigned long y) { - bool res; - bool displayProvided = true; - - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) - return CAN_NOT_OPEN_DISPLAY; - - res = client_msg(disp, DefaultRootWindow(disp), "_NET_DESKTOP_GEOMETRY", - x, y, 0, 0, 0); - - if (!displayProvided) - XCloseDisplay(disp); - - return res ? GEOMETRY_CHANGED : CAN_NOT_CHANGE_GEOMETRY; -} - -enum STATES window_allow_all_sizes(Display *disp, Window win) { - XSizeHints *xsh; - bool displayProvided = true; - - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) - return CAN_NOT_OPEN_DISPLAY; - - xsh = XAllocSizeHints(); - if (!xsh) - return CAN_NOT_ALLOCATE_MEMORY; - - xsh->min_width = 0; - xsh->min_height = 0; - xsh->max_width = 0; - xsh->max_height = 0; - - XSetWMNormalHints(disp, win, xsh); - - if (!displayProvided) - XCloseDisplay(disp); - - XFree(xsh); - return WINDOW_ALLOWED_ALL_SIZE; -} - -enum STATES window_raise(Display *disp, Window win) { - bool displayProvided = true; - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) - return CAN_NOT_OPEN_DISPLAY; - - int res = XRaiseWindow(disp, win); - - if (displayProvided) - XCloseDisplay(disp); - - return res ? WINDOW_RAISED : CAN_NOT_RAISE_WINDOW; -} - -/* -int action_window (Display *disp, Window win, char mode) { - - - case 't': - // move the window to the specified desktop => -r -t / - return window_to_desktop(disp, win, atoi(options.param)); - - case 'R': - // move the window to the current desktop and activate it => -r / - if (window_to_desktop(disp, win, -1) == EXIT_SUCCESS) { - usleep(100000); // 100 ms - make sure the WM has enough - //time to move the window, before we activate it / - return activate_window(disp, win, FALSE); - } - else { - return EXIT_FAILURE; - } - - case 'N': case 'I': case 'T': - window_set_title(disp, win, options.param, mode); - return EXIT_SUCCESS; - - default: - fprintf(stderr, "Unknown action: '%c'\n", mode); - return EXIT_FAILURE; - } -} - -static int action_window_pid (Display *disp, char mode) { - unsigned long wid; - - if (sscanf(options.param_window, "0x%lx", &wid) != 1 && - sscanf(options.param_window, "0X%lx", &wid) != 1 && - sscanf(options.param_window, "%lu", &wid) != 1) { - fputs("Cannot convert argument to number.\n", stderr); - return EXIT_FAILURE; - } - - return action_window(disp, (Window)wid, mode); -} - -static int action_window_str (Display *disp, char mode) { - Window activate = 0; - Window *client_list; - unsigned long client_list_size; - int i; - - if (strcmp(SELECT_WINDOW_MAGIC, options.param_window) == 0) { - activate = Select_Window(disp); - if (activate) { - return action_window(disp, activate, mode); - } - else { - return EXIT_FAILURE; - } - } - if (strcmp(ACTIVE_WINDOW_MAGIC, options.param_window) == 0) { - activate = get_active_window(disp); - if (activate) - { - return action_window(disp, activate, mode); - } - else - { - return EXIT_FAILURE; - } - } - else { - if ((client_list = get_client_list(disp, &client_list_size)) == NULL) { - return EXIT_FAILURE; - } - - for (i = 0; i < client_list_size / sizeof(Window); i++) { - char *match_utf8; - if (options.show_class) { - match_utf8 = get_window_class(disp, client_list[i]); // UTF8 / - } - else { - match_utf8 = get_window_title(disp, client_list[i]); // UTF8 / - } - if (match_utf8) { - char *match; - char *match_cf; - char *match_utf8_cf = NULL; - if (envir_utf8) { - match = g_strdup(options.param_window); - match_cf = g_utf8_casefold(options.param_window, -1); - } - else { - if (! (match = g_locale_to_utf8(options.param_window, -1, NULL, NULL, NULL))) { - match = g_strdup(options.param_window); - } - match_cf = g_utf8_casefold(match, -1); - } - - if (!match || !match_cf) { - continue; - } - - match_utf8_cf = g_utf8_casefold(match_utf8, -1); - - if ((options.full_window_title_match && strcmp(match_utf8, match) == 0) || - (!options.full_window_title_match && strstr(match_utf8_cf, match_cf))) { - activate = client_list[i]; - g_free(match); - g_free(match_cf); - g_free(match_utf8); - g_free(match_utf8_cf); - break; - } - g_free(match); - g_free(match_cf); - g_free(match_utf8); - g_free(match_utf8_cf); - } - } - g_free(client_list); - - if (activate) { - return action_window(disp, activate, mode); - } - else { - return EXIT_FAILURE; - } - } -}*/ \ No newline at end of file diff --git a/libwmctrl/src/window-manager.c b/libwmctrl/src/window-manager.c deleted file mode 100644 index 84d8354..0000000 --- a/libwmctrl/src/window-manager.c +++ /dev/null @@ -1,98 +0,0 @@ -#include "./wmctrl.h" - -bool wm_supports(Display *disp, const char *prop) { - Atom xa_prop = XInternAtom(disp, prop, False); - Atom *list; - unsigned long size; - unsigned long i; - - if (! (list = (Atom *)get_property(disp, DefaultRootWindow(disp), - XA_ATOM, "_NET_SUPPORTED", &size))) { - printf("Cannot get _NET_SUPPORTED property.\n"); - return false; - } - - for (i = 0; i < size / sizeof(Atom); i++) { - if (list[i] == xa_prop) { - free(list); - return true; - } - } - - free(list); - return false; -} - -struct window_info *get_wm_info(Display *disp) { - Window *sup_window = NULL; - char *wm_name = NULL; - char *wm_class = NULL; - unsigned long *wm_pid = NULL; - unsigned long *showing_desktop = NULL; - char *name_out; - char *class_out; - - if (! (sup_window = (Window *)get_property(disp, DefaultRootWindow(disp), - XA_WINDOW, "_NET_SUPPORTING_WM_CHECK", NULL))) { - if (! (sup_window = (Window *)get_property(disp, DefaultRootWindow(disp), - XA_CARDINAL, "_WIN_SUPPORTING_WM_CHECK", NULL))) { - fputs("Cannot get window manager info properties.\n" - "(_NET_SUPPORTING_WM_CHECK or _WIN_SUPPORTING_WM_CHECK)\n", stderr); - return NULL; - } - } - - struct window_info *wi = malloc(sizeof(struct window_info)); - - /* WM_NAME */ - if (! (wm_name = get_property(disp, *sup_window, - XInternAtom(disp, "UTF8_STRING", False), "_NET_WM_NAME", NULL))) { - if (! (wm_name = get_property(disp, *sup_window, - XA_STRING, "_NET_WM_NAME", NULL))) { - printf("Cannot get name of the window manager (_NET_WM_NAME).\n"); - } - } - name_out = get_output_str(wm_name); - - /* WM_CLASS */ - if (! (wm_class = get_property(disp, *sup_window, - XInternAtom(disp, "UTF8_STRING", False), "WM_CLASS", NULL))) { - if (! (wm_class = get_property(disp, *sup_window, - XA_STRING, "WM_CLASS", NULL))) { - printf("Cannot get class of the window manager (WM_CLASS).\n"); - } - } - class_out = get_output_str(wm_class); - - /* WM_PID */ - if (! (wm_pid = (unsigned long *)get_property(disp, *sup_window, - XA_CARDINAL, "_NET_WM_PID", NULL))) { - printf("Cannot get pid of the window manager (_NET_WM_PID).\n"); - } - - /* _NET_SHOWING_DESKTOP */ - if (! (showing_desktop = (unsigned long *)get_property(disp, DefaultRootWindow(disp), - XA_CARDINAL, "_NET_SHOWING_DESKTOP", NULL))) { - printf("Cannot get the _NET_SHOWING_DESKTOP property.\n"); - } - - /* match out the info */ - wi->win_name = strdup(name_out ? name_out : "N/A"); - wi->win_class = strdup(class_out ? class_out : "N/A"); - wi->win_pid = wm_pid ? *wm_pid : 0; - wi->showing_desktop = showing_desktop ? *showing_desktop : 0; - - if (name_out) - free(name_out); - if (sup_window) - free(sup_window); - if (wm_name) - free(wm_name); - if (wm_class) - free(wm_class); - if (wm_pid) - free(wm_pid); - if (showing_desktop) - free(showing_desktop); - return wi; -} \ No newline at end of file diff --git a/libwmctrl/src/window-move-resize-transition.c b/libwmctrl/src/window-move-resize-transition.c deleted file mode 100644 index c7e4716..0000000 --- a/libwmctrl/src/window-move-resize-transition.c +++ /dev/null @@ -1,172 +0,0 @@ -#include "wmctrl.h" - -struct pos_dims { - int32_t x; - int32_t y; - int32_t w; - int32_t h; -}; - -static int max(int tab[], size_t length) { - int max = tab[0]; - for (size_t i = 1; i < length; i++) { - if (max < tab[i]) - max = tab[i]; - } - return max; -} - -static size_t get_pos_dims_size(struct geometry *geo, int32_t x, int32_t y, - int32_t w, int32_t h, int pad) { - - int rx = geo->x > x ? geo->x -x : x - geo->x; - int ry = geo->y > y ? geo->y - y : y - geo->x; - int rw = geo->width > w ? geo->width - w : w - geo->width; - int rh = geo->height > h ? geo->height - h : h - geo->height; - - rx /= pad; - ry /= pad; - rw /= pad; - rh /= pad; - - int tab[] = {rx, ry, rw, rh}; - return max(tab, 4) + 1; -} - -enum STATES window_move_resize_transition(Display *disp, Window win, int32_t grav, - int32_t x, int32_t y, - int32_t w, int32_t h, float await_time, int pad) { - bool displayProvided = true; - struct geometry *geo; - struct pos_dims *pos_dims; - size_t count_x = 0; - size_t count_y = 0; - size_t count_w = 0; - size_t count_h = 0; - size_t i = 0; - - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) - return CAN_NOT_OPEN_DISPLAY; - - if (grav < 0) - return CAN_NOT_MOVE_RESIZE_WINDOW; - - geo = get_window_geometry(disp, win); - pos_dims = malloc(sizeof(struct pos_dims) * get_pos_dims_size(geo, x, y, w, h, pad)); - if (!geo || !pos_dims) - return CAN_NOT_ALLOCATE_MEMORY; - - if (geo->x == x) { - pos_dims[i].x = x; - i++; - } - else if (geo->x > x) { - int tmp_x = geo->x; - while (tmp_x > x) { - tmp_x -= pad; - pos_dims[i].x = tmp_x > x ? tmp_x : x; - i++; - } - } else { - int tmp_x = geo->x; - while (tmp_x < x) { - tmp_x += pad; - pos_dims[i].x = tmp_x < x ? tmp_x : x; - i++; - } - } - count_x = i; - - i = 0; - if (geo->y == y) { - pos_dims[i].y = y; - i++; - } - else if (geo->y > y) { - int tmp_y = geo->y; - while (tmp_y > y) { - tmp_y -= pad; - pos_dims[i].y = tmp_y > y ? tmp_y : y; - i++; - } - }else { - int tmp_y = geo->y; - while (tmp_y <= x) { - tmp_y += pad; - pos_dims[i].y = tmp_y <= x ? tmp_y : y; - i++; - } - } - count_y = i; - - i = 0; - if (geo->width == w) { - pos_dims[i].w = w; - i++; - } - else if (geo->width > w) { - int tmp_width = geo->width; - while (tmp_width > w) { - tmp_width -= pad; - pos_dims[i].w = tmp_width > w ? tmp_width : w; - i++; - } - } else { - int tmp_width = geo->width; - while (tmp_width <= w) { - tmp_width += pad; - pos_dims[i].w = tmp_width <= w ? tmp_width : w; - i++; - } - } - count_w = i; - - i = 0; - if (geo->height == h) { - pos_dims[i].h = h; - i++; - } - else if (geo->height > h) { - int tmp_height = geo->height; - while (tmp_height > h) { - tmp_height -= pad; - pos_dims[i].h = tmp_height > h ? tmp_height : h; - i++; - } - }else { - int tmp_height = geo->height; - while (tmp_height <= h) { - tmp_height += pad; - pos_dims[i].h = tmp_height <= h ? tmp_height :h; - i++; - } - } - count_h = i; - - i = 0; - while(i < count_x || i < count_y || i < count_w || i < count_h) { - int rx,ry,rw,rh; - rx = i >= count_x ? x : pos_dims[i].x; - ry = i >= count_y ? y : pos_dims[i].y; - rw = i >= count_w ? w : pos_dims[i].w; - rh = i >= count_h ? h : pos_dims[i].h; - - int time = await_time * 1000; - window_move_resize(disp, win, grav, rx, ry, rw, rh); - XSync(disp, True); - usleep(time); - i++; - } - - free(geo); - free(pos_dims); - if (!displayProvided) - XCloseDisplay(disp); - - return WINDOW_MOVED_RESIZED; -} \ No newline at end of file diff --git a/libwmctrl/src/window-move-resize.c b/libwmctrl/src/window-move-resize.c deleted file mode 100644 index 5842f6d..0000000 --- a/libwmctrl/src/window-move-resize.c +++ /dev/null @@ -1,143 +0,0 @@ -#include "./wmctrl.h" - -enum STATES window_to_desktop(Display *disp, Window win, int desktop) { - bool displayProvided = false; - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = true; - } - - unsigned long *cur_desktop = NULL; - Window root = DefaultRootWindow(disp); - - if (desktop == -1) { - if (! (cur_desktop = (unsigned long *)get_property(disp, root, - XA_CARDINAL, "_NET_CURRENT_DESKTOP", NULL))) { - if (! (cur_desktop = (unsigned long *)get_property(disp, root, - XA_CARDINAL, "_WIN_WORKSPACE", NULL))) { - fputs("Cannot get current desktop properties. " - "(_NET_CURRENT_DESKTOP or _WIN_WORKSPACE property)" - "\n", stderr); - return CAN_NOT_GET_CURRENT_DESKTOP_PROPERTY; - } - } - desktop = *cur_desktop; - } - free(cur_desktop); - - bool res = client_msg(disp, win, "_NET_WM_DESKTOP", (unsigned long)desktop, - 0, 0, 0, 0); - - if (!displayProvided) - XCloseDisplay(disp); - - return res ? WINDOW_MOVED_TO_DESKTOP : CAN_NOT_MOVE_WINDOW_TO_DESKTOP; -} - -enum STATES window_to_current_desktop(Display *disp, Window win) { - enum STATES st; - bool displayProvided = true; - - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) - return CAN_NOT_OPEN_DISPLAY; - - st = window_to_desktop(disp, win, -1); - if (st == WINDOW_MOVED_TO_DESKTOP) { - usleep(100000); // 100 ms - make sure the WM has enough - //time to move the window, before we activate it / - active_window_by_id(disp, win); - } - - if (!displayProvided) - XCloseDisplay(disp); - - return st; -} - -//_NET_MOVERESIZE_WINDOW -enum STATES window_move_resize(Display *disp, Window win, int32_t grav, - int32_t x, int32_t y, - int32_t w, int32_t h) { - int32_t grflags; - bool displayProvided = true; - bool res; - - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) - return CAN_NOT_OPEN_DISPLAY; - - if (grav < 0) - return CAN_NOT_MOVE_RESIZE_WINDOW; - - grflags = grav; - if (x != -1) grflags |= (1 << 8); - if (y != -1) grflags |= (1 << 9); - if (w != -1) grflags |= (1 << 10); - if (h != -1) grflags |= (1 << 11); - - if (wm_supports(disp, "_NET_MOVERESIZE_WINDOW")) { - res = client_msg(disp, win, "_NET_MOVERESIZE_WINDOW", grflags, x, y, w, h); - - if (!displayProvided) - XCloseDisplay(disp); - - return res ? WINDOW_MOVED_RESIZED : CAN_NOT_MOVE_RESIZE_WINDOW; - } - else { - if ((w < 1 || h < 1) && (x >= 0 && y >= 0)) - XMoveWindow(disp, win, x, y); - - else if ((x < 0 || y < 0) && (w >= 1 && h >= -1)) - XResizeWindow(disp, win, w, h); - - else if (x >= 0 && y >= 0 && w >= 1 && h >= 1) - XMoveResizeWindow(disp, win, x, y, w, h); - - if (!displayProvided) - XCloseDisplay(disp); - - return WINDOW_MOVED_RESIZED; - } -} - -enum STATES window_minimize(Display *disp, Window window) { - int ret; - int screen; - bool displayProvided = true; - /* Get screen number */ - XWindowAttributes attr; - - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) - return CAN_NOT_OPEN_DISPLAY; - - ret = XGetWindowAttributes(disp, window, &attr); - if (ret == 0) { - if (!displayProvided) - XCloseDisplay(disp); - return CAN_NOT_GET_WINDOW_ATTRIBUTES; - } - - screen = XScreenNumberOfScreen(attr.screen); - - /* Minimize it */ - ret = XIconifyWindow(disp, window, screen); - - if (!displayProvided) - XCloseDisplay(disp); - - return ret != 0 ? WINDOW_MINIMIZED : CAN_NOT_MINIMIZE_WINDOW; -} \ No newline at end of file diff --git a/libwmctrl/src/window-properties.c b/libwmctrl/src/window-properties.c deleted file mode 100644 index 72b8b92..0000000 --- a/libwmctrl/src/window-properties.c +++ /dev/null @@ -1,420 +0,0 @@ -#include "./wmctrl.h" - -#define _NET_WM_WINDOW_TYPES ((char const*[]) { \ - "_NET_WM_WINDOW_TYPE_DESKTOP", \ - "_NET_WM_WINDOW_TYPE_DOCK", \ - "_NET_WM_WINDOW_TYPE_TOOLBAR", \ - "_NET_WM_WINDOW_TYPE_MENU", \ - "_NET_WM_WINDOW_TYPE_UTILITY", \ - "_NET_WM_WINDOW_TYPE_SPLASH", \ - "_NET_WM_WINDOW_TYPE_DIALOG", \ - "_NET_WM_WINDOW_TYPE_NORMAL" \ -}) -#define NB_ALLOWED_TYPES 8 - -#define _NET_WM_ALLOWED_ACTIONS ((char const*[]) { \ - "_NET_WM_ACTION_MOVE", "_NET_WM_ACTION_RESIZE", \ - "_NET_WM_ACTION_MINIMIZE", "_NET_WM_ACTION_SHADE", \ - "_NET_WM_ACTION_STICK", "_NET_WM_ACTION_MAXIMIZE_HORZ", \ - "_NET_WM_ACTION_MAXIMIZE_VERT", "_NET_WM_ACTION_FULLSCREEN",\ - "_NET_WM_ACTION_CHANGE_DESKTOP", "_NET_WM_ACTION_CLOSE" \ -}) -#define NB_ALLOWED_ACTIONS 10 - -#define _NET_WM_STATE ((char const*[]) { \ - "_NET_WM_STATE_MODAL", "_NET_WM_STATE_STICKY",\ - "_NET_WM_STATE_MAXIMIZED_VERT", "_NET_WM_STATE_MAXIMIZED_HORZ",\ - "_NET_WM_STATE_SHADED", "_NET_WM_STATE_SKIP_TASKBAR",\ - "_NET_WM_STATE_SKIP_PAGER", "_NET_WM_STATE_HIDDEN",\ - "_NET_WM_STATE_FULLSCREEN", "_NET_WM_STATE_ABOVE",\ - "_NET_WM_STATE_BELOW", "_NET_WM_STATE_DEMANDS_ATTENTION"\ -}) -#define NB_WM_STATE 12 - -char *get_property(Display *disp, Window win, - Atom xa_prop_type, char *prop_name, size_t *size) { - - Atom xa_prop_name; - Atom xa_ret_type; - int ret_format; - unsigned long ret_nitems; - unsigned long ret_bytes_after; - size_t tmp_size; - unsigned char *ret_prop; - char *ret; - - xa_prop_name = XInternAtom(disp, prop_name, false); - - /* MAX_PROPERTY_VALUE_LEN / 4 explanation (XGetWindowProperty manpage): - * - * long_length = Specifies the length in 32-bit multiples of the - * data to be retrieved. - * - * NOTE: see - * http://mail.gnome.org/archives/wm-spec-list/2003-March/msg00067.html - * In particular: - * - * When the X window system was ported to 64-bit architectures, a - * rather peculiar design decision was made. 32-bit quantities such - * as Window IDs, atoms, etc, were kept as longs in the client side - * APIs, even when long was changed to 64 bits. - * - */ - if (XGetWindowProperty(disp, win, xa_prop_name, 0, MAX_PROPERTY_VALUE_LEN / 4, false, - xa_prop_type, &xa_ret_type, &ret_format, - &ret_nitems, &ret_bytes_after, &ret_prop) != Success) { - //fprintf(stderr, "Cannot get %s property, for window %ld\n", prop_name, win); - if (size) { - *size = 0; - } - return NULL; - } - - if (xa_ret_type != xa_prop_type) { - if (size) { - *size = 0; - } - XFree(ret_prop); - return NULL; - } - - /* null terminate the result to make string handling easier */ - tmp_size = (ret_format / 8) * ret_nitems; - /* Correct 64 Architecture implementation of 32 bit data */ - if (ret_format==32) { - tmp_size *= sizeof(long)/4; - } - - ret = malloc(tmp_size + 1); - - if (!ret) { - if (size) { - *size = 0; - } - XFree(ret_prop); - return NULL; - } - - memcpy(ret, ret_prop, tmp_size); - ret[tmp_size] = '\0'; - - if (size) { - *size = tmp_size; - } - - XFree(ret_prop); - return ret; -} - -//_NET_WM_PID -unsigned long get_window_pid(Display *disp, Window win) { - unsigned long pid; - unsigned long *wm_pid; - - if (!disp) - return 0; - - if (! (wm_pid = (unsigned long *)get_property(disp, win, XA_CARDINAL, "_NET_WM_PID", NULL))) { - return 0; - } - pid = *wm_pid; - - free(wm_pid); - return pid; -} - -//_NET_WM_DESKTOP -unsigned long get_window_desktop(Display *disp, Window win) { - unsigned long *net_wm_desktop = NULL; - net_wm_desktop = (unsigned long *)get_property(disp, win, - XA_CARDINAL, "_NET_WM_DESKTOP", NULL); - if (!net_wm_desktop) { - net_wm_desktop = (unsigned long *)get_property(disp, win, - XA_CARDINAL, "_WIN_WORKSPACE", NULL); - return 0; - } - unsigned long desktop = *net_wm_desktop; - free(net_wm_desktop); - return desktop; -} - -//_NET_SHOWING_DESKTOP -unsigned long get_window_shwing_desktop(Display *disp, Window win) { - unsigned long *ret = NULL; - if (! (ret = (unsigned long *)get_property(disp, win, - XA_CARDINAL, "_NET_SHOWING_DESKTOP", NULL))) { - return 0; - } - - unsigned long showing_desktop = *ret; - free(ret); - return showing_desktop; -} - -//WM_CLIENT_MACHINE -char *get_window_client_machine(Display *disp, Window win) { - char *wm_client_machine = get_property(disp, win, - XA_STRING, "WM_CLIENT_MACHINE", NULL); - return wm_client_machine; -} - -//WM_CLASS -char *get_window_class(Display *disp, Window win) { - char *class_utf8; - char *wm_class; - char *p_0; - size_t size; - - wm_class = get_property(disp, win, XA_STRING, "WM_CLASS", &size); - if (wm_class) { - p_0 = strchr(wm_class, '\0'); - if (wm_class + size - 1 > p_0) - *(p_0) = '.'; - class_utf8 = strdup(wm_class); - } - else - class_utf8 = NULL; - - if (wm_class) - free(wm_class); - - return class_utf8; -} - -//_NET_WM_WINDOW_TYPE -struct type_desc *get_window_types(Display *disp, Window win, size_t *size) { - struct type_desc *types = NULL; - Atom *atoms_type = (Atom *)get_property(disp, win, XA_ATOM, - "_NET_WM_WINDOW_TYPE", size); - if (atoms_type) { - *size = *size / sizeof(Atom); - size_t counter = 0; - types = malloc(sizeof(struct type_desc) * (*size)); - for (size_t i = 0; i < *size; i++) { - Atom atom_type = atoms_type[i]; - for (size_t j = 0; j < NB_ALLOWED_TYPES; j++) { - const char *type = _NET_WM_WINDOW_TYPES[j]; - Atom type_atom = XInternAtom(disp, type, False); - if (atom_type == type_atom) { - (types + counter)->flag = strdup(type); - (types + counter)->number = type_atom; - counter++; - } - } - } - - if (counter == 0) { - free(types); - types = NULL; - } - *size = counter; - } - else - *size = 0; - - free(atoms_type); - return types; -} - -//_NET_WM_ALLOWED_ACTIONS -struct action_desc *get_window_allowed_actions(Display *disp, Window win, size_t *size) { - struct action_desc *actions = NULL; - Atom *atoms_action = (Atom *)get_property(disp, win, XA_ATOM, - "_NET_WM_ALLOWED_ACTIONS", size); - if (atoms_action) { - *size = *size / 8; - size_t counter = 0; - actions = malloc(sizeof(struct action_desc) * (*size)); - for (size_t i = 0; i < *size; i++) { - Atom atom_action = atoms_action[i]; - for (size_t j = 0; j < NB_ALLOWED_ACTIONS; j++) { - const char *action = _NET_WM_ALLOWED_ACTIONS[j]; - Atom action_atom = XInternAtom(disp, action, False); - if (atom_action == action_atom) { - (actions + counter)->flag = strdup(action); - (actions + counter)->number = action_atom; - counter++; - } - } - } - - if (counter == 0) { - free(actions); - actions = NULL; - } - *size = counter; - } - else - *size = 0; - - free(atoms_action); - return actions; -} - -//_NET_WM_STATE -struct state_desc *get_window_states(Display *disp, Window win, size_t *size) { - struct state_desc *states = NULL; - Atom *atoms_state = (Atom *)get_property(disp, win, XA_ATOM, - "_NET_WM_STATE", size); - if (atoms_state) { - *size = *size / sizeof(Atom); - size_t counter = 0; - states = malloc(sizeof(struct state_desc) * (*size)); - for (size_t i = 0; i < *size; i++) { - Atom atom_state = atoms_state[i]; - for (size_t j = 0; j < NB_WM_STATE; j++) { - const char *state = _NET_WM_STATE[j]; - Atom state_atom = XInternAtom(disp, state, false); - if (atom_state == state_atom) { - (states + counter)->flag = strdup(state); - (states + counter)->number = state_atom; - counter++; - } - } - } - - if (counter == 0) { - free(states); - states = NULL; - } - *size = counter; - } - else - *size = 0; - - free(atoms_state); - return states; -} - -//_NET_WM_NAME -char *get_window_name(Display *disp, Window win) { - char *title_utf8 = NULL; - char *wm_name = NULL; - char *net_wm_name = NULL; - - wm_name = get_property(disp, win, XA_STRING, "WM_NAME", NULL); - net_wm_name = get_property(disp, win, - XInternAtom(disp, "UTF8_STRING", false), "_NET_WM_NAME", NULL); - - if (net_wm_name) { - title_utf8 = strdup(net_wm_name); - } - else { - if (wm_name) { - title_utf8 = strdup(wm_name); - } - else { - title_utf8 = NULL; - } - } - - free(wm_name); - free(net_wm_name); - - return title_utf8; -} - -//_NET_FRAME_EXTENTS -long *get_window_frame_extents(Display *disp, Window win) { - long *extents = NULL; - long *tmpextents; - Atom actual_type; - int actual_format; - unsigned long nitems, bytes_after; - unsigned char *data = NULL; - int result; - - result = XGetWindowProperty( - disp, win, XInternAtom(disp, "_NET_FRAME_EXTENTS", False), - 0, 4, False, AnyPropertyType, - &actual_type, &actual_format, - &nitems, &bytes_after, &data); - - if (result == Success) { - if ((nitems == 4) && (bytes_after == 0)) { - tmpextents = (long *)data; - extents = malloc(sizeof(long) * nitems); - for (size_t i = 0; i < nitems; i++) - extents[i] = tmpextents[i]; - } - XFree(data); - } - return extents; -} - -//_NET_WM_VISIBLE_NAME -char *get_window_visible_name(Display *disp, Window win) { - char *net_wm_visible_name = NULL; - char *wm_visible_name = NULL; - char *visible_name = NULL; - - wm_visible_name = get_property(disp, win, XA_STRING, "WM_VISIBLE_NAME", NULL); - net_wm_visible_name = get_property(disp, win, - XInternAtom(disp, "UTF8_STRING", False), "_NET_WM_VISIBLE_NAME", NULL); - - if (net_wm_visible_name) { - visible_name = net_wm_visible_name; - }else { - if (wm_visible_name) { - visible_name = strdup(wm_visible_name); - free(wm_visible_name); - } - else { - visible_name = NULL; - } - } - - return visible_name; -} - -//_NET_WM_ICON_NAME -char *get_window_icon_name(Display *disp, Window win) { - char *net_wm_icon_name = NULL; - net_wm_icon_name = get_property(disp, win, - XInternAtom(disp, "UTF8_STRING", False), "_NET_WM_ICON_NAME", NULL); - - return net_wm_icon_name; -} - -//_NET_WM_VISIBLE_ICON_NAME -char *get_window_visible_icon_name(Display *disp, Window win) { - char *net_wm_visible_icon_name = NULL; - net_wm_visible_icon_name = get_property(disp, win, - XInternAtom(disp, "UTF8_STRING", False), - "_NET_WM_VISIBLE_ICON_NAME", NULL); - - return net_wm_visible_icon_name; -} - -struct geometry *get_window_geometry(Display *disp, Window win) { - Window junkroot, child; - int junkx,junky, abs_x, abs_y; - unsigned int wwidth, wheight, bw, depth; - - struct geometry *win_geometry = malloc(sizeof(struct geometry)); - if (!win_geometry) - return NULL; - - XGetGeometry(disp, win, &junkroot, &junkx, &junky, - &wwidth, &wheight, &bw, &depth); // GET RELATIVES COORDINATES - - XTranslateCoordinates(disp, win, junkroot, junkx, junky, - &abs_x, &abs_y, &child); //GET ABSOLUTE COORDINATES - - win_geometry->width = wwidth; - win_geometry->height = wheight; - - win_geometry->x = junkx; - win_geometry->y = junky; - - win_geometry->abs_x = abs_x - junkx; - win_geometry->abs_y = abs_y - junky; - - return win_geometry; -} - -//_NET_WM_STRUT -Atom *get_window_net_wm_strut(Display *disp, Window win, size_t *size) { - return (Atom *)get_property(disp, win, XA_CARDINAL, - "_NET_WM_STRUT", size); -} \ No newline at end of file diff --git a/libwmctrl/src/window.c b/libwmctrl/src/window.c deleted file mode 100644 index 8ea752c..0000000 --- a/libwmctrl/src/window.c +++ /dev/null @@ -1,168 +0,0 @@ -#include "./wmctrl.h" - -static struct window_list *get_windows_by(Display *disp, void *data, - int (*predicate)(struct window_info *wi, void *data), enum STATES *st) { - - enum STATES tmpState; - struct window_info *newWinsInfos; - struct window_info *wi; - struct window_info *nwi; - struct window_list *wl = list_windows(disp, &tmpState); - unsigned long counter; - - *st = tmpState; - - if (!wl) - return NULL; - - newWinsInfos = malloc(sizeof(struct window_info) * wl->client_list_size); - - if (!newWinsInfos) { - if (st) - *st = CAN_NOT_ALLOCATE_MEMORY; - return NULL; - } - counter = 0; - - for (size_t i = 0; i < wl->client_list_size; i++) { - wi = wl->client_list+i; - if (predicate(wi, data)) { - nwi = newWinsInfos + counter; - initializeWindowInfo(nwi); - copy_window_info(nwi, wi); - counter++; - } - } - - if (counter == 0) { - free(newWinsInfos); - free_window_list(wl); - if (st) - *st = NO_WINDOW_FOUND; - return NULL; - } - - for (size_t i = 0; i < wl->client_list_size; i++) - free_window_info_properties(wl->client_list + i); - free(wl->client_list); - - wl->client_list = newWinsInfos; - wl->client_list_size = counter; - return wl; -} - -static int predicate_pid(struct window_info *wi, void *data) { - unsigned long *pid = data; - return wi->win_pid == *pid; -} -struct window_list *get_windows_by_pid(Display *disp, unsigned long pid, enum STATES *st) { - enum STATES tmpState; - struct window_list *wl; - bool displayProvided = false; - - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) { - *st = CAN_NOT_OPEN_DISPLAY; - return NULL; - } - - wl = get_windows_by(disp, &pid, predicate_pid, &tmpState); - - if (st) - *st = tmpState; - - if (!displayProvided) - XCloseDisplay(disp); - - return wl; -} - -static int predicate_class_name(struct window_info *wi, void *data) { - char *class_name = data; - return strcmp(wi->win_class, class_name) == 0; -} -struct window_list *get_windows_by_class_name(Display *disp, char *class_name, - enum STATES *st) { - enum STATES tmpState; - struct window_list *wl; - bool displayProvided = false; - - if (!disp) { - disp = XOpenDisplay(NULL); - displayProvided = false; - } - - if (!disp) { - *st = CAN_NOT_OPEN_DISPLAY; - return NULL; - } - - wl = get_windows_by(disp, class_name, predicate_class_name, &tmpState); - - if (st) - *st = tmpState; - - if (!displayProvided) - XCloseDisplay(disp); - - return wl; -} - -Window Select_Window(Display *dpy) { - /* - * Routine to let user select a window using the mouse - * Taken from xfree86. - */ - int status; - Cursor cursor; - XEvent event; - Window target_win = None, root = DefaultRootWindow(dpy); - int buttons = 0; - int dummyi; - unsigned int dummy; - - /* Make the target cursor */ - cursor = XCreateFontCursor(dpy, XC_crosshair); - - /* Grab the pointer using target cursor, letting it room all over */ - status = XGrabPointer(dpy, root, False, - ButtonPressMask|ButtonReleaseMask, GrabModeSync, - GrabModeAsync, root, cursor, CurrentTime); - if (status != GrabSuccess) { - fputs("ERROR: Cannot grab mouse.\n", stderr); - return 0; - } - - /* Let the user select a window... */ - while ((target_win == None) || (buttons != 0)) { - /* allow one more event */ - XAllowEvents(dpy, SyncPointer, CurrentTime); - XWindowEvent(dpy, root, ButtonPressMask|ButtonReleaseMask, &event); - switch (event.type) { - case ButtonPress: - if (target_win == None) { - target_win = event.xbutton.subwindow; /* window selected */ - if (target_win == None) target_win = root; - } - buttons++; - break; - case ButtonRelease: - if (buttons > 0) /* there may have been some down before we started */ - buttons--; - break; - } - } - - XUngrabPointer(dpy, CurrentTime); /* Done with pointer */ - - if (XGetGeometry (dpy, target_win, &root, &dummyi, &dummyi, - &dummy, &dummy, &dummy, &dummy) && target_win != root) { - target_win = XmuClientWindow (dpy, target_win); - } - - return(target_win); -} \ No newline at end of file diff --git a/libwmctrl/src/wmctrl.h b/libwmctrl/src/wmctrl.h deleted file mode 100644 index 3f9a103..0000000 --- a/libwmctrl/src/wmctrl.h +++ /dev/null @@ -1,261 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define _NET_WM_STATE_REMOVE 0 /* remove/unset property */ -#define _NET_WM_STATE_ADD 1 /* add/set property */ -#define _NET_WM_STATE_TOGGLE 2 /* toggle property */ - -#define MAX_PROPERTY_VALUE_LEN 4096 -#define SELECT_WINDOW_MAGIC ":SELECT:" -#define ACTIVE_WINDOW_MAGIC ":ACTIVE:" -#define MAX_WINDOWS_FOR_FILTER 50 - -struct geometry { - int x; - int y; - int abs_x; - int abs_y; - int width; - int height; -}; - -struct type_desc { - char *flag; - Atom number; -}; - -struct action_desc { - char *flag; - Atom number; -}; - -struct state_desc { - char *flag; - Atom number; -}; - -struct window_info { - Window win_id; - unsigned long win_pid; - unsigned long desktop_number; - unsigned long showing_desktop; - char *win_client_machine; - char *win_class; - struct type_desc *win_types; - size_t nbr_type; - struct action_desc *win_actions; - size_t nbr_action; - struct state_desc *win_states; - size_t nbr_state; - char *win_name; - char *win_visible_name; - char *win_icon_name; - char *win_visible_icon_name; - struct geometry *win_geometry; - XSizeHints *WM_NORMAL_HINTS; - long wm_normal_hints_supplied; - XSizeHints *WM_HINTS; - long wm_hints_supplied; - - Atom *net_wm_strut; - size_t nbr_net_wm_strut; - long *frame_extents; // left:[0],right:[1],top:[2],bottom:[3] -}; - -struct window_list { - struct window_info *client_list; - size_t client_list_size; -}; - -struct window_cache_list { - struct window_cache *heap; - size_t size; -}; - -struct window_cache { - Window win_id; - unsigned long win_pid; - char *win_class; - clock_t dead_time; - struct window_cache *next; -}; - -enum STATES { - CLIENT_LIST_GET = 0, - CAN_NOT_GET_CLIENT_LIST = 1, - - CAN_NOT_ALLOCATE_MEMORY = 2, - - CAN_NOT_OPEN_DISPLAY = 3, - CAN_NOT_CLOSE_DISPLAY = 4, - - VIEWPORT_CHANGED = 5, - CAN_NOT_CHANGE_VIEWPORT = 6, - - GEOMETRY_CHANGED = 7, - CAN_NOT_CHANGE_GEOMETRY = 8, - - WINDOW_ACTIVATED = 9, - CAN_NOT_ACTIVATE_WINDOW = 10, - - WINDOWS_ACTIVATED = 11, - - WINDOW_CLOSED = 12, - CAN_NOT_CLOSE_WINDOW = 13, - - WINDOWS_CLOSED = 14, - - WINDOW_ICON_NAME_SET = 15, - CAN_NOT_SET_WINDOW_ICON_NAME = 16, - - WINDOWS_ICON_NAME_SET = 17, - - WINDOW_TITLE_SET = 18, - CAN_NOT_SET_WINDOW_TITLE = 19, - - WINDOWS_TITLE_SET = 20, - - WINDOW_STATE_SET = 21, - CAN_NOT_SET_WINDOW_STATE = 22, - - WINDOWS_STATE_SET = 23, - NO_WINDOW_FOUND = 24, - UNKNOW_WINID = 25, - - WINDOW_MOVED_RESIZED = 26, - CAN_NOT_MOVE_RESIZE_WINDOW = 27, - - NO_WINDOW_ACTIVE_FOR_NOW = 28, - - WINDOW_MOVED_TO_DESKTOP = 29, - CAN_NOT_MOVE_WINDOW_TO_DESKTOP = 30, - - CAN_NOT_GET_CURRENT_DESKTOP_PROPERTY = 31, - SCREEN_GET = 32, - TOO_MANY_WINDOW_OPENED = 33, - - WINDOW_MINIMIZED = 34, - CAN_NOT_MINIMIZE_WINDOW = 35, - CAN_NOT_GET_WINDOW_ATTRIBUTES = 36, - - WINDOW_PROPERTY_GET = 37, - CAN_NOT_GET_WINDOW_PROPERTY = 38, - CHECKED_SUCCESS = 39, - WINDOW_ALLOWED_ALL_SIZE = 40, - - WINDOW_RAISED = 41, - CAN_NOT_RAISE_WINDOW = 42 -}; - -// NAPI -struct window_list *list_windows_napi(); - -// SCREEN -Screen *get_screen(Display *disp, enum STATES *st); -void free_screen(Screen *sc); - -// UTILS -bool init_wmctrl_lib(); -struct window_cache *init_window_cache(Window win, const char *win_class, - unsigned long win_pid); -struct window_cache *get_window_cache_by_id(struct window_cache_list *wcl, - Window win); -struct window_cache_list *init_window_list_cache(); -void add_window_cache(struct window_cache_list *wcl, Window win, - const char *win_class, unsigned long win_pid); -void free_window_cache_list(struct window_cache_list *wcl); - -struct window_list *list_windows(Display *disp, enum STATES *st); -char *get_error_message(enum STATES st); -int handler_x11_error(Display *d, XErrorEvent *e); - -void initializeWindowInfo(struct window_info *wi); -struct window_info *create_window_info(Display *disp, Window win, enum STATES *st); -void fill_window_info(Display *disp, struct window_info *wi, Window win); -void free_window_info_properties(struct window_info *wi); -void free_window_info(struct window_info *wi); -void free_window_list(struct window_list *wl); -void print_window_info(struct window_info *wi); -void copy_window_info(struct window_info *dest_wi, struct window_info *src_wi); - -char *get_output_str(char *str); -bool client_msg(Display *disp, Window win, char *msg, unsigned long data0, - unsigned long data1, unsigned long data2, unsigned long data3, - unsigned long data4); -Window *get_client_list(Display *disp, unsigned long *size); -bool winExists(Display *disp, Window win, enum STATES *st); - -// WINDOW-MANAGER -struct window_info *get_wm_info(Display *disp); -bool wm_supports(Display *disp, const char *prop); - -// DESKTOP -int switch_desktop(Display *disp, unsigned long target); -int change_number_of_desktops(Display *disp, unsigned long n); -// int list_desktops (Display *disp); -int showing_desktop(Display *disp, unsigned long state); - -// WINDOW-PROPERTIES -char *get_property(Display *disp, Window win, Atom xa_prop_type, - char *prop_name, unsigned long *size); -char *get_window_name(Display *disp, Window win); -char *get_window_visible_name(Display *disp, Window win); -char *get_window_icon_name(Display *disp, Window win); -char *get_window_visible_icon_name(Display *disp, Window win); -unsigned long get_window_desktop(Display *disp, Window win); -struct type_desc *get_window_types(Display *disp, Window win, size_t *size); -struct action_desc *get_window_allowed_actions(Display *disp, Window win, - size_t *size); -struct state_desc *get_window_states(Display *disp, Window win, size_t *size); -char *get_window_client_machine(Display *disp, Window win); -struct geometry *get_window_geometry(Display *disp, Window win); -unsigned long get_window_shwing_desktop(Display *disp, Window win); -char *get_window_class(Display *disp, Window win); -unsigned long get_window_pid(Display *disp, Window win); -Atom *get_window_net_wm_strut(Display *disp, Window win, size_t *size); -long *get_window_frame_extents(Display *disp, Window win); - -// WINDOW -struct window_info *get_active_window(Display *disp, enum STATES *st); -struct window_list *get_windows_by_pid(Display *disp, unsigned long pid, enum STATES *st); -struct window_list *get_windows_by_class_name(Display *disp, char *class_name, - enum STATES *st); - -// WINDOW-EDIT -enum STATES active_window_by_id(Display *disp, Window win); -enum STATES active_windows_by_pid(Display *disp, unsigned long pid); -enum STATES active_windows_by_class_name(Display *disp, const char *class_name); -enum STATES close_window_by_id(Display *disp, Window win); -enum STATES close_windows_by_pid(Display *disp, unsigned long pid); -enum STATES close_windows_by_class_name(Display *disp, const char *class_name); -enum STATES window_state(Display *disp, Window win, unsigned long action, - char *prop1_str, char *prop2_str); -enum STATES window_set_title(Display *disp, Window win, - const char *_net_wm_name); -enum STATES window_set_icon_name(Display *disp, Window win, - const char *_net_wm_icon_name); -enum STATES window_allow_all_sizes(Display *disp, Window win); - -enum STATES change_geometry(Display *disp, unsigned long x, unsigned long y); -enum STATES change_viewport(Display *disp, unsigned long x, unsigned long y); -enum STATES window_raise(Display *disp, Window win); -Window Select_Window(Display *dpy); - -// WINDOW-MOVE-RESIZE -enum STATES window_to_desktop(Display *disp, Window win, int desktop); -enum STATES window_to_current_desktop(Display *disp, Window win); -enum STATES window_move_resize(Display *disp, Window win, int32_t grav, - int32_t x, int32_t y, int32_t w, int32_t h); -enum STATES window_move_resize_transition(Display *disp, Window win, int32_t grav, - int32_t x, int32_t y, int32_t w, int32_t h, float await_time, int pad); -enum STATES window_minimize(Display *disp, Window window); \ No newline at end of file diff --git a/libwmctrl/test/test.c b/libwmctrl/test/test.c deleted file mode 100644 index feec43e..0000000 --- a/libwmctrl/test/test.c +++ /dev/null @@ -1,414 +0,0 @@ -#include "../src/wmctrl.h" -#include -#include -#include - -void test_list_window(Display *disp) { - struct window_list *wl = list_windows(disp, NULL); - printf("Window number %ld\n", wl->client_list_size); - for (int i = 0; i < wl->client_list_size; i++) { - print_window_info(wl->client_list + i); - } - free_window_list(wl); -} - -void debugend(char *test_name) { - printf("\n------- %s ok\n\n", test_name); -} - -struct codeInfos { - clock_t begin; - char *id; -}; - -struct codeInfos **times = NULL; -size_t size_times = 512; - -void timer(char *str) { - if (!times) - times = calloc(sizeof(struct codeInfos *), size_times); - - int64_t call_time = clock(); - //CREATE IF NOT EXIST - for (size_t i = 0; i < size_times; i++) { - if (!times[i]) { - times[i] = malloc(sizeof(struct codeInfos)); - if (!times[i]) - return; - - times[i]->id = strdup(str); - times[i]->begin = call_time; - break; - } - } -} - -void timerEnd(char *str) { - int64_t call_time = clock(); - for (size_t i = 0; i < size_times; i++) { - if (times[i] && strcmp(times[i]->id, str) == 0) { - double time_taken = ((double)(call_time - times[i]->begin))/1000; - printf("%s: %fms\n", times[i]->id, time_taken); - free(times[i]->id); - free(times[i]); - times[i] = NULL; - break; - } - } -} - -void wait_for_x11_server() { - printf("Temperize for X11 server\n"); - sleep(1); -} - -int main(int argc, char **argv) { - if (init_wmctrl_lib()) { - printf("wmctrl_lib initialised!\n"); - } - else { - printf("Can't initialise wmctrl_lib\n"); - return 1; - } - - char *winProcess = "xclock"; - char *class_name = "wmctrlTest.out.XClock";//"xclock.XClock"; - enum STATES st; - struct window_list *wl = NULL; - Screen *sc = NULL; - struct window_info *wi = NULL; - - for (size_t i = 0; i < 100; i++) { - timer("closeWindowById"); - close_window_by_id(NULL, 4); - timerEnd("closeWindowById"); - } - wait_for_x11_server(); - - for (size_t i = 0; i < 100; i++) { - timer("getScreen"); - sc = get_screen(NULL, &st); - timerEnd("getScreen"); - if (sc) - free_screen(sc); - } - wait_for_x11_server(); - - for (size_t i = 0; i < 100; i++) { - timer("getWindowList"); - wl = list_windows(NULL, &st); - free_window_list(wl); - timerEnd("getWindowList"); - } - wait_for_x11_server(); - - for (size_t i = 0; i < 100; i++) { - timer("closeWindowsByClassName"); - st = close_windows_by_class_name(NULL, class_name); - timerEnd("closeWindowsByClassName"); - if (st != WINDOWS_CLOSED) { - char *error = get_error_message(st); - if (error) { - printf("Voluntary error [Must failed] close of windows %s failed error:%s\n", class_name, error); - free(error); - if (st != NO_WINDOW_FOUND) - return 1; - } - else - printf("close of windows %s failed error:Unexpected\n", class_name); - } - } - - wait_for_x11_server(); - - for (int i = 0; i < 50; i++) { - if (fork() == 0) { - execvp(winProcess, argv); - return 1; - } else { - usleep(1000 * 100); - } - } - sleep(5); - - timer("getWindowsByClassName"); - wl = get_windows_by_class_name(class_name, &st); - timerEnd("getWindowsByClassName"); - if (!wl) { - char *error = get_error_message(st); - if (error) { - printf("%s\n", error); - free(error); - } - return 1; - } - printf("%ld windows are open with the class_name %s\n", wl->client_list_size, class_name); - - timer("activeWindowsByClassName"); - st = active_windows_by_class_name(NULL, class_name); - timerEnd("activeWindowsByClassName"); - if (st != WINDOWS_ACTIVATED) { - char *error = get_error_message(st); - if (error) { - printf("%s\n", error); - free(error); - } - } - wait_for_x11_server(); - sleep(1); - - for (size_t i = 0; i < wl->client_list_size; i++) { - wi = wl->client_list + i; - timer("closeWindowsByPid"); - st = close_windows_by_pid(NULL, wi->win_pid); - timerEnd("closeWindowsByPid"); - usleep(100 * 1000); - } - wait_for_x11_server(); - - timer("closeWindowsByClassName"); - st = close_windows_by_class_name(NULL, class_name); - timerEnd("closeWindowsByClassName"); - if (st != WINDOWS_CLOSED) { - char *error = get_error_message(st); - if (error) { - printf("Voluntary error [Must failed] %s\n", error); - free(error); - } - } - free_window_list(wl); - wait_for_x11_server(); - - for (size_t i = 0; i < 100; i++) { - timer("getActiveWindow"); - wi = get_active_window(&st); - timerEnd("getActiveWindow"); - char *error = get_error_message(st); - if (!error) { - printf("CAN_NOT_ALOCATE MEMORY\n"); - return 1; - } - if (st == NO_WINDOW_ACTIVE_FOR_NOW) - printf("Voluntary error [Must failed] %s\n", error); - else if (st != NO_WINDOW_ACTIVE_FOR_NOW) { - printf("Unexpected error %s", error); - free(error); - free_window_info(wi); - return 1; - } - free(error); - free_window_info(wi); - } - - if (fork() == 0) { - execvp("xeyes", argv); - return 1; - } - sleep(2); - - for (size_t i = 0; i < 100; i++) { - timer("activeWindowsByClassName"); - active_windows_by_class_name(NULL, "wmctrlTest.out.XEyes"); - timerEnd("activeWindowsByClassName"); - } - - wait_for_x11_server(); - - for (size_t i = 0; i < 100; i++) { - timer("getActiveWindow"); - wi = get_active_window(&st); - timerEnd("getActiveWindow"); - if (st != CLIENT_LIST_GET) { - char *error = get_error_message(st); - if (error) { - printf("%s\n", error); - free(error); - } - } - free_window_info(wi); - } - - wait_for_x11_server(); - - timer("getWindowsByClassName"); - wl = get_windows_by_class_name("wmctrlTest.out.XEyes", &st); - timerEnd("getWindowsByClassName"); - if (!wl || st != CLIENT_LIST_GET) { - char *error = get_error_message(st); - if (error) { - printf("%s\n", error); - free(error); - } - return 1; - } - - wait_for_x11_server(); - - wi = wl->client_list; - timer("windowMoveResize"); - st = window_move_resize(NULL, wi->win_id, 0, 0, 0, 500, 500); - timerEnd("windowMoveResize"); - if (st != WINDOW_MOVED_RESIZED) { - char *error = get_error_message(st); - if (error) { - printf("%s\n", error); - free(error); - } - return 1; - } - sleep(2); - - timer("windowMoveResize"); - st = window_move_resize(NULL, wi->win_id, 0, 0, 0, 1000, 1000); - timerEnd("windowMoveResize"); - if (st != WINDOW_MOVED_RESIZED) { - char *error = get_error_message(st); - if (error) { - printf("%s\n", error); - free(error); - } - return 1; - } - wait_for_x11_server(); - - timer("windowState"); - st = window_state(NULL, wi->win_id, _NET_WM_STATE_ADD, "maximized_vert", "maximized_horz"); - timerEnd("windowState"); - if (st != WINDOW_STATE_SET) { - char *error = get_error_message(st); - if (error) { - printf("%s\n", error); - free(error); - } - return 1; - } - wait_for_x11_server(); - - timer("windowState"); - st = window_state(NULL, wi->win_id, _NET_WM_STATE_REMOVE, "maximized_vert", "maximized_horz"); - timerEnd("windowState"); - if (st != WINDOW_STATE_SET) { - char *error = get_error_message(st); - if (error) { - printf("%s\n", error); - free(error); - } - return 1; - } - wait_for_x11_server(); - - timer("windowState"); - st = window_state(NULL, wi->win_id, _NET_WM_STATE_ADD, "fullscreen", NULL); - timerEnd("windowState"); - if (st != WINDOW_STATE_SET) { - char *error = get_error_message(st); - if (error) { - printf("%s\n", error); - free(error); - } - return 1; - } - wait_for_x11_server(); - - timer("windowState"); - st = window_state(NULL, wi->win_id, _NET_WM_STATE_REMOVE, "fullscreen", NULL); - timerEnd("windowState"); - if (st != WINDOW_STATE_SET) { - char *error = get_error_message(st); - if (error) { - printf("%s\n", error); - free(error); - } - return 1; - } - wait_for_x11_server(); - - timer("windowMinimize"); - st = window_minimize(NULL, wi->win_id); - timerEnd("windowMinimize"); - if (st != WINDOW_MINIMIZED) { - char *error = get_error_message(st); - if (error) { - printf("%s\n", error); - free(error); - } - return 1; - } - wait_for_x11_server(); - - timer("activeWindowById"); - st = active_window_by_id(NULL, wi->win_id); - timerEnd("activeWindowById"); - if (st != WINDOW_ACTIVATED) { - char *error = get_error_message(st); - if (error) { - printf("%s\n", error); - free(error); - } - return 1; - } - wait_for_x11_server(); - - timer("windowState"); - st = window_state(NULL, wi->win_id, _NET_WM_STATE_ADD, "fullscreen", NULL); - timerEnd("windowState"); - if (st != WINDOW_STATE_SET) { - char *error = get_error_message(st); - if (error) { - printf("%s\n", error); - free(error); - } - return 1; - } - wait_for_x11_server(); - - free_window_list(wl); - - timer("closeWindowsByClassName"); - st = close_windows_by_class_name(NULL, "wmctrlTest.out.XEyes"); - timerEnd("closeWindowsByClassName"); - if (st != WINDOWS_CLOSED) { - char *error = get_error_message(st); - if (error) { - printf("%s\n", error); - free(error); - } - return 1; - } - wait_for_x11_server(); - - if (fork() == 0) { - execvp("firefox", argv); - return 1; - } - sleep(5); - - wl = get_windows_by_class_name("Navigator.Firefox", NULL); - if (!wl) { - printf("No window found\n"); - return 1; - } - - wi = wl->client_list + wl->client_list_size -1; - - timer("windowAllowAllSizes"); - window_allow_all_sizes(NULL, wi->win_id); - timerEnd("windowAllowAllSizes"); - free_window_list(wl); - - wl = get_windows_by_class_name("Navigator.Firefox", NULL); //Refresh window list - wi = wl->client_list + wl->client_list_size -1; - if (!(wi->WM_NORMAL_HINTS->max_width == 0 && - wi->WM_NORMAL_HINTS->max_height == 0 && - wi->WM_NORMAL_HINTS->min_width == 0 && - wi->WM_NORMAL_HINTS->min_height == 0)) { - printf("window_allow_all_sizes failed\n"); - return 1; - } - close_window_by_id(NULL, wi->win_id); - free_window_list(wl); - - printf("ALL TEST ENDED WITH SUCESS\n"); - printf("DONE!\n"); - return 0; -} \ No newline at end of file diff --git a/native/.cargo/config.toml b/native/.cargo/config.toml new file mode 100644 index 0000000..d31d3ad --- /dev/null +++ b/native/.cargo/config.toml @@ -0,0 +1,3 @@ +# A cdylib cannot link musl statically: Node loads it next to its own libc. +[target.'cfg(target_env = "musl")'] +rustflags = ["-C", "target-feature=-crt-static"] diff --git a/native/Cargo.lock b/native/Cargo.lock new file mode 100644 index 0000000..4d1fd23 --- /dev/null +++ b/native/Cargo.lock @@ -0,0 +1,437 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "convert_case" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1af709f1f33454bf52eadfc8c78b3b9ef9cb26fb54d16dc9cd9a7299f899fd1b" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "ctor" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix", + "windows-link", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "754ca22de805bb5744484a5b151a9e1a8e837d5dc232c2d7d8c2e3492edc8b60" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "napi" +version = "3.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "907ff7366fb7182e28edd0f08ef8ac5d6b13b8d65a3c0b3a10bf3ac092437d6b" +dependencies = [ + "bitflags", + "ctor", + "futures", + "libc", + "napi-build", + "napi-sys", + "nohash-hasher", + "rustc-hash", + "serde", + "serde_json", +] + +[[package]] +name = "napi-build" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b899b545d3aa6dca985939059f258c5488d34e4ecf39c274e20009748f4b846d" + +[[package]] +name = "napi-derive" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d32eb00f92f84cf462fc328f49082b29c2a7d2eebeb1d447d19c1f9fdd9f89ee" +dependencies = [ + "convert_case", + "ctor", + "napi-derive-backend", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "napi-derive-backend" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1fe28c64d8fc12e69f9b817d0febdbe7914555760f1e353106281b8ff99cc90" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "semver", + "syn", +] + +[[package]] +name = "napi-sys" +version = "3.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d153beb7d5c973f4b9395be8a83054a28968b61188f1dd1a2cc2321af22daea2" +dependencies = [ + "libloading", +] + +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "foldhash", + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "wmctrljs" +version = "2.0.0" +dependencies = [ + "napi", + "napi-build", + "napi-derive", + "serde_json", + "x11rb", +] + +[[package]] +name = "x11rb" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a8885a854a8bfdf87a301e53e41b17c5f8f33639903131338b997b1eb614f44" +dependencies = [ + "gethostname", + "rustix", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acf4d1bc32aa46eec18caa634ec3cf4c05bfa151f12b93b510b15190f69a1ca8" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/native/Cargo.toml b/native/Cargo.toml new file mode 100644 index 0000000..bc2de3c --- /dev/null +++ b/native/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "wmctrljs" +version = "2.0.0" +edition = "2024" +publish = false + +[lib] +crate-type = ["cdylib"] + +[dependencies] +napi = { version = "3", features = ["serde-json"] } +napi-derive = "3" +serde_json = { version = "1", features = ["preserve_order"] } +x11rb = "0.14" + +[build-dependencies] +napi-build = "2" + +[profile.release] +lto = true +strip = true +# Size over speed: X round trips dominate, and every target ships in the package. +# Not "z": it breaks x11rb's packet reader on ppc64le (empty packet panic). +opt-level = "s" +codegen-units = 1 diff --git a/native/build.rs b/native/build.rs new file mode 100644 index 0000000..0f1b010 --- /dev/null +++ b/native/build.rs @@ -0,0 +1,3 @@ +fn main() { + napi_build::setup(); +} diff --git a/native/examples/fixture.rs b/native/examples/fixture.rs new file mode 100644 index 0000000..0cb7595 --- /dev/null +++ b/native/examples/fixture.rs @@ -0,0 +1,65 @@ +//! Test windows with known properties: `fixture [count] [legacy]`. +//! Prints one window id per line once mapped, exits once the WM closed all of them. +//! `legacy` windows only carry ICCCM properties: WM_CLASS, WM_NAME and 15-long WM_NORMAL_HINTS. + +use x11rb::connection::Connection; +use x11rb::protocol::Event; +use x11rb::protocol::xproto::*; +use x11rb::wrapper::ConnectionExt as _; + +fn main() -> Result<(), Box<dyn std::error::Error>> { + let args: Vec<String> = std::env::args().skip(1).collect(); + let instance = args.first().map_or("wmctrljs-fixture", |s| s); + let title = args.get(1).map_or("fixture", |s| s); + let count: usize = args.get(2).map_or(Ok(1), |s| s.parse())?; + let legacy = args.get(3).is_some_and(|s| s == "legacy"); + + let (c, n) = x11rb::connect(None)?; + let screen = &c.setup().roots[n]; + let atom = |name: &str| -> Result<Atom, Box<dyn std::error::Error>> { Ok(c.intern_atom(false, name.as_bytes())?.reply()?.atom) }; + let (utf8, protocols, delete) = (atom("UTF8_STRING")?, atom("WM_PROTOCOLS")?, atom("WM_DELETE_WINDOW")?); + + let mut wins = vec![]; + for _ in 0..count { + let win = c.generate_id()?; + let aux = CreateWindowAux::new().background_pixel(screen.white_pixel); + c.create_window(0, win, screen.root, 10, 10, 300, 200, 0, WindowClass::INPUT_OUTPUT, 0, &aux)?; + let set8 = |prop: Atom, ty: Atom, v: &[u8]| c.change_property8(PropMode::REPLACE, win, prop, ty, v); + let set32 = |prop: Atom, ty: Atom, v: &[u32]| c.change_property32(PropMode::REPLACE, win, prop, ty, v); + let string = AtomEnum::STRING.into(); + set8(AtomEnum::WM_CLASS.into(), string, format!("{instance}\0Fixture\0").as_bytes())?; + set8(AtomEnum::WM_NAME.into(), string, title.as_bytes())?; + set32(protocols, AtomEnum::ATOM.into(), &[delete])?; + if legacy { + // PMinSize, min 120x90, in the pre-ICCCM-1.0 15 long layout. + let hints = [16, 0, 0, 0, 0, 120, 90, 0, 0, 0, 0, 0, 0, 0, 0]; + set32(AtomEnum::WM_NORMAL_HINTS.into(), AtomEnum::WM_SIZE_HINTS.into(), &hints)?; + } else { + set8(atom("_NET_WM_NAME")?, utf8, format!("{title} ✓").as_bytes())?; + set8(atom("_NET_WM_ICON_NAME")?, utf8, b"fixture-icon")?; + set8(AtomEnum::WM_CLIENT_MACHINE.into(), string, b"fixture-host")?; + set32(atom("_NET_WM_PID")?, AtomEnum::CARDINAL.into(), &[std::process::id()])?; + set32(atom("_NET_WM_WINDOW_TYPE")?, AtomEnum::ATOM.into(), &[atom("_NET_WM_WINDOW_TYPE_NORMAL")?])?; + // PMinSize|PMaxSize|PBaseSize|PWinGravity, min 100x80, max 1000x800, base 10x20, NorthWest. + let hints = [816, 0, 0, 0, 0, 100, 80, 1000, 800, 0, 0, 0, 0, 0, 0, 10, 20, 1]; + set32(AtomEnum::WM_NORMAL_HINTS.into(), AtomEnum::WM_SIZE_HINTS.into(), &hints)?; + } + c.map_window(win)?; + wins.push(win); + } + c.sync()?; + for win in &wins { + println!("{win}"); + } + + while !wins.is_empty() { + if let Event::ClientMessage(ev) = c.wait_for_event()? + && ev.data.as_data32()[0] == delete + { + c.destroy_window(ev.window)?; + c.flush()?; + wins.retain(|w| *w != ev.window); + } + } + Ok(()) +} diff --git a/native/src/lib.rs b/native/src/lib.rs new file mode 100644 index 0000000..2796c5d --- /dev/null +++ b/native/src/lib.rs @@ -0,0 +1,293 @@ +//! N-API bindings: every operation is exported as `<name>Sync` and `<name>Async`. + +use napi::bindgen_prelude::*; +use napi_derive::napi; +use serde_json::Value; + +mod wm; +use wm::{By, Fail, Res}; + +pub struct Json(Value); + +impl TypeName for Json { + fn type_name() -> &'static str { + "Object" + } + + fn value_type() -> ValueType { + ValueType::Object + } +} + +impl ToNapiValue for Json { + unsafe fn to_napi_value(env: sys::napi_env, val: Self) -> Result<sys::napi_value> { + unsafe { Value::to_napi_value(env, val.0) } + } +} + +fn error(name: &str, fail: Fail) -> Error { + Error::from_reason(format!("[{name}] {fail}")) +} + +fn now(name: &str, res: Res) -> Result<Json> { + res.map(Json).map_err(|f| error(name, f)) +} + +type Op = Box<dyn FnOnce() -> Res + Send>; + +/// Runs an operation on the libuv thread pool and settles a promise with it. +pub struct Job(&'static str, Option<Op>); + +impl Task for Job { + type Output = Value; + type JsValue = Json; + + fn compute(&mut self) -> Result<Value> { + let op = self.1.take().expect("a job runs once"); + op().map_err(|f| error(self.0, f)) + } + + fn resolve(&mut self, _env: Env, out: Value) -> Result<Json> { + Ok(Json(out)) + } +} + +fn later(name: &'static str, op: impl FnOnce() -> Res + Send + 'static) -> AsyncTask<Job> { + AsyncTask::new(Job(name, Some(Box::new(op)))) +} + +#[napi] +pub fn get_screen_sync() -> Result<Json> { + now("getScreenSync", wm::screen()) +} + +#[napi] +pub fn get_screen_async() -> AsyncTask<Job> { + later("getScreen", wm::screen) +} + +#[napi] +pub fn get_window_by_id_sync(win_id: u32) -> Result<Json> { + now("getWindowByIdSync", wm::window(win_id)) +} + +#[napi] +pub fn get_window_by_id_async(win_id: u32) -> AsyncTask<Job> { + later("getWindowById", move || wm::window(win_id)) +} + +#[napi] +pub fn get_active_window_sync() -> Result<Json> { + now("getActiveWindowSync", wm::active_window()) +} + +#[napi] +pub fn get_active_window_async() -> AsyncTask<Job> { + later("getActiveWindow", wm::active_window) +} + +#[napi] +pub fn get_window_list_sync() -> Result<Json> { + now("getWindowListSync", wm::list()) +} + +#[napi] +pub fn get_window_list_async() -> AsyncTask<Job> { + later("getWindowList", wm::list) +} + +#[napi] +pub fn get_windows_by_pid_sync(win_pid: u32) -> Result<Json> { + now("getWindowsByPidSync", wm::windows_by(&By::Pid(win_pid))) +} + +#[napi] +pub fn get_windows_by_pid_async(win_pid: u32) -> AsyncTask<Job> { + later("getWindowsByPid", move || wm::windows_by(&By::Pid(win_pid))) +} + +#[napi] +pub fn get_windows_by_class_name_sync(win_class_name: String) -> Result<Json> { + now("getWindowsByClassNameSync", wm::windows_by(&By::Class(win_class_name))) +} + +#[napi] +pub fn get_windows_by_class_name_async(win_class_name: String) -> AsyncTask<Job> { + later("getWindowsByClassName", move || wm::windows_by(&By::Class(win_class_name))) +} + +#[napi] +pub fn active_window_by_id_sync(win_id: u32) -> Result<Json> { + now("activeWindowByIdSync", wm::activate(win_id)) +} + +#[napi] +pub fn active_window_by_id_async(win_id: u32) -> AsyncTask<Job> { + later("activeWindowById", move || wm::activate(win_id)) +} + +#[napi] +pub fn active_windows_by_pid_sync(win_pid: u32) -> Result<Json> { + now("activeWindowsByPidSync", wm::activate_by(&By::Pid(win_pid))) +} + +#[napi] +pub fn active_windows_by_pid_async(win_pid: u32) -> AsyncTask<Job> { + later("activeWindowsByPid", move || wm::activate_by(&By::Pid(win_pid))) +} + +#[napi] +pub fn active_windows_by_class_name_sync(win_class_name: String) -> Result<Json> { + now("activeWindowsByClassNameSync", wm::activate_by(&By::Class(win_class_name))) +} + +#[napi] +pub fn active_windows_by_class_name_async(win_class_name: String) -> AsyncTask<Job> { + later("activeWindowsByClassName", move || wm::activate_by(&By::Class(win_class_name))) +} + +#[napi] +pub fn close_window_by_id_sync(win_id: u32) -> Result<Json> { + now("closeWindowByIdSync", wm::close(win_id)) +} + +#[napi] +pub fn close_window_by_id_async(win_id: u32) -> AsyncTask<Job> { + later("closeWindowById", move || wm::close(win_id)) +} + +#[napi] +pub fn close_windows_by_pid_sync(win_pid: u32) -> Result<Json> { + now("closeWindowsByPidSync", wm::close_by(&By::Pid(win_pid))) +} + +#[napi] +pub fn close_windows_by_pid_async(win_pid: u32) -> AsyncTask<Job> { + later("closeWindowsByPid", move || wm::close_by(&By::Pid(win_pid))) +} + +#[napi] +pub fn close_windows_by_class_name_sync(win_class_name: String) -> Result<Json> { + now("closeWindowsByClassNameSync", wm::close_by(&By::Class(win_class_name))) +} + +#[napi] +pub fn close_windows_by_class_name_async(win_class_name: String) -> AsyncTask<Job> { + later("closeWindowsByClassName", move || wm::close_by(&By::Class(win_class_name))) +} + +#[napi] +pub fn window_move_resize_sync(win_id: u32, gravity: i32, x: i32, y: i32, width: i32, height: i32) -> Result<Json> { + now("windowMoveResizeSync", wm::move_resize(win_id, gravity, x, y, width, height)) +} + +#[napi] +pub fn window_move_resize_async(win_id: u32, gravity: i32, x: i32, y: i32, width: i32, height: i32) -> AsyncTask<Job> { + later("windowMoveResize", move || wm::move_resize(win_id, gravity, x, y, width, height)) +} + +#[napi] +#[allow(clippy::too_many_arguments)] +pub fn window_move_resize_transition_async( + win_id: u32, + gravity: i32, + x: i32, + y: i32, + width: i32, + height: i32, + await_time: f64, + pad: i32, +) -> AsyncTask<Job> { + later("windowMoveResizeTransition", move || { + wm::move_resize_transition(win_id, gravity, x, y, width, height, await_time, pad) + }) +} + +#[napi] +pub fn window_state_sync(win_id: u32, action: String, prop1: String, prop2: String) -> Result<Json> { + now("windowStateSync", wm::state(win_id, &action, &prop1, &prop2)) +} + +#[napi] +pub fn window_state_async(win_id: u32, action: String, prop1: String, prop2: String) -> AsyncTask<Job> { + later("windowState", move || wm::state(win_id, &action, &prop1, &prop2)) +} + +#[napi] +pub fn window_minimize_sync(win_id: u32) -> Result<Json> { + now("windowMinimizeSync", wm::minimize(win_id)) +} + +#[napi] +pub fn window_minimize_async(win_id: u32) -> AsyncTask<Job> { + later("windowMinimize", move || wm::minimize(win_id)) +} + +#[napi] +pub fn window_allow_all_sizes_sync(win_id: u32) -> Result<Json> { + now("windowAllowAllSizesSync", wm::allow_all_sizes(win_id)) +} + +#[napi] +pub fn window_allow_all_sizes_async(win_id: u32) -> AsyncTask<Job> { + later("windowAllowAllSizes", move || wm::allow_all_sizes(win_id)) +} + +#[napi] +pub fn window_raise_sync(win_id: u32) -> Result<Json> { + now("windowRaiseSync", wm::raise(win_id)) +} + +#[napi] +pub fn window_raise_async(win_id: u32) -> AsyncTask<Job> { + later("windowRaise", move || wm::raise(win_id)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn errors_are_prefixed_with_the_js_name() { + assert_eq!(error("getScreenSync", Fail::CanNotOpenDisplay).reason, "[getScreenSync] CAN_NOT_OPEN_DISPLAY (3)"); + assert_eq!(now("closeWindowsByPidSync", Err(Fail::NoWindowFound)).err().unwrap().reason, "[closeWindowsByPidSync] NO_WINDOW_FOUND (24)"); + assert_eq!(now("x", Ok(Value::Bool(true))).ok().unwrap().0, Value::Bool(true)); + } + + #[test] + fn jobs_compute_their_operation_once() { + let mut ok = Job("getWindowList", Some(Box::new(|| Ok(Value::Array(vec![]))))); + assert_eq!(ok.compute().unwrap(), Value::Array(vec![])); + let mut fail = Job("getWindowList", Some(Box::new(|| Err(Fail::CanNotGetClientList)))); + assert_eq!(fail.compute().unwrap_err().reason, "[getWindowList] CAN_NOT_GET_CLIENT_LIST (1)"); + assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| ok.compute())).is_err()); + } + + #[test] + fn no_display_fails_every_operation() { + // SAFETY: tests touching DISPLAY run in this single test. + unsafe { std::env::set_var("DISPLAY", ":4242") }; + let ops: Vec<(&str, Res)> = vec![ + ("screen", wm::screen()), + ("window", wm::window(1)), + ("active_window", wm::active_window()), + ("list", wm::list()), + ("windows_by", wm::windows_by(&By::Pid(1))), + ("activate", wm::activate(1)), + ("activate_by", wm::activate_by(&By::Class("a.A".into()))), + ("close", wm::close(1)), + ("close_by", wm::close_by(&By::Pid(1))), + ("move_resize", wm::move_resize(1, 0, 0, 0, 1, 1)), + ("move_resize_transition", wm::move_resize_transition(1, 0, 0, 0, 1, 1, 0.0, 1)), + ("state", wm::state(1, "ADD", "above", "")), + ("minimize", wm::minimize(1)), + ("allow_all_sizes", wm::allow_all_sizes(1)), + ("raise", wm::raise(1)), + ]; + for (name, res) in ops { + assert_eq!(res, Err(Fail::CanNotOpenDisplay), "{name}"); + } + // Validated before connecting. + assert_eq!(wm::state(1, "add", "above", ""), Err(Fail::CanNotSetWindowState)); + } +} diff --git a/native/src/wm.rs b/native/src/wm.rs new file mode 100644 index 0000000..f2eff77 --- /dev/null +++ b/native/src/wm.rs @@ -0,0 +1,959 @@ +//! EWMH window management spoken directly over the X11 protocol (x11rb): +//! no libX11/libXmu at build or run time. + +use std::{collections::HashMap, fmt, thread, time::Duration}; + +use serde_json::{Value, json}; +use x11rb::atom_manager; +use x11rb::connection::Connection; +use x11rb::cookie::Cookie; +use x11rb::errors::{ConnectionError, ReplyError}; +use x11rb::protocol::xproto::*; +use x11rb::rust_connection::RustConnection; +use x11rb::wrapper::ConnectionExt as _; + +const TYPES: &[&str] = &[ + "_NET_WM_WINDOW_TYPE_DESKTOP", + "_NET_WM_WINDOW_TYPE_DOCK", + "_NET_WM_WINDOW_TYPE_TOOLBAR", + "_NET_WM_WINDOW_TYPE_MENU", + "_NET_WM_WINDOW_TYPE_UTILITY", + "_NET_WM_WINDOW_TYPE_SPLASH", + "_NET_WM_WINDOW_TYPE_DIALOG", + "_NET_WM_WINDOW_TYPE_NORMAL", +]; + +const ACTIONS: &[&str] = &[ + "_NET_WM_ACTION_MOVE", + "_NET_WM_ACTION_RESIZE", + "_NET_WM_ACTION_MINIMIZE", + "_NET_WM_ACTION_SHADE", + "_NET_WM_ACTION_STICK", + "_NET_WM_ACTION_MAXIMIZE_HORZ", + "_NET_WM_ACTION_MAXIMIZE_VERT", + "_NET_WM_ACTION_FULLSCREEN", + "_NET_WM_ACTION_CHANGE_DESKTOP", + "_NET_WM_ACTION_CLOSE", +]; + +const STATES: &[&str] = &[ + "_NET_WM_STATE_MODAL", + "_NET_WM_STATE_STICKY", + "_NET_WM_STATE_MAXIMIZED_VERT", + "_NET_WM_STATE_MAXIMIZED_HORZ", + "_NET_WM_STATE_SHADED", + "_NET_WM_STATE_SKIP_TASKBAR", + "_NET_WM_STATE_SKIP_PAGER", + "_NET_WM_STATE_HIDDEN", + "_NET_WM_STATE_FULLSCREEN", + "_NET_WM_STATE_ABOVE", + "_NET_WM_STATE_BELOW", + "_NET_WM_STATE_DEMANDS_ATTENTION", +]; + +atom_manager! { + Atoms: AtomsCookie { + UTF8_STRING, + WM_VISIBLE_NAME, + WM_CHANGE_STATE, + _NET_SUPPORTED, + _NET_CLIENT_LIST, + _WIN_CLIENT_LIST, + _NET_ACTIVE_WINDOW, + _NET_CLOSE_WINDOW, + _NET_MOVERESIZE_WINDOW, + _NET_WM_PID, + _NET_WM_DESKTOP, + _WIN_WORKSPACE, + _NET_SHOWING_DESKTOP, + _NET_WM_WINDOW_TYPE, + _NET_WM_ALLOWED_ACTIONS, + _NET_WM_STATE, + _NET_WM_NAME, + _NET_WM_VISIBLE_NAME, + _NET_WM_ICON_NAME, + _NET_WM_VISIBLE_ICON_NAME, + _NET_FRAME_EXTENTS, + } +} + +/// Error codes kept identical to the former C `enum STATES`. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Fail { + CanNotGetClientList = 1, + CanNotOpenDisplay = 3, + CanNotActivateWindow = 10, + CanNotSetWindowState = 22, + NoWindowFound = 24, + CanNotMoveResizeWindow = 27, + NoWindowActiveForNow = 28, + CanNotGetWindowAttributes = 36, +} + +impl fmt::Display for Fail { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let name = match self { + Fail::CanNotGetClientList => "CAN_NOT_GET_CLIENT_LIST", + Fail::CanNotOpenDisplay => "CAN_NOT_OPEN_DISPLAY", + Fail::CanNotActivateWindow => "CAN_NOT_ACTIVATE_WINDOW", + Fail::CanNotSetWindowState => "CAN_NOT_SET_WINDOW_STATE", + Fail::NoWindowFound => "NO_WINDOW_FOUND", + Fail::CanNotMoveResizeWindow => "CAN_NOT_MOVE_RESIZE_WINDOW", + Fail::NoWindowActiveForNow => "NO_WINDOW_ACTIVE_FOR_NOW", + Fail::CanNotGetWindowAttributes => "CAN_NOT_GET_WINDOW_ATTRIBUTES", + }; + write!(f, "{name} ({})", *self as i32) + } +} + +// A broken connection mid-call is reported like a display that cannot be opened. +impl From<ConnectionError> for Fail { + fn from(_: ConnectionError) -> Self { + Fail::CanNotOpenDisplay + } +} + +impl From<ReplyError> for Fail { + fn from(_: ReplyError) -> Self { + Fail::CanNotOpenDisplay + } +} + +pub type Res = Result<Value, Fail>; + +pub enum By { + Pid(u32), + Class(String), +} + +type PropCookie<'c> = Cookie<'c, RustConnection, GetPropertyReply>; + +type Flags = HashMap<&'static str, Atom>; + +struct X { + c: RustConnection, + root: Window, + a: Atoms, + flags: Flags, +} + +/// Window info requests already sent to the server, waiting for their replies. +struct Pending<'c> { + win: Window, + props: [(Option<PropCookie<'c>>, Atom); 16], + geo: Option<Cookie<'c, RustConnection, GetGeometryReply>>, + abs: Option<Cookie<'c, RustConnection, TranslateCoordinatesReply>>, +} + +fn connect() -> Result<(RustConnection, usize), Fail> { + RustConnection::connect(None).map_err(|_| Fail::CanNotOpenDisplay) +} + +/// The property exists with the expected type (ANY accepts all). +fn accept(r: &GetPropertyReply, ty: Atom) -> bool { + r.type_ != x11rb::NONE && (ty == u32::from(AtomEnum::ANY) || r.type_ == ty) +} + +fn reply(ck: Option<PropCookie<'_>>, ty: Atom) -> Option<GetPropertyReply> { + ck?.reply().ok().filter(|r| accept(r, ty)) +} + +fn longs(r: Option<GetPropertyReply>) -> Vec<u32> { + r.and_then(|r| Some(r.value32()?.collect())).unwrap_or_default() +} + +fn card(r: Option<GetPropertyReply>) -> u32 { + longs(r).first().copied().unwrap_or(0) +} + +fn cstr(b: &[u8]) -> String { + String::from_utf8_lossy(b.split(|&c| c == 0).next().unwrap_or(&[])).into_owned() +} + +fn text(r: Option<GetPropertyReply>) -> Option<String> { + r.map(|r| cstr(&r.value)) +} + +/// WM_CLASS "instance\0Class\0" -> "instance.Class". +fn class(r: Option<GetPropertyReply>) -> Option<String> { + let mut v = r?.value; + if let Some(i) = v.iter().position(|&c| c == 0) + && i + 1 < v.len() + { + v[i] = b'.'; + } + Some(cstr(&v)) +} + +/// Mirrors XGetWMNormalHints: needs 15 longs, base size and gravity need all 18. +fn size_hints(r: Option<GetPropertyReply>) -> (u32, Value) { + let v: Vec<i32> = longs(r).into_iter().map(|n| n as i32).collect(); + let supplied = match v.len() { + 0..15 => 0, + 15..18 => 255, + _ => 1023, + }; + let f = |i: usize| if supplied == 0 || (i >= 15 && supplied != 1023) { 0 } else { v[i] }; + let hints = json!({ + "flags": f(0) as u32 & supplied, + "x": f(1), + "y": f(2), + "width": f(3), + "height": f(4), + "min_width": f(5), + "min_height": f(6), + "max_width": f(7), + "max_height": f(8), + "width_inc": f(9), + "height_inc": f(10), + "min_aspect": { "numerator": f(11), "denominator": f(12) }, + "max_aspect": { "numerator": f(13), "denominator": f(14) }, + "base_width": f(15), + "base_height": f(16), + "win_gravity": f(17), + }); + (supplied, hints) +} + +/// _NET_MOVERESIZE_WINDOW flags: gravity, plus one bit per value that is not -1 (untouched). +fn moveresize_flags(grav: i32, xywh: [i32; 4]) -> u32 { + xywh.iter().enumerate().filter(|(_, v)| **v != -1).fold(grav as u32, |f, (i, _)| f | 1 << (8 + i)) +} + +/// Plain ConfigureWindow used when the WM lacks _NET_MOVERESIZE_WINDOW. +fn fallback_geometry([x, y, w, h]: [i32; 4]) -> ConfigureWindowAux { + let mut aux = ConfigureWindowAux::new(); + if x >= 0 && y >= 0 { + aux = aux.x(x).y(y); + } + if w >= 1 && h >= 1 { + aux = aux.width(w as u32).height(h as u32); + } + aux +} + +/// Values a transition goes through from `from` to `to`, `pad` at a time. -1 never moves. +fn steps(from: i32, to: i32, pad: i32) -> Vec<i32> { + let mut v = vec![]; + let mut cur = from; + while to != -1 && cur != to { + cur = if cur < to { (cur + pad).min(to) } else { (cur - pad).max(to) }; + v.push(cur); + } + v +} + +/// Every (x, y, width, height) a transition requests; the last one is `to`. +fn transition(from: [i32; 4], to: [i32; 4], pad: i32) -> Vec<[i32; 4]> { + let paths: Vec<_> = (0..4).map(|i| steps(from[i], to[i], pad.max(1))).collect(); + let n = paths.iter().map(Vec::len).max().unwrap_or(0).max(1); + (0..n).map(|i| std::array::from_fn(|axis| paths[axis].get(i).copied().unwrap_or(to[axis]))).collect() +} + +/// _NET_WM_STATE action: REMOVE, ADD or TOGGLE. +fn state_action(action: &str) -> Option<u32> { + ["REMOVE", "ADD", "TOGGLE"].iter().position(|a| *a == action).map(|i| i as u32) +} + +fn state_atom_name(prop: &str) -> String { + format!("_NET_WM_STATE_{}", prop.to_uppercase()) +} + +/// Known EWMH flags among `atoms`, in property order. +fn descs(flags: &Flags, r: Option<GetPropertyReply>, names: &[&'static str]) -> Value { + longs(r) + .into_iter() + .flat_map(|atom| { + names + .iter() + .filter(move |n| flags[*n] == atom) + .map(move |n| json!({ "flag": n, "number": atom })) + }) + .collect() +} + +/// The JS window object, from the replies to the 16 properties `X::request` asks for. +fn window_json( + win: Window, + props: [Option<GetPropertyReply>; 16], + geo: Option<(GetGeometryReply, TranslateCoordinatesReply)>, + flags: &Flags, +) -> Value { + let [ + pid, + desktop, + showing, + machine, + wm_class, + types, + actions, + states, + net_name, + name, + net_visible, + visible, + icon, + visible_icon, + extents, + normal_hints, + ] = props; + let (supplied, normal_hints) = size_hints(normal_hints); + let mut w = json!({ + "win_id": win, + "win_pid": card(pid), + "desktop_number": card(desktop), + "showing_desktop": card(showing), + "win_client_machine": text(machine).unwrap_or_default(), + "win_class": class(wm_class).unwrap_or_default(), + "win_types": descs(flags, types, TYPES), + "win_actions": descs(flags, actions, ACTIONS), + "win_states": descs(flags, states, STATES), + "win_name": text(net_name).or_else(|| text(name)).unwrap_or_default(), + "win_visible_name": text(net_visible).or_else(|| text(visible)).unwrap_or_default(), + "win_icon_name": text(icon).unwrap_or_default(), + "win_visible_icon_name": text(visible_icon).unwrap_or_default(), + "wm_normal_hints_supplied": supplied, + "wm_hints_supplied": 0, + }); + if let Some((g, t)) = geo { + w["win_geometry"] = json!({ + "width": g.width, + "height": g.height, + "x": g.x, + "y": g.y, + "abs_x": t.dst_x, + "abs_y": t.dst_y, + }); + } + w["WM_NORMAL_HINTS"] = normal_hints; + // ponytail: WM_HINTS was always an empty XSizeHints in the C addon; kept for shape compatibility. + w["WM_HINTS"] = size_hints(None).1; + if let [left, right, top, bottom] = longs(extents)[..] { + w["frame_extents"] = json!({ "left": left, "right": right, "top": top, "bottom": bottom }); + } + w +} + +fn matches(w: &Value, by: &By) -> bool { + match by { + By::Pid(pid) => *pid != 0 && w["win_pid"] == *pid, + By::Class(class) => w["win_class"] == class.as_str(), + } +} + +fn screen_json(s: &Screen) -> Value { + json!({ + "backing_store": u32::from(s.backing_stores), + "black_pixel": s.black_pixel, + "cmap": s.default_colormap, + "height": s.height_in_pixels, + "max_maps": s.max_installed_maps, + "mheight": s.height_in_millimeters, + "min_maps": s.min_installed_maps, + "mwidth": s.width_in_millimeters, + "ndepths": s.allowed_depths.len(), + "root_depth": s.root_depth, + "root_input_mask": u32::from(s.current_input_masks), + "save_unders": u8::from(s.save_unders), + "white_pixel": s.white_pixel, + "width": s.width_in_pixels, + }) +} + +impl X { + fn open() -> Result<Self, Fail> { + let (c, screen) = connect()?; + let root = c.setup().roots[screen].root; + let names = TYPES.iter().chain(ACTIONS).chain(STATES); + let a = Atoms::new(&c)?; + let cookies = names + .clone() + .map(|n| c.intern_atom(false, n.as_bytes())) + .collect::<Result<Vec<_>, _>>()?; + let a = a.reply()?; + let flags = names + .zip(cookies) + .map(|(n, ck)| Ok((*n, ck.reply()?.atom))) + .collect::<Result<_, ReplyError>>()?; + Ok(X { c, root, a, flags }) + } + + /// Waits until the server has processed every request, like XCloseDisplay did. + fn done(self) -> Res { + self.c.sync()?; + Ok(Value::Bool(true)) + } + + fn get(&self, win: Window, prop: impl Into<Atom>, ty: impl Into<Atom>) -> Option<PropCookie<'_>> { + self.c.get_property(false, win, prop, ty, 0, u32::MAX).ok() + } + + fn prop(&self, win: Window, prop: Atom, ty: impl Into<Atom>) -> Option<GetPropertyReply> { + let ty = ty.into(); + reply(self.get(win, prop, ty), ty) + } + + fn msg(&self, win: Window, ty: Atom, data: [u32; 5]) -> Result<(), Fail> { + let ev = ClientMessageEvent::new(32, win, ty, data); + let mask = EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY; + self.c.send_event(false, self.root, mask, ev)?; + Ok(()) + } + + fn clients(&self) -> Result<Vec<Window>, Fail> { + self.prop(self.root, self.a._NET_CLIENT_LIST, AtomEnum::WINDOW) + .or_else(|| self.prop(self.root, self.a._WIN_CLIENT_LIST, AtomEnum::CARDINAL)) + .map(|r| longs(Some(r))) + .ok_or(Fail::CanNotGetClientList) + } + + fn request(&self, win: Window) -> Pending<'_> { + let a = &self.a; + let (card, string, atom) = (AtomEnum::CARDINAL.into(), AtomEnum::STRING.into(), AtomEnum::ATOM.into()); + let wanted: [(Atom, Atom); 16] = [ + (a._NET_WM_PID, card), + (a._NET_WM_DESKTOP, card), + (a._NET_SHOWING_DESKTOP, card), + (AtomEnum::WM_CLIENT_MACHINE.into(), string), + (AtomEnum::WM_CLASS.into(), string), + (a._NET_WM_WINDOW_TYPE, atom), + (a._NET_WM_ALLOWED_ACTIONS, atom), + (a._NET_WM_STATE, atom), + (a._NET_WM_NAME, a.UTF8_STRING), + (AtomEnum::WM_NAME.into(), string), + (a._NET_WM_VISIBLE_NAME, a.UTF8_STRING), + (a.WM_VISIBLE_NAME, string), + (a._NET_WM_ICON_NAME, a.UTF8_STRING), + (a._NET_WM_VISIBLE_ICON_NAME, a.UTF8_STRING), + (a._NET_FRAME_EXTENTS, AtomEnum::ANY.into()), + (AtomEnum::WM_NORMAL_HINTS.into(), AtomEnum::WM_SIZE_HINTS.into()), + ]; + Pending { + win, + props: wanted.map(|(p, ty)| (self.get(win, p, ty), ty)), + geo: self.c.get_geometry(win).ok(), + abs: self.c.translate_coordinates(win, self.root, 0, 0).ok(), + } + } + + fn window(&self, p: Pending<'_>) -> Value { + let geo = p.geo.and_then(|c| c.reply().ok()); + let abs = p.abs.and_then(|c| c.reply().ok()); + window_json(p.win, p.props.map(|(ck, ty)| reply(ck, ty)), geo.zip(abs), &self.flags) + } + + /// All client windows, fetched in a single pipelined round trip. + fn list(&self) -> Result<Vec<Value>, Fail> { + let pending: Vec<_> = self.clients()?.into_iter().map(|w| self.request(w)).collect(); + Ok(pending.into_iter().map(|p| self.window(p)).collect()) + } + + fn find(&self, by: &By) -> Result<Vec<Value>, Fail> { + let mut wins = self.list()?; + wins.retain(|w| matches(w, by)); + Ok(wins) + } + + fn find_ids(&self, by: &By) -> Result<Vec<Window>, Fail> { + let ids: Vec<Window> = self.find(by)?.iter().filter_map(|w| w["win_id"].as_u64()).map(|id| id as Window).collect(); + if ids.is_empty() { Err(Fail::NoWindowFound) } else { Ok(ids) } + } + + fn activate(&self, win: Window) -> Result<(), Fail> { + // Like the C addon: a window without a desktop is not an activable client. + if self.prop(win, self.a._NET_WM_DESKTOP, AtomEnum::CARDINAL).is_none() + && self.prop(win, self.a._WIN_WORKSPACE, AtomEnum::CARDINAL).is_none() + { + return Err(Fail::CanNotActivateWindow); + } + self.c.configure_window(win, &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE))?; + self.c.map_window(win)?; + self.msg(win, self.a._NET_ACTIVE_WINDOW, [0; 5]) + } + + fn supports(&self, atom: Atom) -> bool { + longs(self.prop(self.root, self.a._NET_SUPPORTED, AtomEnum::ATOM)).contains(&atom) + } + + fn move_resize(&self, win: Window, grav: i32, x: i32, y: i32, w: i32, h: i32) -> Result<(), Fail> { + if grav < 0 { + return Err(Fail::CanNotMoveResizeWindow); + } + if self.supports(self.a._NET_MOVERESIZE_WINDOW) { + let flags = moveresize_flags(grav, [x, y, w, h]); + return self.msg(win, self.a._NET_MOVERESIZE_WINDOW, [flags, x as u32, y as u32, w as u32, h as u32]); + } + self.c.configure_window(win, &fallback_geometry([x, y, w, h]))?; + Ok(()) + } +} + +pub fn screen() -> Res { + let (c, n) = connect()?; + Ok(screen_json(&c.setup().roots[n])) +} + +pub fn window(win: Window) -> Res { + let x = X::open()?; + Ok(x.window(x.request(win))) +} + +pub fn active_window() -> Res { + let x = X::open()?; + // C quirk kept: a WM without _NET_ACTIVE_WINDOW reports CAN_NOT_ACTIVATE_WINDOW. + let active = x + .prop(x.root, x.a._NET_ACTIVE_WINDOW, AtomEnum::WINDOW) + .ok_or(Fail::CanNotActivateWindow)?; + match card(Some(active)) { + 0 => Err(Fail::NoWindowActiveForNow), + win => Ok(x.window(x.request(win))), + } +} + +pub fn list() -> Res { + Ok(X::open()?.list()?.into()) +} + +pub fn windows_by(by: &By) -> Res { + Ok(X::open()?.find(by)?.into()) +} + +pub fn activate(win: Window) -> Res { + let x = X::open()?; + x.activate(win)?; + x.done() +} + +pub fn activate_by(by: &By) -> Res { + let x = X::open()?; + for win in x.find_ids(by)? { + x.activate(win)?; + } + x.done() +} + +pub fn close(win: Window) -> Res { + let x = X::open()?; + x.msg(win, x.a._NET_CLOSE_WINDOW, [0; 5])?; + x.done() +} + +pub fn close_by(by: &By) -> Res { + let x = X::open()?; + for win in x.find_ids(by)? { + x.msg(win, x.a._NET_CLOSE_WINDOW, [0; 5])?; + } + x.done() +} + +pub fn move_resize(win: Window, grav: i32, x: i32, y: i32, w: i32, h: i32) -> Res { + let c = X::open()?; + c.move_resize(win, grav, x, y, w, h)?; + c.done() +} + +/// Steps each of x/y/width/height `pad` pixels at a time towards the target, +/// waiting `await_ms` between steps. -1 leaves a value untouched. +#[allow(clippy::too_many_arguments)] +pub fn move_resize_transition(win: Window, grav: i32, x: i32, y: i32, w: i32, h: i32, await_ms: f64, pad: i32) -> Res { + let c = X::open()?; + if grav < 0 { + return Err(Fail::CanNotMoveResizeWindow); + } + let geo = c.c.get_geometry(win)?.reply()?; + let abs = c.c.translate_coordinates(win, c.root, 0, 0)?.reply()?; + let from = [abs.dst_x.into(), abs.dst_y.into(), geo.width.into(), geo.height.into()]; + for [x, y, w, h] in transition(from, [x, y, w, h], pad) { + c.move_resize(win, grav, x, y, w, h)?; + c.c.sync()?; + thread::sleep(Duration::from_secs_f64(await_ms.max(0.0) / 1000.0)); + } + c.done() +} + +pub fn state(win: Window, action: &str, prop1: &str, prop2: &str) -> Res { + let action = state_action(action).ok_or(Fail::CanNotSetWindowState)?; + let x = X::open()?; + let atom = |p: &str| -> Result<Atom, Fail> { + if p.is_empty() { + return Ok(0); + } + Ok(x.c.intern_atom(false, state_atom_name(p).as_bytes())?.reply()?.atom) + }; + x.msg(win, x.a._NET_WM_STATE, [action, atom(prop1)?, atom(prop2)?, 0, 0])?; + x.done() +} + +/// XIconifyWindow: ask the WM to switch the window to IconicState (3). +pub fn minimize(win: Window) -> Res { + let x = X::open()?; + x.c.get_window_attributes(win)?.reply().map_err(|_| Fail::CanNotGetWindowAttributes)?; + x.msg(win, x.a.WM_CHANGE_STATE, [3, 0, 0, 0, 0])?; + x.done() +} + +/// Replaces WM_NORMAL_HINTS with empty hints so the WM lifts any size constraint. +pub fn allow_all_sizes(win: Window) -> Res { + let x = X::open()?; + x.c.change_property32(PropMode::REPLACE, win, AtomEnum::WM_NORMAL_HINTS, AtomEnum::WM_SIZE_HINTS, &[0; 18])?; + x.done() +} + +pub fn raise(win: Window) -> Res { + let x = X::open()?; + x.c.configure_window(win, &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE))?; + x.done() +} + + +#[cfg(test)] +mod tests { + use super::*; + + const UTF8: Atom = 500; + + fn reply32(ty: impl Into<Atom>, v: &[u32]) -> Option<GetPropertyReply> { + let value: Vec<u8> = v.iter().flat_map(|n| n.to_ne_bytes()).collect(); + Some(GetPropertyReply { format: 32, sequence: 0, length: 0, type_: ty.into(), bytes_after: 0, value_len: v.len() as u32, value }) + } + + fn reply8(ty: impl Into<Atom>, v: &[u8]) -> Option<GetPropertyReply> { + Some(GetPropertyReply { format: 8, sequence: 0, length: 0, type_: ty.into(), bytes_after: 0, value_len: v.len() as u32, value: v.to_vec() }) + } + + /// Every known flag gets atom 1000 + its index in TYPES ++ ACTIONS ++ STATES. + fn flags() -> Flags { + TYPES.iter().chain(ACTIONS).chain(STATES).enumerate().map(|(i, n)| (*n, 1000 + i as u32)).collect() + } + + fn atom_of(name: &str) -> u32 { + flags()[name] + } + + #[test] + fn fail_messages_keep_the_c_codes() { + let all = [ + (Fail::CanNotGetClientList, "CAN_NOT_GET_CLIENT_LIST (1)"), + (Fail::CanNotOpenDisplay, "CAN_NOT_OPEN_DISPLAY (3)"), + (Fail::CanNotActivateWindow, "CAN_NOT_ACTIVATE_WINDOW (10)"), + (Fail::CanNotSetWindowState, "CAN_NOT_SET_WINDOW_STATE (22)"), + (Fail::NoWindowFound, "NO_WINDOW_FOUND (24)"), + (Fail::CanNotMoveResizeWindow, "CAN_NOT_MOVE_RESIZE_WINDOW (27)"), + (Fail::NoWindowActiveForNow, "NO_WINDOW_ACTIVE_FOR_NOW (28)"), + (Fail::CanNotGetWindowAttributes, "CAN_NOT_GET_WINDOW_ATTRIBUTES (36)"), + ]; + for (fail, msg) in all { + assert_eq!(fail.to_string(), msg); + } + } + + #[test] + fn connection_errors_map_to_can_not_open_display() { + assert_eq!(Fail::from(ConnectionError::UnknownError), Fail::CanNotOpenDisplay); + assert_eq!(Fail::from(ReplyError::from(ConnectionError::UnknownError)), Fail::CanNotOpenDisplay); + } + + #[test] + fn accept_checks_existence_and_type() { + let card = u32::from(AtomEnum::CARDINAL); + assert!(accept(&reply32(card, &[1]).unwrap(), card)); + assert!(!accept(&reply32(AtomEnum::ATOM, &[1]).unwrap(), card)); + assert!(!accept(&reply32(x11rb::NONE, &[]).unwrap(), card)); + assert!(accept(&reply32(card, &[1]).unwrap(), AtomEnum::ANY.into())); + assert!(!accept(&reply32(x11rb::NONE, &[]).unwrap(), AtomEnum::ANY.into())); + } + + #[test] + fn longs_and_card() { + assert_eq!(longs(reply32(AtomEnum::CARDINAL, &[1, 2, u32::MAX])), [1, 2, u32::MAX]); + assert_eq!(longs(reply8(AtomEnum::STRING, b"abcd")), Vec::<u32>::new()); + assert_eq!(longs(None), Vec::<u32>::new()); + assert_eq!(card(reply32(AtomEnum::CARDINAL, &[42, 7])), 42); + assert_eq!(card(reply32(AtomEnum::CARDINAL, &[])), 0); + assert_eq!(card(None), 0); + } + + #[test] + fn strings_stop_at_nul_and_survive_bad_utf8() { + assert_eq!(cstr(b"hello\0world"), "hello"); + assert_eq!(cstr(b""), ""); + assert_eq!(cstr("caf\u{e9} \u{2713}".as_bytes()), "caf\u{e9} \u{2713}"); + assert_eq!(cstr(b"bad\xff"), "bad\u{fffd}"); + assert_eq!(text(reply8(UTF8, b"title\0")), Some("title".into())); + assert_eq!(text(None), None); + } + + #[test] + fn wm_class_joins_instance_and_class() { + let c = |v: &[u8]| class(reply8(AtomEnum::STRING, v)); + assert_eq!(c(b"xeyes\0XEyes\0"), Some("xeyes.XEyes".into())); + assert_eq!(c(b"xeyes\0XEyes"), Some("xeyes.XEyes".into())); + assert_eq!(c(b"xeyes\0"), Some("xeyes".into())); + assert_eq!(c(b"xeyes"), Some("xeyes".into())); + assert_eq!(c(b"xeyes\0\0"), Some("xeyes.".into())); + assert_eq!(c(b""), Some("".into())); + assert_eq!(class(None), None); + } + + #[test] + fn size_hints_absent_or_short_are_all_zero() { + for r in [None, reply32(AtomEnum::WM_SIZE_HINTS, &[1; 14])] { + let (supplied, hints) = size_hints(r); + assert_eq!(supplied, 0); + assert_eq!(hints, size_hints(None).1); + assert_eq!(hints["min_aspect"], json!({ "numerator": 0, "denominator": 0 })); + } + } + + #[test] + fn size_hints_full_18_longs() { + let v: Vec<u32> = (0..18).map(|i| i * 10).collect(); + let mut v = v; + v[0] = 0xffff; // every flag bit, only the defined ones survive + v[1] = -5i32 as u32; + let (supplied, h) = size_hints(reply32(AtomEnum::WM_SIZE_HINTS, &v)); + assert_eq!(supplied, 1023); + assert_eq!( + h, + json!({ + "flags": 1023, "x": -5, "y": 20, "width": 30, "height": 40, + "min_width": 50, "min_height": 60, "max_width": 70, "max_height": 80, + "width_inc": 90, "height_inc": 100, + "min_aspect": { "numerator": 110, "denominator": 120 }, + "max_aspect": { "numerator": 130, "denominator": 140 }, + "base_width": 150, "base_height": 160, "win_gravity": 170, + }) + ); + let keys: Vec<_> = h.as_object().unwrap().keys().cloned().collect(); + assert_eq!(keys[0], "flags"); + assert_eq!(keys.last().unwrap(), "win_gravity"); + } + + #[test] + fn size_hints_old_15_to_17_longs_skip_base_and_gravity() { + for n in 15..18 { + let v: Vec<u32> = (1..=n).collect(); + let (supplied, h) = size_hints(reply32(AtomEnum::WM_SIZE_HINTS, &v)); + assert_eq!(supplied, 255, "{n} longs"); + assert_eq!(h["flags"], 1); + assert_eq!(h["max_aspect"]["denominator"], 15); + assert_eq!((h["base_width"].clone(), h["base_height"].clone(), h["win_gravity"].clone()), (json!(0), json!(0), json!(0))); + } + // PBaseSize / PWinGravity flags are dropped when not supplied. + let mut v = vec![0; 15]; + v[0] = 256 | 512 | 16; + assert_eq!(size_hints(reply32(AtomEnum::WM_SIZE_HINTS, &v)).1["flags"], 16); + } + + #[test] + fn size_hints_ignore_8_bit_data() { + assert_eq!(size_hints(reply8(AtomEnum::WM_SIZE_HINTS, &[1; 72])).0, 0); + } + + #[test] + fn descs_keep_property_order_and_skip_unknown_atoms() { + let f = flags(); + let r = reply32(AtomEnum::ATOM, &[atom_of("_NET_WM_STATE_ABOVE"), 4242, atom_of("_NET_WM_STATE_MODAL")]); + assert_eq!( + descs(&f, r, STATES), + json!([ + { "flag": "_NET_WM_STATE_ABOVE", "number": atom_of("_NET_WM_STATE_ABOVE") }, + { "flag": "_NET_WM_STATE_MODAL", "number": atom_of("_NET_WM_STATE_MODAL") }, + ]) + ); + // A type atom in the state list is not a state. + assert_eq!(descs(&f, reply32(AtomEnum::ATOM, &[atom_of("_NET_WM_WINDOW_TYPE_NORMAL")]), STATES), json!([])); + assert_eq!(descs(&f, None, TYPES), json!([])); + } + + #[test] + fn known_flag_lists_match_the_c_addon() { + assert_eq!((TYPES.len(), ACTIONS.len(), STATES.len()), (8, 10, 12)); + for n in TYPES.iter().chain(ACTIONS).chain(STATES) { + assert!(n.starts_with("_NET_WM_"), "{n}"); + } + } + + #[test] + fn window_json_of_a_window_without_properties() { + let w = window_json(7, Default::default(), None, &flags()); + let keys: Vec<_> = w.as_object().unwrap().keys().cloned().collect(); + assert_eq!( + keys, + [ + "win_id", "win_pid", "desktop_number", "showing_desktop", "win_client_machine", "win_class", + "win_types", "win_actions", "win_states", "win_name", "win_visible_name", "win_icon_name", + "win_visible_icon_name", "wm_normal_hints_supplied", "wm_hints_supplied", "WM_NORMAL_HINTS", "WM_HINTS", + ] + ); + assert_eq!(w["win_id"], 7); + assert_eq!(w["win_pid"], 0); + assert_eq!(w["win_class"], ""); + assert_eq!(w["win_name"], ""); + assert_eq!(w["win_types"], json!([])); + assert_eq!(w["WM_NORMAL_HINTS"], w["WM_HINTS"]); + } + + #[test] + fn window_json_with_every_property() { + let s = AtomEnum::STRING; + let card = AtomEnum::CARDINAL; + let props = [ + reply32(card, &[1234]), + reply32(card, &[u32::MAX]), + reply32(card, &[1]), + reply8(s, b"host"), + reply8(s, b"app\0App\0"), + reply32(AtomEnum::ATOM, &[atom_of("_NET_WM_WINDOW_TYPE_DIALOG")]), + reply32(AtomEnum::ATOM, &[atom_of("_NET_WM_ACTION_CLOSE"), atom_of("_NET_WM_ACTION_MOVE")]), + reply32(AtomEnum::ATOM, &[atom_of("_NET_WM_STATE_FULLSCREEN")]), + reply8(UTF8, "net \u{2713}".as_bytes()), + reply8(s, b"legacy"), + reply8(UTF8, b"net visible"), + reply8(s, b"legacy visible"), + reply8(UTF8, b"icon"), + reply8(UTF8, b"visible icon"), + reply32(card, &[1, 2, 3, 4]), + reply32(AtomEnum::WM_SIZE_HINTS, &[16, 0, 0, 0, 0, 10, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), + ]; + let geo = GetGeometryReply { depth: 24, sequence: 0, length: 0, root: 1, x: 1, y: 18, width: 300, height: 200, border_width: 0 }; + let abs = TranslateCoordinatesReply { same_screen: true, sequence: 0, length: 0, child: 0, dst_x: -20, dst_y: 30 }; + let w = window_json(9, props, Some((geo, abs)), &flags()); + assert_eq!(w["win_pid"], 1234); + assert_eq!(w["desktop_number"], u32::MAX); // sticky windows are on every desktop + assert_eq!(w["showing_desktop"], 1); + assert_eq!(w["win_client_machine"], "host"); + assert_eq!(w["win_class"], "app.App"); + assert_eq!(w["win_types"][0]["flag"], "_NET_WM_WINDOW_TYPE_DIALOG"); + assert_eq!(w["win_actions"].as_array().unwrap().len(), 2); + assert_eq!(w["win_states"][0]["flag"], "_NET_WM_STATE_FULLSCREEN"); + assert_eq!(w["win_name"], "net \u{2713}"); + assert_eq!(w["win_visible_name"], "net visible"); + assert_eq!(w["win_icon_name"], "icon"); + assert_eq!(w["win_visible_icon_name"], "visible icon"); + assert_eq!(w["win_geometry"], json!({ "width": 300, "height": 200, "x": 1, "y": 18, "abs_x": -20, "abs_y": 30 })); + assert_eq!(w["frame_extents"], json!({ "left": 1, "right": 2, "top": 3, "bottom": 4 })); + assert_eq!(w["wm_normal_hints_supplied"], 1023); + assert_eq!(w["WM_NORMAL_HINTS"]["min_height"], 20); + } + + #[test] + fn window_json_falls_back_to_legacy_names() { + let mut props: [Option<GetPropertyReply>; 16] = Default::default(); + props[9] = reply8(AtomEnum::STRING, b"legacy"); + props[11] = reply8(AtomEnum::STRING, b"legacy visible"); + let w = window_json(1, props, None, &flags()); + assert_eq!(w["win_name"], "legacy"); + assert_eq!(w["win_visible_name"], "legacy visible"); + } + + #[test] + fn frame_extents_need_exactly_four_values() { + for v in [&[1, 2, 3][..], &[1, 2, 3, 4, 5][..]] { + let mut props: [Option<GetPropertyReply>; 16] = Default::default(); + props[14] = reply32(AtomEnum::CARDINAL, v); + assert!(window_json(1, props, None, &flags()).get("frame_extents").is_none()); + } + } + + #[test] + fn matches_by_pid_and_class() { + let w = json!({ "win_pid": 42, "win_class": "app.App" }); + assert!(matches(&w, &By::Pid(42))); + assert!(!matches(&w, &By::Pid(43))); + assert!(matches(&w, &By::Class("app.App".into()))); + assert!(!matches(&w, &By::Class("app".into()))); + // pid 0 means "no _NET_WM_PID": it never matches. + assert!(!matches(&json!({ "win_pid": 0, "win_class": "" }), &By::Pid(0))); + } + + #[test] + fn screen_json_maps_every_field() { + let s = Screen { + root: 1, + default_colormap: 32, + white_pixel: 0xffffff, + black_pixel: 0, + current_input_masks: EventMask::from(7u32), + width_in_pixels: 1280, + height_in_pixels: 800, + width_in_millimeters: 325, + height_in_millimeters: 203, + min_installed_maps: 1, + max_installed_maps: 2, + root_visual: 33, + backing_stores: BackingStore::WHEN_MAPPED, + save_unders: true, + root_depth: 24, + allowed_depths: vec![Depth { depth: 24, visuals: vec![] }, Depth { depth: 1, visuals: vec![] }], + }; + assert_eq!( + screen_json(&s), + json!({ + "backing_store": 1, "black_pixel": 0, "cmap": 32, "height": 800, "max_maps": 2, "mheight": 203, + "min_maps": 1, "mwidth": 325, "ndepths": 2, "root_depth": 24, "root_input_mask": 7, + "save_unders": 1, "white_pixel": 0xffffff, "width": 1280, + }) + ); + } + + #[test] + fn moveresize_flags_mark_set_values() { + assert_eq!(moveresize_flags(0, [-1; 4]), 0); + assert_eq!(moveresize_flags(10, [-1; 4]), 10); + assert_eq!(moveresize_flags(1, [0, 0, 1, 1]), 1 | 0xf00); + assert_eq!(moveresize_flags(0, [5, -1, -1, 9]), 1 << 8 | 1 << 11); + assert_eq!(moveresize_flags(0, [-2, 0, 0, 0]), 0xf00); // only -1 means untouched + } + + #[test] + fn fallback_geometry_matches_the_c_rules() { + let g = |v| { + let a = fallback_geometry(v); + (a.x, a.y, a.width, a.height) + }; + assert_eq!(g([10, 20, 300, 200]), (Some(10), Some(20), Some(300), Some(200))); + assert_eq!(g([10, 20, -1, -1]), (Some(10), Some(20), None, None)); + assert_eq!(g([-1, -1, 300, 200]), (None, None, Some(300), Some(200))); + assert_eq!(g([-1, 5, 300, -1]), (None, None, None, None)); + assert_eq!(g([0, 0, 0, 1]), (Some(0), Some(0), None, None)); + } + + #[test] + fn steps_walk_towards_the_target() { + assert_eq!(steps(0, 10, 3), [3, 6, 9, 10]); + assert_eq!(steps(10, 0, 4), [6, 2, 0]); + assert_eq!(steps(5, 5, 1), Vec::<i32>::new()); + assert_eq!(steps(5, -1, 1), Vec::<i32>::new()); + assert_eq!(steps(0, 3, 100), [3]); + assert_eq!(steps(-30, -10, 10), [-20, -10]); + } + + #[test] + fn transition_ends_on_the_target_and_holds_finished_axes() { + let t = transition([0, 0, 100, 100], [20, 10, 100, 120], 10); + assert_eq!(t, [[10, 10, 100, 110], [20, 10, 100, 120]]); + assert_eq!(transition([5, 5, 5, 5], [5, 5, 5, 5], 1), [[5, 5, 5, 5]]); + assert_eq!(transition([0, 0, 10, 10], [-1, -1, 12, -1], 1), [[-1, -1, 11, -1], [-1, -1, 12, -1]]); + // pad <= 0 behaves like 1 instead of looping forever like the C addon. + assert_eq!(transition([0, 0, 0, 0], [2, 0, 0, 0], 0).len(), 2); + assert_eq!(transition([0, 0, 0, 0], [2, 0, 0, 0], -5).len(), 2); + let long = transition([0, 0, 50, 50], [1000, 500, 800, 600], 7); + assert_eq!(long.len(), 143); + assert_eq!(*long.last().unwrap(), [1000, 500, 800, 600]); + assert!(long.windows(2).all(|p| (0..4).all(|i| p[1][i] >= p[0][i]))); + } + + #[test] + fn state_action_and_atom_names() { + assert_eq!(state_action("REMOVE"), Some(0)); + assert_eq!(state_action("ADD"), Some(1)); + assert_eq!(state_action("TOGGLE"), Some(2)); + assert_eq!(state_action("add"), None); + assert_eq!(state_action(""), None); + assert_eq!(state_atom_name("maximized_vert"), "_NET_WM_STATE_MAXIMIZED_VERT"); + for s in STATES { + assert_eq!(state_atom_name(&s["_NET_WM_STATE_".len()..].to_lowercase()), *s); + } + } +} diff --git a/package.json b/package.json index 50ca3d4..132de4f 100644 --- a/package.json +++ b/package.json @@ -1,41 +1,59 @@ { "name": "wmctrljs", - "version": "1.2.8", - "description": "wmctrl natif code using n-api", + "version": "2.0.0", + "description": "Native X11 window management for Node.js (wmctrl and more), written in Rust, shipped prebuilt", "main": "dist/index.js", + "types": "dist/index.d.ts", + "files": [ + "dist/index.js", + "dist/index.d.ts", + "prebuilds" + ], "scripts": { - "install": "node-gyp-build", - "pre-build": "node-gyp configure", - "build:dev": "node-gyp build --debug && tsc", - "build": "node-gyp build && tsc", - "clean": "node-gyp clean && rm -r dist", - "test": "make -C libwmctrl runtest", - "start": "node dist/test.js" + "build:native": "node scripts/build-native.js", + "build": "tsc", + "test": "node --test dist/test/*.test.js" }, "repository": { "type": "git", "url": "git+https://github.com/Kmynes/wmctrljs.git" }, "keywords": [ - "wmctl", + "wmctrl", "n-api", + "napi-rs", "native", - "C", + "rust", "window", - "Xlib" + "x11", + "ewmh" ], "author": "kevin.voyer.developpeur@gmail.com", "license": "ISC", - "gypfile": true, "bugs": { - "url": "https://github.com/Kmynes/wmctrl/issues" + "url": "https://github.com/Kmynes/wmctrljs/issues" }, - "homepage": "https://github.com/Kmynes/wmctrl#readme", - "dependencies": { - "node-addon-api": "^2.0.0", - "node-gyp-build": "^4.2.0" + "homepage": "https://github.com/Kmynes/wmctrljs#readme", + "os": [ + "linux", + "freebsd", + "darwin", + "win32" + ], + "cpu": [ + "x64", + "arm64", + "arm", + "ia32", + "ppc64", + "s390x", + "riscv64" + ], + "engines": { + "node": ">=18" }, "devDependencies": { - "@types/node": "^13.1.6" + "@types/node": "^22", + "typescript": "^7.0.2" } } diff --git a/scripts/build-native.js b/scripts/build-native.js new file mode 100644 index 0000000..823210b --- /dev/null +++ b/scripts/build-native.js @@ -0,0 +1,28 @@ +// Builds the addon into prebuilds/<dir>/wmctrljs.node and the X11 test fixture into fixtures/<dir>/. +// Usage: node scripts/build-native.js [--target <rust triple>[.<glibc version>]] [--dir <platform>-<arch>[-musl]] [--zig] +// --zig cross-compiles with cargo-zigbuild, which also accepts a minimum glibc suffix (x86_64-unknown-linux-gnu.2.17). +const { parseArgs } = require("node:util"); +const { execFileSync } = require("node:child_process"); +const fs = require("node:fs"); +const path = require("node:path"); + +const { values: opts } = parseArgs({ options: { target: { type: "string" }, dir: { type: "string" }, zig: { type: "boolean" } } }); +const native = path.join(__dirname, "../native"); +const triple = opts.target?.replace(/(\.\d+)+$/, ""); +const musl = process.platform === "linux" && !process.report.getReport().header.glibcVersionRuntime; +const dir = opts.dir ?? `${process.platform}-${process.arch}${musl ? "-musl" : ""}`; +const platform = dir.split("-")[0]; +const run = (cmd, args) => execFileSync(cmd, args, { cwd: native, stdio: "inherit" }); + +if (triple) + run("rustup", ["target", "add", triple]); +// cwd is native/ so cargo picks up native/.cargo/config.toml. +run("cargo", [opts.zig ? "zigbuild" : "build", "--release", "--lib", "--example", "fixture", ...(opts.target ? ["--target", opts.target] : [])]); + +const out = path.join(native, "target", triple ?? "", "release"); +const lib = { win32: "wmctrljs.dll", darwin: "libwmctrljs.dylib" }[platform] ?? "libwmctrljs.so"; +const exe = platform === "win32" ? "fixture.exe" : "fixture"; +for (const d of ["prebuilds", "fixtures"]) + fs.mkdirSync(path.join(__dirname, "..", d, dir), { recursive: true }); +fs.copyFileSync(path.join(out, lib), path.join(__dirname, "../prebuilds", dir, "wmctrljs.node")); +fs.copyFileSync(path.join(out, "examples", exe), path.join(__dirname, "../fixtures", dir, exe)); diff --git a/src/debug.js b/src/debug.js deleted file mode 100644 index 350cbd2..0000000 --- a/src/debug.js +++ /dev/null @@ -1,18 +0,0 @@ -const wmctrl = require("../dist/index.js"); -const {wait} = require("../dist/unit-test/utils.js"); - -(async () => { - const promises = []; - for (let i = 0; i < 500; i++) - promises.push(wmctrl.getWindowById(0x02800001)); - - await Promise.all(promises); - console.log(await wmctrl.getWindowById(0x02800001)); - - const windows = await wmctrl.getWindowsByClassName("Navigator.Firefox"); - for (const win of windows) { - await wmctrl.activeWindowById(win.win_id); - } - console.log("Wait 5 second"); - await wait(5); -})() diff --git a/src/index.ts b/src/index.ts index 257949a..c90d3de 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,13 @@ -import * as path from "path"; -const root = path.join(__dirname, "../"); -const wmctrl = require('node-gyp-build')(root); +// glibc and musl (Alpine) Linux need different binaries. +const musl = process.platform === "linux" && !(process.report.getReport() as any).header?.glibcVersionRuntime; +const target = `${process.platform}-${process.arch}${musl ? "-musl" : ""}`; +const wmctrl = (() => { + try { + return require(`../prebuilds/${target}/wmctrljs.node`); + } catch (e) { + throw new Error(`wmctrljs: cannot load the binary for ${target}: ${(e as Error).message}`, { cause: e }); + } +})(); export interface TypeDesc { flag:string @@ -17,8 +24,8 @@ export interface Geometry { } export interface Aspect { - x:number /* numerator */ - y:number /* denominator */ + numerator:number + denominator:number } export interface XSizeHints { //Based on Xutils.h @@ -62,6 +69,7 @@ export interface Window { win_geometry:Geometry|undefined; wm_normal_hints_supplied:number; + wm_hints_supplied:number; WM_NORMAL_HINTS:XSizeHints|undefined; WM_HINTS:XSizeHints|undefined; desktop_number:number; @@ -103,8 +111,7 @@ export function getScreen():Promise<Screen> { } export function getWindowListSync():Window[] { - const windows = wmctrl.getWindowListSync(); - return !windows ? [] : windows; + return wmctrl.getWindowListSync(); } export function getWindowList():Promise<Window[]> { @@ -131,8 +138,7 @@ export function getActiveWindow():Promise<Window> { export function getWindowsByPidSync(win_pid:number):Window[] { expectParam("getWindowsByPid", "win_pid", win_pid, "number"); - const windows = wmctrl.getWindowsByPidSync(win_pid); - return !windows ? [] : windows; + return wmctrl.getWindowsByPidSync(win_pid); } export async function getWindowsByPid(win_pid:number):Promise<Window[]> { @@ -142,8 +148,7 @@ export async function getWindowsByPid(win_pid:number):Promise<Window[]> { export function getWindowsByClassNameSync(win_class_name:string):Window[] { expectParam("getWindowsByClassName", "win_class_name", win_class_name, "string"); - const windows = wmctrl.getWindowsByClassNameSync(win_class_name); - return !windows ? [] : windows; + return wmctrl.getWindowsByClassNameSync(win_class_name); } export async function getWindowsByClassName(win_class_name:string):Promise<Window[]> { @@ -239,7 +244,7 @@ export async function windowMoveResize(win_id:number, win_gravity:number, win_x: } export async function windowMoveResizeTransition(win_id:number, win_gravity:number, win_x:number, - win_y:number, win_width:number, win_height:number, await_time:number=1, pad:number=1) { + win_y:number, win_width:number, win_height:number, await_time:number=1, pad:number=1):Promise<boolean> { expectParam("windowMoveResizeTransition", "win_id", win_id, "number"); expectParam("windowMoveResizeTransition", "win_gravity", win_gravity, "number"); expectParam("windowMoveResizeTransition", "win_x", win_x, "number"); @@ -272,7 +277,7 @@ const enabledProperties = [ "above", "below" ]; -export function windowStateSync(win_id:number, action:string, prop1:string, prop2?:string) { +export function windowStateSync(win_id:number, action:string, prop1:string, prop2?:string):boolean { expectParam("windowState", "win_id", win_id, "number"); expectParam("windowState", "action", action, "string"); expectParam("windowState", "prop1", prop1, "string"); @@ -282,13 +287,13 @@ export function windowStateSync(win_id:number, action:string, prop1:string, prop prop1 = prop1.toLowerCase(); if (!enabledProperties.includes(prop1)) - throw new Error(`[windowState] property prop1 (${prop1}) is not an enabled property ${enabledActions.join(',')}`); + throw new Error(`[windowState] property prop1 (${prop1}) is not an enabled property ${enabledProperties.join(',')}`); if (prop2) { expectParam("windowState", "prop2", prop2, "string"); prop2 = prop2.toLowerCase(); if (!enabledProperties.includes(prop2)) - throw new Error(`[windowState] property prop2 (${prop2}) is not an enabled property ${enabledActions.join(',')}`); + throw new Error(`[windowState] property prop2 (${prop2}) is not an enabled property ${enabledProperties.join(',')}`); } else prop2 = ""; @@ -306,13 +311,13 @@ export async function windowState(win_id:number, action:string, prop1:string, pr prop1 = prop1.toLowerCase(); if (!enabledProperties.includes(prop1)) - throw new Error(`[windowState] property prop1 (${prop1}) is not an enabled property ${enabledActions.join(',')}`); + throw new Error(`[windowState] property prop1 (${prop1}) is not an enabled property ${enabledProperties.join(',')}`); if (prop2) { expectParam("windowState", "prop2", prop2, "string"); prop2 = prop2.toLowerCase(); if (!enabledProperties.includes(prop2)) - throw new Error(`[windowState] property prop2 (${prop2}) is not an enabled property ${enabledActions.join(',')}`); + throw new Error(`[windowState] property prop2 (${prop2}) is not an enabled property ${enabledProperties.join(',')}`); } else prop2 = ""; diff --git a/src/napi/active-window-by-id.cpp b/src/napi/active-window-by-id.cpp deleted file mode 100644 index 8c7c063..0000000 --- a/src/napi/active-window-by-id.cpp +++ /dev/null @@ -1,59 +0,0 @@ -#include "wmctrl-napi.hpp" - -using namespace Napi; - -class ActiveByIdWorker : public AsyncWorker { - public: - ActiveByIdWorker(Napi::Env &env, Promise::Deferred deferred, Window win_id) - : AsyncWorker(env), deferred(deferred), win_id(win_id), err(NULL) {} - ~ActiveByIdWorker() { - if (this->err) - free(this->err); - } - - void Execute() override { - st = active_window_by_id(NULL, win_id); - } - - void OnOK() override { - Napi::Env env = Env(); - String err_js; - - if (st != WINDOW_ACTIVATED) { - this->err = get_libwmctrl_error("activeWindowById", st); - err_js = String::New(env, this->err); - this->deferred.Reject(err_js); - } else { - this->deferred.Resolve(Boolean::New(env, true)); - } - } - - private: - Promise::Deferred deferred; - Window win_id; - char *err; - enum STATES st; -}; - -Boolean activeWindowByIdSync(const CallbackInfo &info) { - checkId(info, "activeWindowByIdSync"); - Env env = info.Env(); - int32_t win_id = info[0].As<Number>().Int32Value(); - enum STATES st = active_window_by_id(NULL, win_id); - - if (st != WINDOW_ACTIVATED) { - handling_libwmctrl_error(env, "activeWindowByIdSync", st); - return Boolean::New(env, false); - } - return Boolean::New(env, true); -} - -Promise activeWindowByIdAsync(const CallbackInfo &info) { - checkId(info, "activeWindowByIdAsync"); - Napi::Env env = info.Env(); - int32_t win_id = info[0].As<Number>().Int32Value(); - Promise::Deferred deferred = Promise::Deferred::New(env); - ActiveByIdWorker *wk = new ActiveByIdWorker(env, deferred, win_id); - wk->Queue(); - return deferred.Promise(); -} \ No newline at end of file diff --git a/src/napi/active-windows-by-className.cpp b/src/napi/active-windows-by-className.cpp deleted file mode 100644 index ea2e38f..0000000 --- a/src/napi/active-windows-by-className.cpp +++ /dev/null @@ -1,66 +0,0 @@ -#include "wmctrl-napi.hpp" - -using namespace Napi; - -class ActiveByClassNameWorker : public AsyncWorker { - public: - ActiveByClassNameWorker(Napi::Env &env, Promise::Deferred deferred, const char *win_class_name) - :AsyncWorker(env), deferred(deferred), win_class_name(strdup(win_class_name)), err(NULL){} - ~ActiveByClassNameWorker() { - if (this->win_class_name) - free(this->win_class_name); - - if (this->err) - free(err); - } - - void Execute() override { - st = active_windows_by_class_name(NULL, this->win_class_name); - } - - void OnOK() override { - Napi::Env env = Env(); - String err_js; - - if (this->st != WINDOWS_ACTIVATED) { - this->err = get_libwmctrl_error("activeWindowsByClassName", st); - err_js = String::New(env, this->err); - this->deferred.Reject(err_js); - } - else { - this->deferred.Resolve(Boolean::New(env, true)); - } - } - - private: - Promise::Deferred deferred; - char *win_class_name; - char *err; - enum STATES st; -}; - -Boolean activeWindowsByClassNameSync(const CallbackInfo &info) { - checkClassName(info, "activeWindowsByClassNameSync"); - Env env = info.Env(); - std::string win_class_name; - enum STATES st = active_windows_by_class_name(NULL, win_class_name.c_str()); - - if (st != WINDOWS_ACTIVATED) { - handling_libwmctrl_error(env, "activeWindowsByClassNameSync", st); - return Boolean::New(env, false); - } - - return Boolean::New(env, true); -} - -Promise activeWindowsByClassNameAsync(const CallbackInfo &info) { - checkClassName(info, "activeWindowsByClassName"); - std::string win_class_name; - Env env = info.Env(); - - win_class_name = info[0].As<String>().Utf8Value(); - Promise::Deferred deferred = Promise::Deferred::New(env); - ActiveByClassNameWorker *wk = new ActiveByClassNameWorker(env, deferred, win_class_name.c_str()); - wk->Queue(); - return deferred.Promise(); -} \ No newline at end of file diff --git a/src/napi/active-windows-by-pid.cpp b/src/napi/active-windows-by-pid.cpp deleted file mode 100644 index fc9f790..0000000 --- a/src/napi/active-windows-by-pid.cpp +++ /dev/null @@ -1,60 +0,0 @@ -#include "wmctrl-napi.hpp" - -using namespace Napi; - -class ActiveByPidWorker : public AsyncWorker { - public: - ActiveByPidWorker(Napi::Env &env, Promise::Deferred deferred, Window win_pid) - : AsyncWorker(env), deferred(deferred), win_pid(win_pid), err(NULL) {} - ~ActiveByPidWorker() { - if (this->err) - free(err); - } - - void Execute() override { - st = active_windows_by_pid(NULL, win_pid); - } - - void OnOK() override { - Napi::Env env = Env(); - String err_js; - - if (this->st != WINDOWS_ACTIVATED) { - this->err = get_libwmctrl_error("activeWindowsByPid", this->st); - err_js = String::New(env, this->err); - this->deferred.Reject(err_js); - }else { - this->deferred.Resolve(Boolean::New(env, true)); - } - } - - private: - Promise::Deferred deferred; - Window win_pid; - char *err; - enum STATES st; -}; - -Boolean activeWindowsByPidSync(const CallbackInfo &info) { - checkPid(info, "activeWindowsByPidSync"); - Env env = info.Env(); - int32_t win_pid = info[0].As<Number>().Int32Value(); - enum STATES st = active_windows_by_pid(NULL, win_pid); - - if (st != WINDOWS_ACTIVATED) { - handling_libwmctrl_error(env, "activeWindowsByPidSync", st); - return Boolean::New(env, false); - } - return Boolean::New(env, true); -} - -Promise activeWindowsByPidAsync(const CallbackInfo &info) { - checkPid(info, "activeWindowsByPid"); - Env env = info.Env(); - int32_t win_pid = info[0].As<Number>().Int32Value(); - - Promise::Deferred deferred = Promise::Deferred(env); - ActiveByPidWorker *wk = new ActiveByPidWorker(env, deferred, win_pid); - wk->Queue(); - return deferred.Promise(); -} \ No newline at end of file diff --git a/src/napi/allow-all-sizes-window.cpp b/src/napi/allow-all-sizes-window.cpp deleted file mode 100644 index 1ed8ce0..0000000 --- a/src/napi/allow-all-sizes-window.cpp +++ /dev/null @@ -1,60 +0,0 @@ -#include "wmctrl-napi.hpp" - -class AllowAllSizesWorker : public AsyncWorker { - public: - AllowAllSizesWorker(Napi::Env &env, Promise::Deferred deferred, Window id) - :AsyncWorker(env), deferred(deferred), id(id), err(NULL) { - - } - ~AllowAllSizesWorker() { - if (this->err) - free(this->err); - } - - void Execute() override { - this->st = window_allow_all_sizes(NULL, this->id); - } - - void OnOK() override { - Napi::Env env = Env(); - String err_js; - - if (this->st != WINDOW_ALLOWED_ALL_SIZE) { - this->err = get_libwmctrl_error("windowAllowAllSizes", this->st); - this->deferred.Reject(err_js); - } else { - this->deferred.Resolve(Boolean::New(env, true)); - } - } - - private: - Promise::Deferred deferred; - Window id; - char *err; - enum STATES st; -}; - -Promise windowAllowAllSizesAsync(const CallbackInfo &info) { - checkId(info, "windowAllowAllSizes"); - Napi::Env env = info.Env(); - int id = info[0].As<Number>(); - - Promise::Deferred deferred = Promise::Deferred(env); - AllowAllSizesWorker *wk = new AllowAllSizesWorker(env, deferred, id); - wk->Queue(); - return deferred.Promise(); -} - -Boolean windowAllowAllSizesSync(const CallbackInfo &info) { - checkId(info, "windowAllowAllSizesSync"); - Napi::Env env = info.Env(); - int id = info[0].As<Number>(); - enum STATES st = window_allow_all_sizes(NULL, id); - - if (st != WINDOW_ALLOWED_ALL_SIZE) { - handling_libwmctrl_error(env, "windowAllowAllSizesSync", st); - return Boolean::New(env, false); - } - - return Boolean::New(env, true); -} \ No newline at end of file diff --git a/src/napi/close-window-by-id.cpp b/src/napi/close-window-by-id.cpp deleted file mode 100644 index 2854464..0000000 --- a/src/napi/close-window-by-id.cpp +++ /dev/null @@ -1,59 +0,0 @@ -#include "wmctrl-napi.hpp" - -using namespace Napi; - -class CloseByIdWorker : public AsyncWorker { - public: - CloseByIdWorker(Napi::Env env, Promise::Deferred deferred, Window win_id) - : AsyncWorker(env), deferred(deferred), win_id(win_id), err(NULL) {} - ~CloseByIdWorker() { - if (this->err) - free(err); - } - - void Execute() override { - st = close_window_by_id(NULL, win_id); - } - - void OnOK() override { - Napi::Env env = Env(); - String err_js; - - if (st != WINDOW_CLOSED) { - this->err = get_libwmctrl_error("closeWindowById", st); - err_js = String::New(env, err); - this->deferred.Reject(err_js); - }else { - this->deferred.Resolve(Boolean::New(env, true)); - } - } - - private: - Promise::Deferred deferred; - Window win_id; - char *err; - enum STATES st; -}; - -Boolean closeWindowByIdSync(const CallbackInfo &info) { - checkId(info, "closeWindowById"); - Env env = info.Env(); - int32_t win_id = info[0].As<Number>().Int32Value(); - enum STATES st = close_window_by_id(NULL, win_id); - - if (st != WINDOW_CLOSED) { - handling_libwmctrl_error(env, "closeWindowByIdSync", st); - return Boolean::New(env, false); - } - return Boolean::New(env, true); -} - -Promise closeWindowByIdAsync(const CallbackInfo &info) { - checkId(info, "closeWindowById"); - Env env = info.Env(); - int32_t win_id = info[0].As<Number>().Int32Value(); - Promise::Deferred deferred = Promise::Deferred::New(env); - CloseByIdWorker *wk = new CloseByIdWorker(env, deferred, win_id); - wk->Queue(); - return deferred.Promise(); -} \ No newline at end of file diff --git a/src/napi/close-windows-by-className.cpp b/src/napi/close-windows-by-className.cpp deleted file mode 100644 index 77173c9..0000000 --- a/src/napi/close-windows-by-className.cpp +++ /dev/null @@ -1,61 +0,0 @@ -#include "wmctrl-napi.hpp" - -using namespace Napi; - -class CloseByClassNameWorker : public AsyncWorker { - public: - CloseByClassNameWorker(Napi::Env &env, Promise::Deferred deferred, const char *win_class_name) - :AsyncWorker(env), deferred(deferred), win_class_name(strdup(win_class_name)), err(NULL) {} - ~CloseByClassNameWorker() { - if (this->win_class_name) - free(this->win_class_name); - if (this->err) - free(this->err); - } - - void Execute() override { - st = close_windows_by_class_name(NULL, this->win_class_name); - } - - void OnOK() override { - Napi::Env env = Env(); - String err_js; - - if (st != WINDOWS_CLOSED) { - this->err = get_libwmctrl_error("closeWindowsByClassName", st); - err_js = String::New(env, this->err); - this->deferred.Reject(err_js); - }else { - this->deferred.Resolve(Boolean::New(env, true)); - } - } - - private: - Promise::Deferred deferred; - char *win_class_name; - char *err; - enum STATES st; -}; - -Boolean closeWindowsByClassNameSync(const CallbackInfo &info) { - checkClassName(info, "closeWindowsByClassNameSync"); - Env env = info.Env(); - std::string win_class_name = info[0].As<String>().Utf8Value();; - enum STATES st = close_windows_by_class_name(NULL, win_class_name.c_str()); - - if (st != WINDOWS_ACTIVATED) { - handling_libwmctrl_error(env, "closeWindowsByClassNameSync", st); - return Boolean::New(env, false); - } - return Boolean::New(env, true); -} - -Promise closeWindowsByClassNameAsync(const CallbackInfo &info) { - checkClassName(info, "closeWindowsByClassName"); - Env env = info.Env(); - std::string win_class_name = info[0].As<String>().Utf8Value(); - Promise::Deferred deferred = Promise::Deferred::New(env); - CloseByClassNameWorker *wk = new CloseByClassNameWorker(env, deferred, win_class_name.c_str()); - wk->Queue(); - return deferred.Promise(); -} \ No newline at end of file diff --git a/src/napi/close-windows-by-pid.cpp b/src/napi/close-windows-by-pid.cpp deleted file mode 100644 index 42e5f6a..0000000 --- a/src/napi/close-windows-by-pid.cpp +++ /dev/null @@ -1,59 +0,0 @@ -#include "wmctrl-napi.hpp" - -using namespace Napi; - -class CloseByPidWorker : public AsyncWorker { - public: - CloseByPidWorker(Napi::Env &env, Promise::Deferred deferred, Window win_pid) - : AsyncWorker(env), deferred(deferred), win_pid(win_pid) {} - ~CloseByPidWorker() {} - - void Execute() override { - st = close_windows_by_pid(NULL, win_pid); - } - - void OnOK() override { - Napi::Env env = Env(); - char *err; - String err_js; - - if (this->st != WINDOWS_CLOSED) { - err = get_libwmctrl_error("closeWindowsByPid", st); - err_js = String::New(env, err); - free(err); - this->deferred.Reject(err_js); - }else { - this->deferred.Resolve(Boolean::New(env, true)); - } - } - - private: - Promise::Deferred deferred; - Window win_pid; - enum STATES st; -}; - -Boolean closeWindowsByPidSync(const CallbackInfo &info) { - checkPid(info, "closeWindowsByPidSync"); - Env env = info.Env(); - int32_t win_pid = info[0].As<Number>().Int32Value(); - enum STATES st = close_windows_by_pid(NULL, win_pid); - - if (st != WINDOWS_ACTIVATED) { - handling_libwmctrl_error(env, "closeWindowsByPidSync", st); - return Boolean::New(env, false); - } - - return Boolean::New(env, true); -} - -Promise closeWindowsByPidAsync(const CallbackInfo &info) { - checkPid(info, "closeWindowsByPid"); - Napi::Env env = info.Env(); - int32_t win_pid = info[0].As<Number>().Int32Value(); - - Promise::Deferred deferred = Promise::Deferred::New(env); - CloseByPidWorker *wk = new CloseByPidWorker(env, deferred, win_pid); - wk->Queue(); - return deferred.Promise(); -} \ No newline at end of file diff --git a/src/napi/create_window_js.cpp b/src/napi/create_window_js.cpp deleted file mode 100644 index de589a8..0000000 --- a/src/napi/create_window_js.cpp +++ /dev/null @@ -1,152 +0,0 @@ -#include "./wmctrl-napi.hpp" - -Object create_geometry_js(Env env, struct geometry *geo) { - Object geo_js = Object::New(env); - - if (!geo) { - return geo_js; - } - - geo_js.Set("width", geo->width); - geo_js.Set("height", geo->height); - geo_js.Set("x", geo->x); - geo_js.Set("y", geo->y); - geo_js.Set("abs_x", geo->abs_x); - geo_js.Set("abs_y", geo->abs_y); - return geo_js; -} - -Object create_window_info_js(Env env, XSizeHints *xsize) { - Object xsize_js = Object::New(env); - Object min_aspect = Object::New(env); - Object max_aspect = Object::New(env); - - if (!xsize) { - return xsize_js; - } - - min_aspect.Set("numerator", xsize->min_aspect.x); - min_aspect.Set("denominator", xsize->min_aspect.y); - max_aspect.Set("numerator", xsize->max_aspect.x); - max_aspect.Set("denominator", xsize->max_aspect.y); - - min_aspect.Set("numerator", xsize->min_aspect.x); - min_aspect.Set("denominator", xsize->min_aspect.y); - max_aspect.Set("numerator", xsize->max_aspect.x); - max_aspect.Set("denominator", xsize->max_aspect.y); - - xsize_js.Set("flags", xsize->flags); - xsize_js.Set("x", xsize->x); - xsize_js.Set("y", xsize->y); - xsize_js.Set("width", xsize->width); - xsize_js.Set("height", xsize->height); - xsize_js.Set("min_width", xsize->min_width); - xsize_js.Set("min_height", xsize->min_height); - xsize_js.Set("max_width", xsize->max_width); - xsize_js.Set("max_height", xsize->max_height); - xsize_js.Set("width_inc", xsize->width_inc); - xsize_js.Set("height_inc", xsize->height_inc); - xsize_js.Set("width_inc", xsize->width_inc); - xsize_js.Set("height_inc", xsize->height_inc); - xsize_js.Set("min_aspect", min_aspect); - xsize_js.Set("max_aspect", max_aspect); - xsize_js.Set("base_width", xsize->base_width); - xsize_js.Set("base_height", xsize->base_height); - xsize_js.Set("win_gravity", xsize->win_gravity); - return xsize_js; -} - -Object create_window_js(Env env, struct window_info *wi) { - Object window_js = Object::New(env); - Array win_types_js = Array::New(env); - Array win_actions_js = Array::New(env); - Array win_states_js = Array::New(env); - Array net_wm_strut_js = Array::New(env); - Object frame_extents = Object::New(env); - - if (!wi) { - return window_js; - } - - window_js.Set("win_id", wi->win_id); - window_js.Set("win_pid", wi->win_pid); - window_js.Set("desktop_number", wi->desktop_number); - window_js.Set("showing_desktop", wi->showing_desktop); - window_js.Set("win_client_machine", wi->win_client_machine ? wi->win_client_machine : ""); - window_js.Set("win_class", wi->win_class ? wi->win_class : ""); - window_js.Set("win_types", win_types_js); - window_js.Set("win_actions", win_actions_js); - window_js.Set("win_states", win_states_js); - - if (wi->win_types) { - for (size_t i = 0; i < wi->nbr_type; i++) { - struct type_desc *desc = wi->win_types + i; - Object desc_js = Object::New(env); - if (desc) { - desc_js.Set("flag", desc->flag); - desc_js.Set("number", desc->number); - } - win_types_js[i] = desc_js; - } - } - - if (wi->win_actions) { - for (size_t i = 0; i < wi->nbr_action; i++) { - struct action_desc *desc = wi->win_actions + i; - Object desc_js = Object::New(env); - if (desc) { - desc_js.Set("flag", desc->flag); - desc_js.Set("number", desc->number); - } - win_actions_js[i] = desc_js; - } - } - - if (wi->win_states) { - for (size_t i = 0; i < wi->nbr_state; i++) { - struct state_desc *desc = wi->win_states + i; - Object desc_js = Object::New(env); - if (desc) { - desc_js.Set("flag", desc->flag); - desc_js.Set("number", desc->number); - } - win_states_js[i] = desc_js; - } - } - - window_js.Set("win_name", wi->win_name ? wi->win_name : ""); - window_js.Set("win_visible_name", wi->win_visible_name ? wi->win_visible_name : ""); - window_js.Set("win_visible_icon_name", wi->win_visible_icon_name ? wi->win_visible_icon_name : ""); - window_js.Set("wm_normal_hints_supplied", wi->wm_normal_hints_supplied); - window_js.Set("wm_hints_supplied", wi->wm_hints_supplied); - window_js.Set("wm_normal_hints_supplied", wi->wm_normal_hints_supplied); - - if (wi->win_geometry) { - window_js.Set("win_geometry", create_geometry_js(env, wi->win_geometry)); - } - - if (wi->WM_NORMAL_HINTS) { - window_js.Set("WM_NORMAL_HINTS", create_window_info_js(env, wi->WM_NORMAL_HINTS)); - } - - if (wi->WM_HINTS) { - window_js.Set("WM_HINTS", create_window_info_js(env, wi->WM_HINTS)); - } - - if (wi->net_wm_strut) { - for (size_t i = 0; i < wi->nbr_net_wm_strut; i++) { - net_wm_strut_js[i] = wi->net_wm_strut[i]; - } - window_js.Set("net_wm_strut", net_wm_strut_js); - } - - if (wi->frame_extents) { - frame_extents.Set("left", wi->frame_extents[0]); - frame_extents.Set("right", wi->frame_extents[1]); - frame_extents.Set("top", wi->frame_extents[2]); - frame_extents.Set("bottom", wi->frame_extents[3]); - window_js.Set("frame_extents", frame_extents); - } - - return window_js; -} diff --git a/src/napi/get-active-window.cpp b/src/napi/get-active-window.cpp deleted file mode 100644 index 30a126f..0000000 --- a/src/napi/get-active-window.cpp +++ /dev/null @@ -1,65 +0,0 @@ -#include "./wmctrl-napi.hpp" - -class GetActiveWindowWorker : public AsyncWorker { - public: - GetActiveWindowWorker(Napi::Env &env, Promise::Deferred deferred) - : AsyncWorker(env), deferred(deferred), wi(NULL), err(NULL) {} - ~GetActiveWindowWorker() { - if (this->wi) - free_window_info(this->wi); - - if (this->err) - free(this->err); - } - - void Execute() override { - this->wi = get_active_window(NULL, &this->st); - } - - void OnOK() override { - Napi::Env env = Env(); - Object window_js; - String err_js; - - if (this->st != CLIENT_LIST_GET) { - this->err = get_error_message(this->st); - err_js = String::New(env, this->err); - this->deferred.Reject(err_js); - } - else { - window_js = create_window_js(env, wi); - free_window_info(wi); - this->deferred.Resolve(window_js); - } - } - - private: - Promise::Deferred deferred; - struct window_info *wi; - char *err; - enum STATES st; -}; - -Promise getActiveWindowAsync(const CallbackInfo &info) { - Env env = info.Env(); - Promise::Deferred deferred = Promise::Deferred::New(env); - GetActiveWindowWorker *wk = new GetActiveWindowWorker(env, deferred); - wk->Queue(); - return deferred.Promise(); -} - -Value getActiveWindowSync(const CallbackInfo &info) { - Env env = info.Env(); - Object window_js; - enum STATES st; - struct window_info *wi = get_active_window(NULL, &st); - - if (!wi || st != CLIENT_LIST_GET) { - handling_libwmctrl_error(env, "getActiveWindowSync", st); - return env.Null(); - } - - window_js = create_window_js(env, wi); - free_window_info(wi); - return window_js; -} \ No newline at end of file diff --git a/src/napi/get-window-by-id.cpp b/src/napi/get-window-by-id.cpp deleted file mode 100644 index 2dd3839..0000000 --- a/src/napi/get-window-by-id.cpp +++ /dev/null @@ -1,71 +0,0 @@ -#include "wmctrl-napi.hpp" - -class GetByIdWorker : public AsyncWorker { - public: - GetByIdWorker(Napi::Env &env, Promise::Deferred deferred, Window id) - :AsyncWorker(env), deferred(deferred), id(id), wi(NULL), error(NULL) {} - ~GetByIdWorker() { - if (this->wi) - free_window_info(this->wi); - - if (this->error) - free(this->error); - } - - void Execute() override { - this->wi = create_window_info(NULL, this->id, &this->st); - } - - void OnOK() override { - Napi::Env env = Env(); - Object wi_js; - String error_js; - if (this->st != WINDOW_PROPERTY_GET) { - this->error = get_error_message(this->st); - error_js = String::New(env, this->error); - this->deferred.Reject(error_js); - } else { - wi_js = create_window_js(env, this->wi); - this->deferred.Resolve(wi_js); - } - } - - private: - Promise::Deferred deferred; - Window id; - struct window_info *wi; - char *error; - enum STATES st; -}; - -Promise getWindowByIdAsync(const CallbackInfo &info) { - checkId(info, "getWindowById"); - Env env = info.Env(); - - int id = info[0].As<Number>(); - Promise::Deferred deferred = Promise::Deferred::New(env); - GetByIdWorker *wk = new GetByIdWorker(env, deferred, (Window)id); - wk->Queue(); - - return deferred.Promise(); -} - -Value getWindowByIdSync(const CallbackInfo &info) { - checkId(info, "getWindowByIdSync"); - Env env = info.Env(); - Object wi_js; - int id = info[0].As<Number>(); - enum STATES st; - struct window_info *wi; - - wi = create_window_info(NULL, id, &st); - if (st != WINDOW_PROPERTY_GET) { - handling_libwmctrl_error(env, "getWindowByIdSync", st); - return Boolean::New(env, false); - } - - wi_js = create_window_js(env, wi); - free_window_info(wi); - - return wi_js; -} \ No newline at end of file diff --git a/src/napi/get-window-list.cpp b/src/napi/get-window-list.cpp deleted file mode 100644 index b93eaab..0000000 --- a/src/napi/get-window-list.cpp +++ /dev/null @@ -1,87 +0,0 @@ -#include "./wmctrl-napi.hpp" - - -class GetWindowListWorker : public AsyncWorker { - public: - GetWindowListWorker(Napi::Env &env, Promise::Deferred deferred) - : AsyncWorker(env), deferred(deferred), wl(NULL), err(NULL) {} - ~GetWindowListWorker() { - if (this->wl) { - free_window_list(this->wl); - } - - if (this->err) { - free(this->err); - } - } - - void Execute() override { - this->wl = list_windows(NULL, &this->st); - } - - void OnOK() override { - Napi::Env env = Env(); - String err_js; - Array windows_js; - struct window_info *wi; - - if (this->st != CLIENT_LIST_GET) { - this->err = get_error_message(this->st); - if (this->err) { - err_js = String::New(env, "Memory alloc failed"); - } else { - err_js = String::New(env, this->err); - } - this->deferred.Reject(err_js); - } else { - if (this->wl) { - windows_js = Array::New(env, this->wl->client_list_size); - - for (size_t i = 0; i < this->wl->client_list_size; i++) { - wi = this->wl->client_list + i; - windows_js[i] = create_window_js(env, wi); - } - - this->deferred.Resolve(windows_js); - } else { - this->deferred.Reject(String::New(env, "Memory alloc failed")); - } - } - } - - private: - Promise::Deferred deferred; - struct window_list *wl; - char *err; - enum STATES st; -}; - -Promise getWindowListAsync(const CallbackInfo &info) { - Napi::Env env = info.Env(); - Promise::Deferred deferred = Promise::Deferred::New(env); - GetWindowListWorker *wk = new GetWindowListWorker(env, deferred); - wk->Queue(); - return deferred.Promise(); -} - -Value getWindowListSync(const CallbackInfo &info) { - Napi::Env env = info.Env(); - Array windows_js; - enum STATES st; - struct window_info *wi; - struct window_list *wl = list_windows(NULL, &st); - - if (st != CLIENT_LIST_GET) { - handling_libwmctrl_error(env, "getWindowListSync", st); - return env.Null(); - } - - windows_js = Array::New(env, wl->client_list_size); - for (size_t i = 0; i < wl->client_list_size; i++) { - wi = wl->client_list + i; - windows_js[i] = create_window_js(env, wi); - } - free_window_list(wl); - - return windows_js; -} \ No newline at end of file diff --git a/src/napi/get-windows-by-className.cpp b/src/napi/get-windows-by-className.cpp deleted file mode 100644 index 8542ff5..0000000 --- a/src/napi/get-windows-by-className.cpp +++ /dev/null @@ -1,86 +0,0 @@ -#include "./wmctrl-napi.hpp" - -class GetWindowsByClassName : public AsyncWorker { - public: - GetWindowsByClassName(Napi::Env &env, Promise::Deferred deferred, const char *class_name) - : AsyncWorker(env), deferred(deferred), class_name(strdup(class_name)), wl(NULL), err(NULL) {} - ~GetWindowsByClassName() { - if (this->class_name) - free(this->class_name); - - if (this->wl) - free_window_list(this->wl); - - if (this->err) - free(this->err); - } - - void Execute() override { - if (this->class_name) - this->wl = get_windows_by_class_name(NULL, this->class_name, &this->st); - } - - void OnOK() override { - Napi::Env env = Env(); - Array windows_js; - String err_js; - struct window_info *wi; - - if (this->st != CLIENT_LIST_GET) { - this->err = get_libwmctrl_error("getWindowByClassName", this->st); - err_js = String::New(env, this->err); - this->deferred.Reject(err_js); - } else { - windows_js = Array::New(env, this->wl->client_list_size); - for (size_t i = 0; i < this->wl->client_list_size; i++) { - wi = this->wl->client_list + i; - windows_js[i] = create_window_js(env, wi); - } - this->deferred.Resolve(windows_js); - } - } - - private: - Promise::Deferred deferred; - char *class_name; - struct window_list *wl; - char *err; - enum STATES st; -}; - -Promise getWindowsByClassNameAsync(const CallbackInfo &info) { - checkClassName(info, "getWindowsByClassNameAsync"); - Napi::Env env = info.Env(); - std::string class_name = info[0].As<String>().Utf8Value(); - - Promise::Deferred deferred = Promise::Deferred::New(env); - GetWindowsByClassName *wk = new GetWindowsByClassName(env, deferred, class_name.c_str()); - wk->Queue(); - - return deferred.Promise(); -} - -Value getWindowsByClassNameSync(const CallbackInfo &info) { - checkClassName(info, "getWindowsByClassNameSync"); - Napi::Env env = info.Env(); - std::string class_name = info[0].As<String>().Utf8Value(); - Array windows_js; - enum STATES st; - struct window_list *wl; - struct window_info *wi; - - wl = get_windows_by_class_name(NULL, (char *)class_name.c_str(), &st); - if (st != CLIENT_LIST_GET) { - handling_libwmctrl_error(env, "getWindowsByClassNameSync", st); - return env.Null(); - } - - windows_js = Array::New(env, wl->client_list_size); - for (size_t i = 0; i < wl->client_list_size; i++) { - wi = wl->client_list + i; - windows_js[i] = create_window_js(env, wi); - } - - free_window_list(wl); - return windows_js; -} \ No newline at end of file diff --git a/src/napi/get-windows-by-pid.cpp b/src/napi/get-windows-by-pid.cpp deleted file mode 100644 index 1681f23..0000000 --- a/src/napi/get-windows-by-pid.cpp +++ /dev/null @@ -1,82 +0,0 @@ -#include "./wmctrl-napi.hpp" - -class GetWindowsByPid : public AsyncWorker { - public: - GetWindowsByPid(Napi::Env &env, Promise::Deferred deferred, unsigned long pid) - : AsyncWorker(env), deferred(deferred), pid(pid), wl(NULL), err(NULL) {} - ~GetWindowsByPid() { - if (this->wl) - free_window_list(this->wl); - - if (this->err) - free(this->err); - } - - void Execute() override { - this->wl = get_windows_by_pid(NULL, this->pid, &this->st); - } - - void OnOK() override { - Napi::Env env = Env(); - Array windows_js; - String err_js; - struct window_info *wi; - - if (this->st != CLIENT_LIST_GET) { - this->err = get_libwmctrl_error("getWindowByClassName", this->st); - err_js = String::New(env, this->err); - this->deferred.Reject(err_js); - } else { - windows_js = Array::New(env, this->wl->client_list_size); - for (size_t i = 0; i < this->wl->client_list_size; i++) { - wi = this->wl->client_list + i; - windows_js[i] = create_window_js(env, wi); - } - this->deferred.Resolve(windows_js); - } - } - - private: - Promise::Deferred deferred; - unsigned long pid; - struct window_list *wl; - char *err; - enum STATES st; -}; - -Promise getWindowsByPidAsync(const CallbackInfo &info) { - checkPid(info, "getWindowsByPidAsync"); - Napi::Env env = info.Env(); - unsigned int pid = info[0].As<Number>(); - - Promise::Deferred deferred = Promise::Deferred::New(env); - GetWindowsByPid *wk = new GetWindowsByPid(env, deferred, pid); - wk->Queue(); - - return deferred.Promise(); -} - -Value getWindowsByPidSync(const CallbackInfo &info) { - checkPid(info, "getWindowsByPidSync"); - Napi::Env env = info.Env(); - Array windows_js; - unsigned int pid = info[0].As<Number>(); - enum STATES st; - struct window_list *wl; - struct window_info *wi; - - wl = get_windows_by_pid(NULL, pid, &st); - if (st != CLIENT_LIST_GET) { - handling_libwmctrl_error(env, "getWindowsByPidSync", st); - return env.Null(); - } - - windows_js = Array::New(env, wl->client_list_size); - for (size_t i = 0; i < wl->client_list_size; i++) { - wi = wl->client_list + i; - windows_js[i] = create_window_js(env, wi); - } - - free_window_list(wl); - return windows_js; -} \ No newline at end of file diff --git a/src/napi/getScreen.cpp b/src/napi/getScreen.cpp deleted file mode 100644 index a467522..0000000 --- a/src/napi/getScreen.cpp +++ /dev/null @@ -1,80 +0,0 @@ -#include "wmctrl-napi.hpp" - -Object create_screen(Env env, Screen *sc) { - Object screen_js = Object::New(env); - screen_js.Set("backing_store", sc->backing_store); - screen_js.Set("black_pixel", sc->black_pixel); - screen_js.Set("cmap", sc->cmap); - screen_js.Set("height", sc->height); - screen_js.Set("max_maps", sc->max_maps); - screen_js.Set("mheight", sc->mheight); - screen_js.Set("min_maps", sc->min_maps); - screen_js.Set("mwidth", sc->mwidth); - screen_js.Set("ndepths", sc->ndepths); - screen_js.Set("root_depth", sc->root_depth); - screen_js.Set("root_input_mask", sc->root_input_mask); - screen_js.Set("save_unders", sc->save_unders); - screen_js.Set("white_pixel", sc->white_pixel); - screen_js.Set("width", sc->width); - return screen_js; -} - -class GetScreenWorker : public AsyncWorker { - public: - GetScreenWorker(Napi::Env &env, Promise::Deferred deferred) - : AsyncWorker(env), deferred(deferred){} - ~GetScreenWorker() {} - - void Execute() override { - this->sc = get_screen(NULL, &this->st); - } - - void OnOK() override { - Object sc_js; - String err_js; - char *err; - - if (this->st != SCREEN_GET) { - err = get_error_message(st); - err_js = String::New(Env(), err); - free(err); - this->deferred.Reject(err_js); - } else { - sc_js = create_screen(Env(), this->sc); - free_screen(this->sc); - this->deferred.Resolve(sc_js); - } - } - - void OnError(Napi::Error const &error) override { - this->deferred.Reject(error.Value()); - } - - private: - enum STATES st; - Screen *sc; - Promise::Deferred deferred; -}; - -Promise getScreenAsync(const CallbackInfo &info) { - Napi::Env env = info.Env(); - Promise::Deferred deferred = Promise::Deferred::New(env); - GetScreenWorker *wk = new GetScreenWorker(env, deferred); - wk->Queue(); - return deferred.Promise(); -} - -Value getScreenSync(const CallbackInfo &info) { - Env env = info.Env(); - Object screen_js; - enum STATES st; - Screen *sc = get_screen(NULL, &st); - if (!sc || st != SCREEN_GET) { - handling_libwmctrl_error(env, "getScreenSync", st); - return env.Null(); - } - - screen_js = create_screen(env, sc); - free_screen(sc); - return screen_js; -} \ No newline at end of file diff --git a/src/napi/minimize-window.cpp b/src/napi/minimize-window.cpp deleted file mode 100644 index d75368d..0000000 --- a/src/napi/minimize-window.cpp +++ /dev/null @@ -1,60 +0,0 @@ -#include "wmctrl-napi.hpp" - -class MinimizeWorker : public AsyncWorker { - public: - MinimizeWorker(Napi::Env &env, Promise::Deferred deferred, Window id) - :AsyncWorker(env), deferred(deferred), id(id), err(NULL) {} - ~MinimizeWorker() { - if (this->err) - free(this->err); - } - - void Execute() override { - this->st = window_minimize(NULL, this->id); - } - - void OnOK() override { - Napi::Env env = Env(); - String err_js; - - if (this->st != WINDOW_MINIMIZED) { - this->err = get_libwmctrl_error("windowMinimize", this->st); - this->deferred.Reject(err_js); - } else { - this->deferred.Resolve(Boolean::New(env, true)); - } - } - - private: - Promise::Deferred deferred; - Window id; - char *err; - enum STATES st; -}; - -Promise windowMinimizeAsync(const CallbackInfo &info) { - checkId(info, "windowMinimize"); - Napi::Env env = info.Env(); - int id = info[0].As<Number>(); - - Promise::Deferred deferred = Promise::Deferred(env); - MinimizeWorker *wk = new MinimizeWorker(env, deferred, id); - wk->Queue(); - return deferred.Promise(); -} - -Boolean windowMinimizeSync(const CallbackInfo &info) { - checkId(info, "windowMinimizeSync"); - Napi::Env env = info.Env(); - int id = info[0].As<Number>(); - enum STATES st; - - st = window_minimize(NULL, id); - - if (st != WINDOW_MINIMIZED) { - handling_libwmctrl_error(env, "windowMinimizeSync", st); - return Boolean::New(env, false); - } - - return Boolean::New(env, true); -} \ No newline at end of file diff --git a/src/napi/move-resize-window.cpp b/src/napi/move-resize-window.cpp deleted file mode 100644 index 8ac4950..0000000 --- a/src/napi/move-resize-window.cpp +++ /dev/null @@ -1,85 +0,0 @@ -#include "wmctrl-napi.hpp" - -class MoveResizeWorker : public AsyncWorker { - public: - MoveResizeWorker(Napi::Env &env, Promise::Deferred deferred, Window id, int g, int x, int y, int w, int h) - : AsyncWorker(env), deferred(deferred), id(id), g(g), x(x), y(y), w(w), h(h), err(NULL){} - ~MoveResizeWorker() { - if (this->err) - free(this->err); - } - - void Execute() override { - this->st = window_move_resize(NULL, id, g, x, y, w, h); - } - - void OnOK() override { - Napi::Env env = Env(); - String err_js; - - if (this->st != WINDOW_MOVED_RESIZED) { - this->err = get_libwmctrl_error("MoveResizeWorker", this->st); - err_js = String::New(env, this->err); - this->deferred.Reject(err_js); - } - else { - this->deferred.Resolve(Boolean::New(env, true)); - } - } - - private: - Promise::Deferred deferred; - Window id; - int g,x,y,w,h; - char *err; - enum STATES st; -}; - -Promise windowMoveResizeAsync(const CallbackInfo &info) { - checkNumber(info, "moveResizeWindow", "id", 0); - checkNumber(info, "moveResizeWindow", "gravity", 1); - checkNumber(info, "moveResizeWindow", "x", 2); - checkNumber(info, "moveResizeWindow", "y", 3); - checkNumber(info, "moveResizeWindow", "width", 4); - checkNumber(info, "moveResizeWindow", "height", 5); - Napi::Env env = info.Env(); - - int id = info[0].As<Number>(); - int g = info[1].As<Number>(); - int x = info[2].As<Number>(); - int y = info[3].As<Number>(); - int w = info[4].As<Number>(); - int h = info[5].As<Number>(); - - Promise::Deferred deferred = Promise::Deferred::New(env); - MoveResizeWorker *wk = new MoveResizeWorker(env, deferred, id, g, x, y, w, h); - wk->Queue(); - - return deferred.Promise(); -} - -Boolean windowMoveResizeSync(const CallbackInfo &info) { - checkNumber(info, "moveResizeWindow", "id", 0); - checkNumber(info, "moveResizeWindow", "gravity", 1); - checkNumber(info, "moveResizeWindow", "x", 2); - checkNumber(info, "moveResizeWindow", "y", 3); - checkNumber(info, "moveResizeWindow", "width", 4); - checkNumber(info, "moveResizeWindow", "height", 5); - - Napi::Env env = info.Env(); - enum STATES st; - int id = info[0].As<Number>(); - int g = info[1].As<Number>(); - int x = info[2].As<Number>(); - int y = info[3].As<Number>(); - int w = info[4].As<Number>(); - int h = info[5].As<Number>(); - - st = window_move_resize(NULL, id, g, x, y, w, h); - - if (st != WINDOW_MOVED_RESIZED) { - handling_libwmctrl_error(env, "moveResizeWindowSync", st); - return Boolean::New(env, false); - } - return Boolean::New(env, true); -} \ No newline at end of file diff --git a/src/napi/raise-window.cpp b/src/napi/raise-window.cpp deleted file mode 100644 index 1aec217..0000000 --- a/src/napi/raise-window.cpp +++ /dev/null @@ -1,62 +0,0 @@ -#include "wmctrl-napi.hpp" - -class RaiseWorker : public AsyncWorker { - public: - RaiseWorker(Napi::Env &env, Promise::Deferred deferred, Window id) - :AsyncWorker(env), deferred(deferred), id(id), err(NULL) { - - } - ~RaiseWorker() { - if (this->err) - free(this->err); - } - - void Execute() override { - this->st = window_raise(NULL, this->id); - } - - void OnOK() override { - Napi::Env env = Env(); - String err_js; - - if (this->st != WINDOW_RAISED) { - this->err = get_libwmctrl_error("windowRaise", this->st); - this->deferred.Reject(err_js); - } else { - this->deferred.Resolve(Boolean::New(env, true)); - } - } - - private: - Promise::Deferred deferred; - Window id; - char *err; - enum STATES st; -}; - -Promise windowRaiseAsync(const CallbackInfo &info) { - checkId(info, "windowRaise"); - Napi::Env env = info.Env(); - int id = info[0].As<Number>(); - - Promise::Deferred deferred = Promise::Deferred(env); - RaiseWorker *wk = new RaiseWorker(env, deferred, id); - wk->Queue(); - return deferred.Promise(); -} - -Boolean windowRaiseSync(const CallbackInfo &info) { - checkId(info, "windowRaiseSync"); - Napi::Env env = info.Env(); - int id = info[0].As<Number>(); - enum STATES st; - - st = window_raise(NULL, id); - - if (st != WINDOW_RAISED) { - handling_libwmctrl_error(env, "windowRaiseSync", st); - return Boolean::New(env, false); - } - - return Boolean::New(env, true); -} \ No newline at end of file diff --git a/src/napi/update-window-state.cpp b/src/napi/update-window-state.cpp deleted file mode 100644 index 9c8b442..0000000 --- a/src/napi/update-window-state.cpp +++ /dev/null @@ -1,121 +0,0 @@ -#include "./wmctrl-napi.hpp" - -class UpdateStateWorker: public AsyncWorker { - public: - UpdateStateWorker(Napi::Env &env, Promise::Deferred deferred, Window win, unsigned long action, char *p1, char *p2) - :AsyncWorker(env), deferred(deferred), win(win), action(action), err(NULL) { - this->p1 = p1 ? strdup(p1) : NULL; - this->p2 = p2 ? strdup(p2) : NULL; - } - ~UpdateStateWorker() { - if (this->err) - free(this->err); - - if (this->p1) - free(this->p1); - - if (this->p2) - free(this->p2); - } - - void Execute() override { - this->st = window_state(NULL, this->win, this->action, this->p1, this->p2); - } - - void OnOK() override { - Napi::Env env = Env(); - String err_js; - - if (this->st != WINDOW_STATE_SET) { - this->err = get_libwmctrl_error("windowState", this->st); - err_js = String::New(env, this->err); - this->deferred.Reject(err_js); - } else { - this->deferred.Resolve(Boolean::New(env, true)); - } - } - - private: - Promise::Deferred deferred; - Window win; - unsigned long action; - char *p1; - char *p2; - char *err; - enum STATES st; -}; - -Promise windowStateAsync(const CallbackInfo &info) { - Napi::Env env = info.Env(); - int win_id; - char *action; - char *p1; - char *p2; - char msg[128]; - unsigned long action_number = 0; - - win_id = info[0].As<Number>(); - action = strdup(info[1].As<String>().Utf8Value().c_str()); - p1 = strdup(info[2].As<String>().Utf8Value().c_str()); - p2 = strdup(info[3].As<String>().Utf8Value().c_str()); - - if (strcmp(action, "REMOVE") == 0) - action_number = _NET_WM_STATE_REMOVE; - else if (strcmp(action, "ADD") == 0) - action_number = _NET_WM_STATE_ADD; - else if (strcmp(action, "TOGGLE") == 0) - action_number = _NET_WM_STATE_TOGGLE; - else { - sprintf(msg, "[windowState] bad action provided (%s)", action); - Napi::Error::New(env, msg) - .ThrowAsJavaScriptException(); - } - - Promise::Deferred deferred = Promise::Deferred::New(env); - UpdateStateWorker *wk = new UpdateStateWorker(env, deferred, win_id, action_number, p1, p2); - wk->Queue(); - free(action); - free(p1); - free(p2); - return deferred.Promise(); -} - -Boolean windowStateSync(const CallbackInfo &info) { - Napi::Env env = info.Env(); - int win_id; - char *action; - char *p1; - char *p2; - char msg[128]; - unsigned long action_number = 0; - enum STATES st; - - win_id = info[0].As<Number>(); - action = strdup(info[1].As<String>().Utf8Value().c_str()); - p1 = strdup(info[2].As<String>().Utf8Value().c_str()); - p2 = strdup(info[3].As<String>().Utf8Value().c_str()); - - if (strcmp(action, "REMOVE") == 0) - action_number = _NET_WM_STATE_REMOVE; - else if (strcmp(action, "ADD") == 0) - action_number = _NET_WM_STATE_ADD; - else if (strcmp(action, "TOGGLE") == 0) - action_number = _NET_WM_STATE_TOGGLE; - else { - sprintf(msg, "[windowStateSync] bad action provided (%s)", action); - Napi::Error::New(env, msg) - .ThrowAsJavaScriptException(); - } - - st = window_state(NULL, win_id, action_number, p1, p2); - - free(action); - free(p1); - free(p2); - if (st != WINDOW_STATE_SET) { - handling_libwmctrl_error(env, "windowStateSync", st); - return Boolean::New(env, false); - } - - return Boolean::New(env, true); -} \ No newline at end of file diff --git a/src/napi/window-move-resize-transition.cpp b/src/napi/window-move-resize-transition.cpp deleted file mode 100644 index b5cb673..0000000 --- a/src/napi/window-move-resize-transition.cpp +++ /dev/null @@ -1,64 +0,0 @@ -#include "wmctrl-napi.hpp" - -class MoveResizeTransitionWorker: public AsyncWorker { - public: - MoveResizeTransitionWorker(Napi::Env &env, Promise::Deferred deferred, Window id, int g, int x, int y, int w, int h, float await_time, int pad) - : AsyncWorker(env), deferred(deferred), id(id), g(g), x(x), y(y), w(w), h(h), await_time(await_time), pad(pad), err(NULL) {} - ~MoveResizeTransitionWorker() { - if (this->err) - free(this->err); - } - - void Execute() override { - this->st = window_move_resize_transition(NULL, id, g, x, y, w, h, await_time, pad); - } - - void OnOK() override { - Napi::Env env = Env(); - String err_js; - - if (this->st != WINDOW_MOVED_RESIZED) { - this->err = get_libwmctrl_error("MoveResizeWorker", this->st); - err_js = String::New(env, this->err); - this->deferred.Reject(err_js); - } - else { - this->deferred.Resolve(Boolean::New(env, true)); - } - } - - private: - Promise::Deferred deferred; - Window id; - int g,x,y,w,h; - float await_time; - int pad; - char *err; - enum STATES st; -}; - -Promise windowMoveResizeTransitionAsync(const CallbackInfo &info) { - checkNumber(info, "windowMoveResizeTransition", "id", 0); - checkNumber(info, "windowMoveResizeTransition", "gravity", 1); - checkNumber(info, "windowMoveResizeTransition", "x", 2); - checkNumber(info, "windowMoveResizeTransition", "y", 3); - checkNumber(info, "windowMoveResizeTransition", "width", 4); - checkNumber(info, "windowMoveResizeTransition", "height", 5); - checkNumber(info, "windowMoveResizeTransition", "await_time", 6); - checkNumber(info, "windowMoveResizeTransition", "pad", 7); - - Napi::Env env = info.Env(); - int id = info[0].As<Number>(); - int g = info[1].As<Number>(); - int x = info[2].As<Number>(); - int y = info[3].As<Number>(); - int w = info[4].As<Number>(); - int h = info[5].As<Number>(); - float await_time = info[6].As<Number>(); - int pad = info[7].As<Number>(); - - Promise::Deferred deferred = Promise::Deferred::New(env); - MoveResizeTransitionWorker *wk = new MoveResizeTransitionWorker(env, deferred, id, g, x, y, w, h, await_time, pad); - wk->Queue(); - return deferred.Promise(); -} \ No newline at end of file diff --git a/src/napi/wmctrl-napi.hpp b/src/napi/wmctrl-napi.hpp deleted file mode 100644 index 7549164..0000000 --- a/src/napi/wmctrl-napi.hpp +++ /dev/null @@ -1,77 +0,0 @@ -#include <napi.h> -extern "C" { - #include "../../libwmctrl/src/wmctrl.h" -} - -using namespace Napi; - -char *get_libwmctrl_error(const char *fnName, enum STATES st); -void handling_libwmctrl_error(Env env, const char *fnName, enum STATES st); - -//Utils -void checkId(const CallbackInfo &info, const char * fnName); -void checkClassName(const CallbackInfo &info, const char *fnName); -void checkPid(const CallbackInfo &info, const char *fnName); -void checkNumber(const CallbackInfo &info, const char *fnName, const char*field, unsigned i); - -//Active -Boolean activeWindowByIdSync(const CallbackInfo &info); -Promise activeWindowByIdAsync(const CallbackInfo &info); - -Boolean activeWindowsByPidSync(const CallbackInfo &info); -Promise activeWindowsByPidAsync(const CallbackInfo &info); - -Boolean activeWindowsByClassNameSync(const CallbackInfo &info); -Promise activeWindowsByClassNameAsync(const CallbackInfo &info); - -//Close -Boolean closeWindowByIdSync(const CallbackInfo &info); -Promise closeWindowByIdAsync(const CallbackInfo &info); - -Boolean closeWindowsByPidSync(const CallbackInfo &info); -Promise closeWindowsByPidAsync(const CallbackInfo &info); - -Boolean closeWindowsByClassNameSync(const CallbackInfo &info); -Promise closeWindowsByClassNameAsync(const CallbackInfo &info); - -//Get Windows -Object create_window_js(Env env, struct window_info *wi); -Promise getWindowByIdAsync(const CallbackInfo &info); -Value getWindowByIdSync(const CallbackInfo &info); - -Value getActiveWindowSync(const CallbackInfo &info); -Promise getActiveWindowAsync(const CallbackInfo &info); - -Value getWindowListSync(const CallbackInfo &info); -Promise getWindowListAsync(const CallbackInfo &info); - -Value getWindowsByClassNameSync(const CallbackInfo &info); -Promise getWindowsByClassNameAsync(const CallbackInfo &info); - -Value getWindowsByPidSync(const CallbackInfo &info); -Promise getWindowsByPidAsync(const CallbackInfo &info); - -//Screen -Value getScreenSync(const CallbackInfo &info); -Promise getScreenAsync(const CallbackInfo &info); - -//Move-Resize -Boolean windowMoveResizeSync(const CallbackInfo &info); -Promise windowMoveResizeAsync(const CallbackInfo &info); - -Promise windowMoveResizeTransitionAsync(const CallbackInfo &info); - -Promise windowStateAsync(const CallbackInfo &info); -Boolean windowStateSync(const CallbackInfo &info); - -//Minimize -Boolean windowMinimizeSync(const CallbackInfo &info); -Promise windowMinimizeAsync(const CallbackInfo &info); - -//Allow-All-Sizes -Boolean windowAllowAllSizesSync(const CallbackInfo &info); -Promise windowAllowAllSizesAsync(const CallbackInfo &info); - -//Raise -Boolean windowRaiseSync(const CallbackInfo &info); -Promise windowRaiseAsync(const CallbackInfo &info); \ No newline at end of file diff --git a/src/napi/wmctrl-utils.cpp b/src/napi/wmctrl-utils.cpp deleted file mode 100644 index 6224041..0000000 --- a/src/napi/wmctrl-utils.cpp +++ /dev/null @@ -1,95 +0,0 @@ -#include "wmctrl-napi.hpp" - -using namespace Napi; - -char *get_libwmctrl_error(const char *fnName, enum STATES st) { - char *error = get_error_message(st); - char *msg = (char*)calloc(sizeof(char), 512); - if (error) { - sprintf(msg, "[%s] %s", fnName, error); - free(error); - } - else - sprintf(msg, "[%s] %s", fnName, "Not enough memory error"); - return msg; -} - -void handling_libwmctrl_error(Env env, const char *fnName, enum STATES st) { - char buffer[512]; - char *msg = get_libwmctrl_error(fnName, st); - strcpy(buffer, msg); - free(msg); - Error::New(env, buffer).ThrowAsJavaScriptException(); -} - -void checkNumber(const CallbackInfo &info, const char *fnName, const char*field, unsigned i) { - Env env = info.Env(); - char buffer[512]; - - if (info.Length() < i + 1) { - sprintf(buffer, "Must have arg [%s] [%s]", field, fnName); - Error::New(env, buffer) - .ThrowAsJavaScriptException(); - return; - } - - if (!info[i].IsNumber()) { - sprintf(buffer, "%s must be a number [%s]", field, fnName); - TypeError::New(env, buffer) - .ThrowAsJavaScriptException(); - } -} - -void checkId(const CallbackInfo &info, const char * fnName) { - Env env = info.Env(); - char buffer[512]; - - if (info.Length() < 1) { - sprintf(buffer, "Must have arg wid_js [%s]", fnName); - Error::New(env, buffer) - .ThrowAsJavaScriptException(); - return; - } - - if (!info[0].IsNumber()) { - sprintf(buffer, "win_js must be a number [%s]", fnName); - TypeError::New(env, buffer) - .ThrowAsJavaScriptException(); - } -} - -void checkClassName(const CallbackInfo &info, const char *fnName) { - Env env = info.Env(); - char buffer[512]; - if (info.Length() < 1) { - sprintf(buffer, "Must have arg win_class_name_js [%s]", fnName); - Error::New(env, buffer) - .ThrowAsJavaScriptException(); - return; - } - - if (!info[0].IsString()) { - sprintf(buffer, "win_class_name_js must be a string [%s]", fnName); - TypeError::New(env, buffer) - .ThrowAsJavaScriptException(); - return; - } -} - -void checkPid(const CallbackInfo &info, const char *fnName) { - Env env = info.Env(); - char buffer[512]; - if (info.Length() < 1) { - sprintf(buffer, "Must have arg wid_js [%s]", fnName); - Error::New(env, buffer) - .ThrowAsJavaScriptException(); - return; - } - - if (!info[0].IsNumber()) { - sprintf(buffer, "win_js must be a number [%s]", fnName); - TypeError::New(env, buffer) - .ThrowAsJavaScriptException(); - return; - } -} \ No newline at end of file diff --git a/src/napi/wmctrl.cpp b/src/napi/wmctrl.cpp deleted file mode 100644 index 51da9e9..0000000 --- a/src/napi/wmctrl.cpp +++ /dev/null @@ -1,60 +0,0 @@ -#include "wmctrl-napi.hpp" -#include <stdio.h> - -using namespace Napi; - -Object Init(Env env, Object exports) { - init_wmctrl_lib(); - - exports.Set("getScreenSync", Function::New(env, getScreenSync)); - exports.Set("getScreenAsync", Function::New(env, getScreenAsync)); - - exports.Set("getWindowByIdAsync", Function::New(env, getWindowByIdAsync)); - exports.Set("getWindowByIdSync", Function::New(env, getWindowByIdSync)); - - exports.Set("getActiveWindowSync", Function::New(env, getActiveWindowSync)); - exports.Set("getActiveWindowAsync", Function::New(env, getActiveWindowAsync)); - - exports.Set("getWindowListSync", Function::New(env, getWindowListSync)); - exports.Set("getWindowListAsync", Function::New(env, getWindowListAsync)); - - exports.Set("getWindowsByClassNameSync", Function::New(env, getWindowsByClassNameSync)); - exports.Set("getWindowsByClassNameAsync", Function::New(env, getWindowsByClassNameAsync)); - - exports.Set("getWindowsByPidSync", Function::New(env, getWindowsByPidSync)); - exports.Set("getWindowsByPidAsync", Function::New(env, getWindowsByPidAsync)); - - exports.Set("activeWindowByIdSync", Function::New(env, activeWindowByIdSync)); - exports.Set("activeWindowByIdAsync", Function::New(env, activeWindowByIdAsync)); - exports.Set("activeWindowsByPidSync", Function::New(env, activeWindowsByPidSync)); - exports.Set("activeWindowsByPidAsync", Function::New(env, activeWindowsByPidAsync)); - exports.Set("activeWindowsByClassNameSync", Function::New(env, activeWindowsByClassNameSync)); - exports.Set("activeWindowsByClassNameAsync", Function::New(env, activeWindowsByClassNameAsync)); - - exports.Set("closeWindowByIdSync", Function::New(env, closeWindowByIdSync)); - exports.Set("closeWindowByIdAsync", Function::New(env, closeWindowByIdAsync)); - exports.Set("closeWindowsByPidSync", Function::New(env, closeWindowsByPidSync)); - exports.Set("closeWindowsByPidAsync", Function::New(env, closeWindowsByPidAsync)); - exports.Set("closeWindowsByClassNameSync", Function::New(env, closeWindowsByClassNameSync)); - exports.Set("closeWindowsByClassNameAsync", Function::New(env, closeWindowsByClassNameAsync)); - - exports.Set("windowMoveResizeSync", Function::New(env, windowMoveResizeSync)); - exports.Set("windowMoveResizeAsync", Function::New(env, windowMoveResizeAsync)); - - exports.Set("windowMoveResizeTransitionAsync", Function::New(env, windowMoveResizeTransitionAsync)); - - exports.Set("windowStateSync", Function::New(env, windowStateSync)); - exports.Set("windowStateAsync", Function::New(env, windowStateAsync)); - - exports.Set("windowMinimizeSync", Function::New(env, windowMinimizeSync)); - exports.Set("windowMinimizeAsync", Function::New(env, windowMinimizeAsync)); - - exports.Set("windowAllowAllSizesSync", Function::New(env, windowAllowAllSizesSync)); - exports.Set("windowAllowAllSizesAsync", Function::New(env, windowAllowAllSizesAsync)); - - exports.Set("windowRaiseSync", Function::New(env, windowRaiseSync)); - exports.Set("windowRaiseAsync", Function::New(env, windowRaiseAsync)); - return exports; -} - -NODE_API_MODULE(wmctrl, Init) \ No newline at end of file diff --git a/src/test.ts b/src/test.ts deleted file mode 100644 index 434b27f..0000000 --- a/src/test.ts +++ /dev/null @@ -1,258 +0,0 @@ -import { - getScreenSync, - getWindowListSync, - getActiveWindowSync, - getWindowsByPidSync, - getWindowsByClassNameSync, - activeWindowByIdSync, - activeWindowsByPidSync, - activeWindowsByClassNameSync, - closeWindowByIdSync, - closeWindowsByPidSync, - closeWindowsByClassNameSync, - windowMoveResizeSync, - windowStateSync, - windowMinimize, - Window, - getWindowsByClassName, - getWindowList, - windowAllowAllSizesSync, - windowRaiseSync, - windowMinimizeSync -} from "./index"; - -import { promisify } from "util"; -import * as cp from "child_process"; -import { wait } from "./unit-test/utils"; - -const winProcess = "xclock"; -const class_name = "xclock.XClock"; - -const exec = promisify(cp.exec); - -(async () => { - for(let i = 0; i < 100; i++) { - console.time("closeWindowById"); - closeWindowByIdSync(4); - console.timeEnd("closeWindowById"); - } - - for(let i = 0; i < 100; i++) { - console.time("getScreenSync"); - const screen = getScreenSync(); - console.timeEnd("getScreenSync"); - console.log(screen); - } - - let windows = [] as Window[]; - for (let i = 0; i < 100; i++) { - console.time("getWindowListSync"); - windows = await getWindowList(); - console.timeEnd("getWindowListSync"); - } - - for(let i = 0; i < 100; i++) { - console.time("getWindowListSync"); - windows = getWindowListSync(); - console.timeEnd("getWindowListSync"); - } - - const frames = windows.filter(win => win.frame_extents) - .map(({frame_extents}) => { - if (frame_extents) - return `left:${frame_extents.left},right:${frame_extents.right},top:${frame_extents.top},bottom:${frame_extents.bottom},`; - }) - .join('\n'); - console.log(frames); - - for(let i = 0; i < 100; i++) { - try { - closeWindowsByClassNameSync(class_name); - }catch(e) { - //Voluntary error [Must failed] - console.error("Voluntary error [Must failed]", e.message); - } - } - - for (let i = 0; i < 50; i++) { - exec(winProcess); - await wait(0.1); - } - await wait(5); - - console.time("getWindowsByClassName"); - const xclockWindows = getWindowsByClassNameSync(class_name); - console.timeEnd("getWindowsByClassName"); - if (!xclockWindows) - throw("Unexpected error xclockWinsows"); - - console.log(`${xclockWindows.length} windows are open with the class_name ${class_name}`); - - try { - console.time("activeWindowsByClassName"); - activeWindowsByClassNameSync(class_name); - console.timeEnd("activeWindowsByClassName"); - } catch (e) { - console.log(`Voluntary error [Must failed][activeWindowsByClassName] ${e.message}`); - getWindowsByClassNameSync(class_name) - .forEach(win => activeWindowByIdSync(win.win_id)); - } - await wait(1); - - for (const winXclock of xclockWindows) { - console.time("closeWindowsByPid"); - closeWindowsByPidSync(winXclock.win_pid); - console.timeEnd("closeWindowsByPid"); - await wait(0.1); - } - await wait(1); - - try { - closeWindowsByClassNameSync(class_name); - } - catch(e) { - //Voluntary error [Must failed] - console.error("Voluntary error [Must failed]", e.message); - } - await wait(1); - - for (let i = 0; i < 100; i++) { - try { - console.time("getActiveWindow"); - getActiveWindowSync(); - console.timeEnd("getActiveWindow"); - } catch (e) { - //Voluntary error [Must failed] - console.error("Voluntary error [Must failed]", e.message); - console.timeEnd("getActiveWindow"); - } - } - - exec("xeyes"); - await wait(2); - - for (let i = 0; i < 100; i++) { - console.time("activeWindowsByClassName"); - activeWindowsByClassNameSync("xeyes.XEyes"); - console.timeEnd("activeWindowsByClassName"); - } - await wait(1); - - for (let i = 0; i < 100; i++) { - try { - getActiveWindowSync(); - } catch(e) { - //Voluntary error [Must failed] - console.error("Voluntary error [Must failed]", e.message); - } - } - const winsXeyes = getWindowsByClassNameSync("xeyes.XEyes"); - console.timeEnd('getWindowsByClassName'); - if (!winsXeyes || !winsXeyes.length) - throw new Error("Unexpected empty array"); - await wait(1); - - console.time("windowMoveResize"); - windowMoveResizeSync(winsXeyes[0].win_id, 0, 0, 0, 500, 500); - console.timeEnd("windowMoveResize"); - await wait(1); - - console.time("windowMoveResize"); - windowMoveResizeSync(winsXeyes[0].win_id, 0, 0, 0, 1000, 1000); - console.timeEnd("windowMoveResize"); - await wait(1); - - console.time("windowState"); - windowStateSync(winsXeyes[0].win_id, "add", "maximized_vert", "maximized_horz"); - console.timeEnd("windowState"); - await wait(1); - - console.time("windowState"); - windowStateSync(winsXeyes[0].win_id, "remove", "maximized_vert", "maximized_horz"); - console.timeEnd("windowState"); - await wait(1); - - console.time("windowState"); - windowStateSync(winsXeyes[0].win_id, "add", "fullscreen"); - console.timeEnd("windowState"); - await wait(1); - - console.time("windowState"); - windowStateSync(winsXeyes[0].win_id, "remove", "fullscreen"); - console.timeEnd("windowState"); - await wait(1); - - console.time("windowMinimize"); - windowMinimize(winsXeyes[0].win_id); - console.timeEnd("windowMinimize"); - await wait(1); - - console.time("activeWindowById"); - activeWindowByIdSync(winsXeyes[0].win_id); - console.timeEnd("activeWindowById"); - - console.time("windowState"); - windowStateSync(winsXeyes[0].win_id, "add", "fullscreen"); - console.timeEnd("windowState"); - await wait(1); - - console.time("closeWindowsByClassName"); - closeWindowsByClassNameSync("xeyes.XEyes"); - console.timeEnd("closeWindowsByClassName"); - exec("firefox"); - await wait(5); - - console.time("getWindowsByClassName"); - let firefoxWindows = getWindowsByClassNameSync("Navigator.Firefox"); - console.timeEnd("getWindowsByClassName"); - let lastWindow = firefoxWindows[firefoxWindows.length - 1]; - - console.time("windowAllowAllSizes"); - windowAllowAllSizesSync(lastWindow.win_id); - console.timeEnd("windowAllowAllSizes"); - - console.time("getWindowsByClassName"); - firefoxWindows = getWindowsByClassNameSync("Navigator.Firefox"); - console.timeEnd("getWindowsByClassName"); - lastWindow = firefoxWindows[firefoxWindows.length - 1]; - - if (lastWindow.WM_NORMAL_HINTS) { - const { - max_width, - max_height, - min_width, - min_height - } = lastWindow.WM_NORMAL_HINTS; - if (!(max_width !== 0 || - max_height !== 0 || - min_width !== 0 || - min_height !== 0)) - throw new Error("window_allow_all_sizes failed"); - } else { - throw new Error("WM_NORMAL_HINTS not provided"); - } - - console.time("windowMinimizeSync"); - windowMinimizeSync(lastWindow.win_id); - console.timeEnd("windowMinimizeSync"); - await wait(3); - - console.time("windowRaiseSync"); - windowRaiseSync(lastWindow.win_id); - console.timeEnd("windowRaiseSync"); - await wait(5); - - console.time("closeWindowByIdSync"); - closeWindowByIdSync(lastWindow.win_id); - console.timeEnd("closeWindowByIdSync"); - -})() -.then(() => { - console.log("ALL TEST ENDED WITH SUCESS"); -}) -.catch(e => { - console.error("Unexpected error during tests", e); -}) -.finally(() => { - console.log("DONE!"); -}); \ No newline at end of file diff --git a/src/test/api.test.ts b/src/test/api.test.ts new file mode 100644 index 0000000..09117a1 --- /dev/null +++ b/src/test/api.test.ts @@ -0,0 +1,161 @@ +// API surface tests: run anywhere, no X server needed. +import { test, describe } from "node:test"; +import * as assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import * as path from "node:path"; +import * as wm from "../index"; + +// Every call must fail to connect: this file runs in its own process. +process.env.DISPLAY = ":4242"; + +const api = wm as unknown as Record<string, (...args:unknown[]) => unknown>; +const INDEX = path.join(__dirname, "../index.js"); + +const NATIVE_NAMES = [ + "activeWindowByIdAsync", "activeWindowByIdSync", "activeWindowsByClassNameAsync", "activeWindowsByClassNameSync", + "activeWindowsByPidAsync", "activeWindowsByPidSync", "closeWindowByIdAsync", "closeWindowByIdSync", + "closeWindowsByClassNameAsync", "closeWindowsByClassNameSync", "closeWindowsByPidAsync", "closeWindowsByPidSync", + "getActiveWindowAsync", "getActiveWindowSync", "getScreenAsync", "getScreenSync", "getWindowByIdAsync", + "getWindowByIdSync", "getWindowListAsync", "getWindowListSync", "getWindowsByClassNameAsync", + "getWindowsByClassNameSync", "getWindowsByPidAsync", "getWindowsByPidSync", "windowAllowAllSizesAsync", + "windowAllowAllSizesSync", "windowMinimizeAsync", "windowMinimizeSync", "windowMoveResizeAsync", + "windowMoveResizeSync", "windowMoveResizeTransitionAsync", "windowRaiseAsync", "windowRaiseSync", + "windowStateAsync", "windowStateSync" +]; + +type Param = [name:string, type:"number"|"string", valid:unknown]; +const id:Param = ["win_id", "number", 1]; +const pid:Param = ["win_pid", "number", 1]; +const cls:Param = ["win_class_name", "string", "a.A"]; + +// [public name, params, has a Sync variant] +const FUNCTIONS:[string, Param[], boolean][] = [ + ["getScreen", [], true], + ["getWindowList", [], true], + ["getActiveWindow", [], true], + ["getWindowById", [id], true], + ["getWindowsByPid", [pid], true], + ["getWindowsByClassName", [cls], true], + ["activeWindowById", [id], true], + ["activeWindowsByPid", [pid], true], + ["activeWindowsByClassName", [cls], true], + ["closeWindowById", [id], true], + ["closeWindowsByPid", [pid], true], + ["closeWindowsByClassName", [cls], true], + ["windowMoveResize", [id, ["win_gravity", "number", 0], ["win_x", "number", 0], ["win_y", "number", 0], + ["win_width", "number", 10], ["win_height", "number", 10]], true], + ["windowMoveResizeTransition", [id, ["win_gravity", "number", 0], ["win_x", "number", 0], ["win_y", "number", 0], + ["win_width", "number", 10], ["win_height", "number", 10], ["await_time", "number", 0], ["pad", "number", 1]], false], + ["windowState", [id, ["action", "string", "add"], ["prop1", "string", "above"], ["prop2", "string", "below"]], true], + ["windowMinimize", [id], true], + ["windowAllowAllSizes", [id], true], + ["windowRaise", [id], true], +]; + +const valid = (params:Param[]) => params.map(p => p[2]); +const noDisplay = (name:string) => ({ name: "Error", message: `[${name}] CAN_NOT_OPEN_DISPLAY (3)` }); + +test("the module exports exactly the documented functions", () => { + const names = FUNCTIONS.flatMap(([n, , sync]) => sync ? [n, `${n}Sync`] : [n]).sort(); + assert.deepEqual(Object.keys(wm).filter(k => typeof api[k] === "function").sort(), names); +}); + +test("the native binary exports exactly the expected functions", () => { + const musl = process.platform === "linux" && !(process.report.getReport() as any).header?.glibcVersionRuntime; + const native = require(`../../prebuilds/${process.platform}-${process.arch}${musl ? "-musl" : ""}/wmctrljs.node`); + assert.deepEqual(Object.keys(native).sort(), NATIVE_NAMES); +}); + +for (const [name, params, hasSync] of FUNCTIONS) { + describe(name, () => { + test("async variant rejects with an Error when no display can be opened", async () => { + const p = api[name](...valid(params)); + assert.ok(p instanceof Promise); + await assert.rejects(p as Promise<unknown>, noDisplay(name)); + }); + + if (hasSync) + test("sync variant throws an Error when no display can be opened", () => { + assert.throws(() => api[`${name}Sync`](...valid(params)), noDisplay(`${name}Sync`)); + }); + + params.forEach(([param, type], i) => { + const wrong = type === "number" ? "1" : 1; + const args = (bad:unknown) => valid(params).map((v, j) => j === i ? bad : v); + const message = `[${name}] expect a type [${type}] for param [${param}]`; + + test(`rejects a ${typeof wrong} ${param}`, async () => { + await assert.rejects(async () => api[name](...args(wrong)), { message }); + if (hasSync) + assert.throws(() => api[`${name}Sync`](...args(wrong)), { message }); + }); + + if (type === "number") + test(`rejects a NaN ${param}`, async () => { + const nan = { message: `${message} received NaN value` }; + await assert.rejects(async () => api[name](...args(NaN)), nan); + if (hasSync) + assert.throws(() => api[`${name}Sync`](...args(NaN)), nan); + }); + }); + }); +} + +describe("windowState validation", () => { + for (const action of ["bogus", "", "added"]) + test(`refuses action "${action}"`, async () => { + const message = `[windowState] only actions [REMOVE,ADD,TOGGLE] are enabled note (${action.toUpperCase()})`; + assert.throws(() => wm.windowStateSync(1, action, "above"), { message }); + await assert.rejects(wm.windowState(1, action, "above"), { message }); + }); + + const props = "modal,sticky,maximized_vert,maximized_horz,shaded,skip_taskbar,skip_pager,hidden,fullscreen,above,below"; + for (const prop of ["bogus", "demands_attention", "maximized"]) + test(`refuses property "${prop}"`, async () => { + assert.throws(() => wm.windowStateSync(1, "add", prop), { message: `[windowState] property prop1 (${prop}) is not an enabled property ${props}` }); + assert.throws(() => wm.windowStateSync(1, "add", "above", prop), { message: `[windowState] property prop2 (${prop}) is not an enabled property ${props}` }); + await assert.rejects(wm.windowState(1, "add", prop), /is not an enabled property/); + }); + + for (const prop of props.split(",")) + test(`accepts property "${prop}" in any case`, () => { + // Validation passes, then the native call fails to reach the display. + assert.throws(() => wm.windowStateSync(1, "Toggle", prop.toUpperCase()), noDisplay("windowStateSync")); + assert.throws(() => wm.windowStateSync(1, "remove", "above", prop), noDisplay("windowStateSync")); + }); + + test("prop2 is optional and may be empty", () => { + assert.throws(() => wm.windowStateSync(1, "add", "above"), noDisplay("windowStateSync")); + assert.throws(() => wm.windowStateSync(1, "add", "above", ""), noDisplay("windowStateSync")); + }); +}); + +describe("binary loader", () => { + // Runs index.js in a child process after `setup`, printing the native path it requires. + const load = (setup:string) => execFileSync(process.execPath, ["-e", ` + const Module = require("module"); + const req = Module.prototype.require; + Module.prototype.require = function (id) { + if (id.endsWith(".node")) { console.log(id); process.exit(0); } + return req.apply(this, arguments); + }; + ${setup} + require(${JSON.stringify(INDEX)});`]).toString().trim(); + + test("loads prebuilds/<platform>-<arch>", () => { + assert.match(load(""), new RegExp(`^\\.\\./prebuilds/${process.platform}-${process.arch}(-musl)?/wmctrljs\\.node$`)); + }); + + test("picks the musl build when the runtime has no glibc", { skip: process.platform !== "linux" }, () => { + assert.equal(load(`process.report.getReport = () => ({ header: {} });`), `../prebuilds/linux-${process.arch}-musl/wmctrljs.node`); + assert.equal(load(`process.report.getReport = () => ({ header: { glibcVersionRuntime: "2.17" } });`), `../prebuilds/linux-${process.arch}/wmctrljs.node`); + }); + + test("explains which binary is missing", () => { + const out = execFileSync(process.execPath, ["-e", ` + Object.defineProperty(process, "arch", { value: "mips" }); + try { require(${JSON.stringify(INDEX)}); } catch (e) { console.log(e.message); console.log(e.cause instanceof Error); }`]).toString(); + assert.match(out, /^wmctrljs: cannot load the binary for \w+-mips(-musl)?: Cannot find module/); + assert.match(out, /\ntrue\n$/); + }); +}); diff --git a/src/test/x11.test.ts b/src/test/x11.test.ts new file mode 100644 index 0000000..dd6db65 --- /dev/null +++ b/src/test/x11.test.ts @@ -0,0 +1,459 @@ +// Behaviour tests against a real X server with an EWMH window manager (CI: Xvfb + openbox). +// Skipped when DISPLAY is unset. Only ever acts on the fixture windows it spawns. +import { test, describe, before, after } from "node:test"; +import * as assert from "node:assert/strict"; +import { spawn, ChildProcess } from "node:child_process"; +import { once } from "node:events"; +import { createInterface } from "node:readline"; +import * as path from "node:path"; +import { setTimeout as sleep } from "node:timers/promises"; +import * as wm from "../index"; + +const FIXTURE = process.env.WMCTRLJS_FIXTURE ?? path.join(__dirname, "../../native/target/release/examples/fixture"); +const skip = !process.env.DISPLAY && "DISPLAY is not set"; +const spawned:ChildProcess[] = []; + +interface Fixture { + ids:number[] + id:number + pid:number + cls:string + exited:Promise<unknown> +} + +let serial = 0; +async function fixture(opts:{ count?:number, legacy?:boolean, instance?:string } = {}):Promise<Fixture> { + const instance = opts.instance ?? `wmctrljs-${process.pid}-${serial++}`; + const args = [instance, `title ${instance}`, String(opts.count ?? 1), opts.legacy ? "legacy" : ""]; + const proc = spawn(FIXTURE, args, { stdio: ["ignore", "pipe", "inherit"] }); + spawned.push(proc); + const exited = once(proc, "exit"); + const ids:number[] = []; + for await (const line of createInterface({ input: proc.stdout! })) { + ids.push(Number(line)); + if (ids.length === (opts.count ?? 1)) + break; + } + await waitFor(() => ids.every(id => wm.getWindowListSync().some(w => w.win_id === id))); + return { ids, id: ids[0], pid: proc.pid!, cls: `${instance}.Fixture`, exited }; +} + +async function waitFor<T>(fn:() => T, ms = 20000):Promise<T> { + const end = Date.now() + ms; + for (;;) { + const v = fn(); + if (v) + return v; + if (Date.now() > end) + throw new Error(`timed out waiting for ${fn}`); + await sleep(20); + } +} + +const states = (id:number) => wm.getWindowByIdSync(id).win_states.map(s => s.flag); +const geometry = (id:number) => wm.getWindowByIdSync(id).win_geometry!; +// _NET_ACTIVE_WINDOW is briefly 0 while the WM hands focus over. +const active = () => { try { return wm.getActiveWindowSync().win_id; } catch { return 0; } }; +const MISSING = 1; // never a client window id: X servers hand out ids from 0x200000 + +// The WM publishes _NET_CLIENT_LIST once it manages the screen; it starts slowly under emulation. +before(() => skip || waitFor(() => { try { return wm.getWindowListSync(); } catch { return false; } }, 60000)); +after(() => spawned.forEach(p => p.kill())); + +describe("X11", { skip }, () => { + describe("screen", () => { + test("sync and async agree on the screen", async () => { + const screen = wm.getScreenSync(); + assert.deepEqual(Object.keys(screen), [ + "backing_store", "black_pixel", "cmap", "height", "max_maps", "mheight", "min_maps", + "mwidth", "ndepths", "root_depth", "root_input_mask", "save_unders", "white_pixel", "width" + ]); + assert.ok(Object.values(screen).every(v => Number.isInteger(v) && v >= 0)); + assert.ok(screen.width > 0 && screen.height > 0 && screen.root_depth > 0 && screen.ndepths > 0); + assert.notEqual(screen.white_pixel, screen.black_pixel); + assert.deepEqual(await wm.getScreen(), screen); + }); + }); + + describe("reading windows", () => { + test("getWindowById reports every fixture property", async () => { + const f = await fixture(); + const win = wm.getWindowByIdSync(f.id); + assert.deepEqual(Object.keys(win), [ + "win_id", "win_pid", "desktop_number", "showing_desktop", "win_client_machine", "win_class", + "win_types", "win_actions", "win_states", "win_name", "win_visible_name", "win_icon_name", + "win_visible_icon_name", "wm_normal_hints_supplied", "wm_hints_supplied", "win_geometry", + "WM_NORMAL_HINTS", "WM_HINTS", "frame_extents" + ]); + assert.equal(win.win_id, f.id); + assert.equal(win.win_pid, f.pid); + assert.equal(win.win_class, f.cls); + assert.equal(win.win_name, `title ${f.cls.replace(".Fixture", "")} ✓`); + assert.ok(win.win_visible_name.startsWith(win.win_name)); + assert.equal(win.win_icon_name, "fixture-icon"); + assert.ok(win.win_visible_icon_name.startsWith("fixture-icon")); + assert.equal(win.win_client_machine, "fixture-host"); + assert.equal(win.desktop_number, 0); + assert.equal(win.showing_desktop, 0); + assert.deepEqual(win.win_types.map(t => t.flag), ["_NET_WM_WINDOW_TYPE_NORMAL"]); + assert.ok(win.win_types[0].number > 0); + assert.ok(win.win_actions.some(a => a.flag === "_NET_WM_ACTION_CLOSE")); + assert.ok(win.win_actions.every(a => a.flag.startsWith("_NET_WM_ACTION_") && a.number > 0)); + assert.deepEqual(win.win_states, []); + assert.equal(win.wm_normal_hints_supplied, 1023); + assert.deepEqual(win.WM_NORMAL_HINTS, { + flags: 816, x: 0, y: 0, width: 0, height: 0, + min_width: 100, min_height: 80, max_width: 1000, max_height: 800, + width_inc: 0, height_inc: 0, + min_aspect: { numerator: 0, denominator: 0 }, + max_aspect: { numerator: 0, denominator: 0 }, + base_width: 10, base_height: 20, win_gravity: 1 + }); + assert.equal(win.wm_hints_supplied, 0); + assert.ok(Object.values(win.WM_HINTS!).every(v => typeof v === "object" || v === 0)); + assert.equal(win.win_geometry!.width, 300); + assert.equal(win.win_geometry!.height, 200); + const fe = win.frame_extents!; + assert.ok([fe.left, fe.right, fe.top, fe.bottom].every(v => Number.isInteger(v) && v >= 0)); + // Client area sits inside the frame. + assert.equal(win.win_geometry!.x, fe.left); + assert.equal(win.win_geometry!.y, fe.top); + assert.deepEqual(await wm.getWindowById(f.id), win); + }); + + test("legacy ICCCM-only clients", async () => { + const f = await fixture({ legacy: true }); + const win = wm.getWindowByIdSync(f.id); + assert.equal(win.win_name, `title ${f.cls.replace(".Fixture", "")}`); // from WM_NAME + assert.equal(win.win_pid, 0); + assert.equal(win.win_client_machine, ""); + assert.equal(win.win_icon_name, ""); + assert.deepEqual(win.win_types, []); + assert.equal(win.wm_normal_hints_supplied, 255); // 15-long hints: no base size, no gravity + assert.equal(win.WM_NORMAL_HINTS!.flags, 16); + assert.equal(win.WM_NORMAL_HINTS!.min_width, 120); + assert.equal(win.WM_NORMAL_HINTS!.min_height, 90); + assert.equal(win.WM_NORMAL_HINTS!.base_width, 0); + // Windows without _NET_WM_PID never match a pid lookup. + assert.ok(!wm.getWindowsByPidSync(0).some(w => w.win_id === f.id)); + assert.deepEqual(wm.getWindowsByClassNameSync(f.cls).map(w => w.win_id), [f.id]); + }); + + test("a window that does not exist reads as empty", async () => { + const win = wm.getWindowByIdSync(MISSING); + assert.equal(win.win_id, MISSING); + assert.equal(win.win_pid, 0); + assert.equal(win.win_class, ""); + assert.equal(win.win_name, ""); + assert.deepEqual([win.win_types, win.win_actions, win.win_states], [[], [], []]); + assert.equal(win.wm_normal_hints_supplied, 0); + assert.equal(win.win_geometry, undefined); + assert.equal(win.frame_extents, undefined); + assert.deepEqual(await wm.getWindowById(MISSING), win); + }); + + test("getWindowList lists clients in mapping order", async () => { + const a = await fixture(); + const b = await fixture(); + const list = wm.getWindowListSync(); + assert.deepEqual(await wm.getWindowList(), list); + const ids = list.map(w => w.win_id); + assert.ok(ids.indexOf(a.id) >= 0 && ids.indexOf(a.id) < ids.indexOf(b.id)); + assert.equal(new Set(ids).size, ids.length); + }); + + test("getWindowsByPid / getWindowsByClassName", async () => { + const a = await fixture(); + const b = await fixture({ count: 3 }); + assert.deepEqual(wm.getWindowsByPidSync(a.pid).map(w => w.win_id), [a.id]); + assert.deepEqual((await wm.getWindowsByPid(b.pid)).map(w => w.win_id), b.ids); + assert.deepEqual(wm.getWindowsByClassNameSync(b.cls).map(w => w.win_id), b.ids); + assert.deepEqual((await wm.getWindowsByClassName(a.cls)).map(w => w.win_id), [a.id]); + // Each match is a full window object. + assert.deepEqual(wm.getWindowsByPidSync(a.pid)[0], wm.getWindowByIdSync(a.id)); + }); + + test("no match is an empty list", async () => { + assert.deepEqual(wm.getWindowsByPidSync(0), []); + assert.deepEqual(wm.getWindowsByPidSync(2 ** 31), []); + assert.deepEqual(await wm.getWindowsByPid(0), []); + assert.deepEqual(wm.getWindowsByClassNameSync("nope.Nope"), []); + assert.deepEqual(wm.getWindowsByClassNameSync(""), []); + assert.deepEqual(await wm.getWindowsByClassName("nope.Nope"), []); + }); + + test("class names match exactly", async () => { + const f = await fixture(); + const instance = f.cls.replace(".Fixture", ""); + assert.deepEqual(wm.getWindowsByClassNameSync(instance), []); + assert.deepEqual(wm.getWindowsByClassNameSync(f.cls.toUpperCase()), []); + assert.deepEqual(wm.getWindowsByClassNameSync(`${f.cls} `), []); + }); + + test("many concurrent calls stay consistent", async () => { + const f = await fixture(); + const one = wm.getWindowByIdSync(f.id); + const results = await Promise.all(Array.from({ length: 200 }, (_, i) => + i % 3 === 0 ? wm.getWindowById(f.id) : i % 3 === 1 ? wm.getWindowList() : wm.getScreen())); + results.forEach((r, i) => { + if (i % 3 === 0) + assert.deepEqual(r, one); + else if (i % 3 === 1) + assert.ok((r as wm.Window[]).some(w => w.win_id === f.id)); + }); + for (let i = 0; i < 200; i++) + assert.equal(wm.getWindowByIdSync(f.id).win_id, f.id); + }); + }); + + describe("activation", () => { + test("by id, pid and class name; getActiveWindow follows", async () => { + const a = await fixture(); + const b = await fixture(); + assert.equal(wm.activeWindowByIdSync(a.id), true); + await waitFor(() => active() === a.id); + assert.equal(await wm.activeWindowById(b.id), true); + await waitFor(() => active() === b.id); + assert.equal(wm.activeWindowsByClassNameSync(a.cls), true); + await waitFor(() => active() === a.id); + assert.equal(await wm.activeWindowsByPid(b.pid), true); + await waitFor(() => active() === b.id); + assert.equal(wm.activeWindowsByPidSync(a.pid), true); + await waitFor(() => active() === a.id); + assert.equal(await wm.activeWindowsByClassName(b.cls), true); + await waitFor(() => active() === b.id); + assert.equal((await wm.getActiveWindow()).win_id, b.id); + assert.deepEqual(wm.getActiveWindowSync(), wm.getWindowByIdSync(b.id)); + }); + + test("every window of a pid gets activated", async () => { + const f = await fixture({ count: 3 }); + assert.equal(wm.activeWindowsByPidSync(f.pid), true); + await waitFor(() => f.ids.includes(active())); + }); + + test("activating a minimized window restores it", async () => { + const f = await fixture(); + wm.windowMinimizeSync(f.id); + await waitFor(() => states(f.id).includes("_NET_WM_STATE_HIDDEN")); + wm.activeWindowByIdSync(f.id); + await waitFor(() => !states(f.id).includes("_NET_WM_STATE_HIDDEN") && active() === f.id); + }); + + test("errors", async () => { + const legacy = await fixture({ legacy: true }); + assert.throws(() => wm.activeWindowByIdSync(0), { message: "[activeWindowByIdSync] CAN_NOT_ACTIVATE_WINDOW (10)" }); + assert.throws(() => wm.activeWindowByIdSync(MISSING), { message: "[activeWindowByIdSync] CAN_NOT_ACTIVATE_WINDOW (10)" }); + await assert.rejects(wm.activeWindowById(0), { message: "[activeWindowById] CAN_NOT_ACTIVATE_WINDOW (10)" }); + assert.throws(() => wm.activeWindowsByPidSync(0), { message: "[activeWindowsByPidSync] NO_WINDOW_FOUND (24)" }); + await assert.rejects(wm.activeWindowsByPid(2 ** 31), { message: "[activeWindowsByPid] NO_WINDOW_FOUND (24)" }); + assert.throws(() => wm.activeWindowsByClassNameSync("nope.Nope"), { message: "[activeWindowsByClassNameSync] NO_WINDOW_FOUND (24)" }); + await assert.rejects(wm.activeWindowsByClassName("nope.Nope"), { message: "[activeWindowsByClassName] NO_WINDOW_FOUND (24)" }); + // Managed windows always carry _NET_WM_DESKTOP, even legacy ones. + assert.equal(wm.activeWindowByIdSync(legacy.id), true); + }); + }); + + describe("move and resize", () => { + test("windowMoveResize places the frame and sizes the client", async () => { + const f = await fixture(); + assert.equal(wm.windowMoveResizeSync(f.id, 0, 50, 60, 400, 300), true); + await waitFor(() => geometry(f.id).width === 400 && geometry(f.id).height === 300); + const { left, top } = wm.getWindowByIdSync(f.id).frame_extents!; + assert.equal(geometry(f.id).abs_x, 50 + left); + assert.equal(geometry(f.id).abs_y, 60 + top); + + assert.equal(await wm.windowMoveResize(f.id, 0, 70, 80, 410, 310), true); + await waitFor(() => geometry(f.id).width === 410 && geometry(f.id).abs_x === 70 + left); + }); + + test("-1 keeps the current value", async () => { + const f = await fixture(); + wm.windowMoveResizeSync(f.id, 0, 100, 100, 300, 200); + await waitFor(() => geometry(f.id).abs_x > 100); + const before = geometry(f.id); + wm.windowMoveResizeSync(f.id, 0, -1, -1, 500, -1); + await waitFor(() => geometry(f.id).width === 500); + assert.equal(geometry(f.id).height, before.height); + assert.equal(geometry(f.id).abs_x, before.abs_x); + wm.windowMoveResizeSync(f.id, 0, 150, -1, -1, -1); + await waitFor(() => geometry(f.id).abs_x === before.abs_x + 50); + assert.equal(geometry(f.id).abs_y, before.abs_y); + assert.equal(geometry(f.id).width, 500); + }); + + test("every gravity is accepted", async () => { + const f = await fixture(); + for (let gravity = 0; gravity <= 10; gravity++) { + assert.equal(wm.windowMoveResizeSync(f.id, gravity, 100, 100, 200 + gravity, 150), true); + await waitFor(() => geometry(f.id).width === 200 + gravity); + } + }); + + test("size hints are enforced until windowAllowAllSizes", async () => { + const f = await fixture(); + wm.windowMoveResizeSync(f.id, 0, 10, 10, 50, 40); + await waitFor(() => geometry(f.id).abs_x < 50); + assert.deepEqual([geometry(f.id).width, geometry(f.id).height], [100, 80]); // min size + + assert.equal(wm.windowAllowAllSizesSync(f.id), true); + const hints = wm.getWindowByIdSync(f.id).WM_NORMAL_HINTS!; + assert.equal(hints.flags, 0); + assert.equal(hints.min_width, 0); + assert.equal(hints.max_width, 0); + wm.windowMoveResizeSync(f.id, 0, 10, 10, 50, 40); + await waitFor(() => geometry(f.id).width === 50 && geometry(f.id).height === 40); + assert.equal(await wm.windowAllowAllSizes(f.id), true); + }); + + test("windowMoveResizeTransition steps to the target", async () => { + const f = await fixture(); + wm.windowMoveResizeSync(f.id, 0, 0, 0, 300, 200); + await waitFor(() => geometry(f.id).width === 300); + const start = Date.now(); + assert.equal(await wm.windowMoveResizeTransition(f.id, 0, 100, 100, 350, 250, 20, 50), true); + assert.ok(Date.now() - start >= 40, "at least 2 steps of 20ms"); + await waitFor(() => geometry(f.id).width === 350 && geometry(f.id).height === 250); + // Defaults: 1ms per step, 1px per step. + assert.equal(await wm.windowMoveResizeTransition(f.id, 0, -1, -1, 360, -1), true); + await waitFor(() => geometry(f.id).width === 360); + assert.equal(geometry(f.id).height, 250); + // pad 0 used to hang the C addon. + assert.equal(await wm.windowMoveResizeTransition(f.id, 0, -1, -1, 362, -1, 0, 0), true); + await waitFor(() => geometry(f.id).width === 362); + }); + + test("errors", async () => { + const f = await fixture(); + assert.throws(() => wm.windowMoveResizeSync(f.id, -1, 0, 0, 10, 10), { message: "[windowMoveResizeSync] CAN_NOT_MOVE_RESIZE_WINDOW (27)" }); + await assert.rejects(wm.windowMoveResize(f.id, -1, 0, 0, 10, 10), { message: "[windowMoveResize] CAN_NOT_MOVE_RESIZE_WINDOW (27)" }); + await assert.rejects(wm.windowMoveResizeTransition(f.id, -1, 0, 0, 10, 10), { message: "[windowMoveResizeTransition] CAN_NOT_MOVE_RESIZE_WINDOW (27)" }); + await assert.rejects(wm.windowMoveResizeTransition(MISSING, 0, 0, 0, 10, 10), /^Error: \[windowMoveResizeTransition\] /); + }); + }); + + describe("states", () => { + // openbox keeps sticky windows on a desktop rather than flagging them, so sticky is only sent. + const honoured = ["modal", "maximized_vert", "maximized_horz", "shaded", "skip_taskbar", "skip_pager", + "hidden", "fullscreen", "above", "below"]; + + for (const prop of honoured) + test(`add and remove ${prop}`, async () => { + const f = await fixture(); + const flag = `_NET_WM_STATE_${prop.toUpperCase()}`; + assert.equal(wm.windowStateSync(f.id, "add", prop), true); + await waitFor(() => states(f.id).includes(flag)); + assert.equal(await wm.windowState(f.id, "remove", prop), true); + await waitFor(() => !states(f.id).includes(flag)); + }); + + test("sticky is accepted", async () => { + const f = await fixture(); + assert.equal(wm.windowStateSync(f.id, "toggle", "sticky"), true); + assert.equal(await wm.windowState(f.id, "toggle", "sticky"), true); + }); + + test("two properties at once", async () => { + const f = await fixture(); + const maxed = ["_NET_WM_STATE_MAXIMIZED_VERT", "_NET_WM_STATE_MAXIMIZED_HORZ"]; + assert.equal(await wm.windowState(f.id, "add", "maximized_vert", "maximized_horz"), true); + await waitFor(() => maxed.every(s => states(f.id).includes(s))); + const screen = wm.getScreenSync(); + assert.ok(geometry(f.id).width > screen.width / 2); + assert.equal(wm.windowStateSync(f.id, "remove", "maximized_vert", "maximized_horz"), true); + await waitFor(() => !maxed.some(s => states(f.id).includes(s))); + }); + + test("toggle flips the state back and forth", async () => { + const f = await fixture(); + assert.equal(wm.windowStateSync(f.id, "toggle", "above"), true); + await waitFor(() => states(f.id).includes("_NET_WM_STATE_ABOVE")); + assert.equal(wm.windowStateSync(f.id, "toggle", "above"), true); + await waitFor(() => !states(f.id).includes("_NET_WM_STATE_ABOVE")); + }); + + test("actions and properties are case-insensitive", async () => { + const f = await fixture(); + assert.equal(wm.windowStateSync(f.id, "Add", "SHADED"), true); + await waitFor(() => states(f.id).includes("_NET_WM_STATE_SHADED")); + assert.equal(wm.windowStateSync(f.id, "REMOVE", "Shaded"), true); + await waitFor(() => !states(f.id).includes("_NET_WM_STATE_SHADED")); + }); + + test("fullscreen covers the screen", async () => { + const f = await fixture(); + wm.windowAllowAllSizesSync(f.id); // the fixture's 1000x800 max size would cap it + wm.windowStateSync(f.id, "add", "fullscreen"); + const screen = wm.getScreenSync(); + await waitFor(() => geometry(f.id).width === screen.width && geometry(f.id).height === screen.height); + }); + }); + + describe("minimize and raise", () => { + test("windowMinimize hides the window", async () => { + const f = await fixture(); + assert.equal(wm.windowMinimizeSync(f.id), true); + await waitFor(() => states(f.id).includes("_NET_WM_STATE_HIDDEN")); + const g = await fixture(); + assert.equal(await wm.windowMinimize(g.id), true); + await waitFor(() => states(g.id).includes("_NET_WM_STATE_HIDDEN")); + }); + + test("windowMinimize needs an existing window", async () => { + assert.throws(() => wm.windowMinimizeSync(MISSING), { message: "[windowMinimizeSync] CAN_NOT_GET_WINDOW_ATTRIBUTES (36)" }); + await assert.rejects(wm.windowMinimize(MISSING), { message: "[windowMinimize] CAN_NOT_GET_WINDOW_ATTRIBUTES (36)" }); + }); + + test("windowRaise", async () => { + const f = await fixture(); + assert.equal(wm.windowRaiseSync(f.id), true); + assert.equal(await wm.windowRaise(f.id), true); + // Like XRaiseWindow in the C addon, a missing window is not reported. + assert.equal(wm.windowRaiseSync(MISSING), true); + }); + }); + + describe("closing", () => { + test("by id", async () => { + const a = await fixture(); + const b = await fixture(); + assert.equal(wm.closeWindowByIdSync(a.id), true); + await a.exited; + assert.equal(await wm.closeWindowById(b.id), true); + await b.exited; + await waitFor(() => !wm.getWindowListSync().some(w => w.win_id === a.id || w.win_id === b.id)); + }); + + test("by pid closes every window of the process", async () => { + const a = await fixture({ count: 3 }); + const b = await fixture({ count: 2 }); + // The C addon threw on success here. + assert.equal(wm.closeWindowsByPidSync(a.pid), true); + await a.exited; + assert.equal(await wm.closeWindowsByPid(b.pid), true); + await b.exited; + }); + + test("by class name closes every matching process", async () => { + const instance = `wmctrljs-shared-${process.pid}`; + const a = await fixture({ instance }); + const b = await fixture({ instance, count: 2 }); + const other = await fixture(); + assert.equal(wm.closeWindowsByClassNameSync(a.cls), true); + await Promise.all([a.exited, b.exited]); + assert.ok(wm.getWindowListSync().some(w => w.win_id === other.id)); + const c = await fixture(); + assert.equal(await wm.closeWindowsByClassName(c.cls), true); + await c.exited; + }); + + test("errors", async () => { + assert.throws(() => wm.closeWindowsByPidSync(0), { message: "[closeWindowsByPidSync] NO_WINDOW_FOUND (24)" }); + await assert.rejects(wm.closeWindowsByPid(0), { message: "[closeWindowsByPid] NO_WINDOW_FOUND (24)" }); + assert.throws(() => wm.closeWindowsByClassNameSync("nope.Nope"), { message: "[closeWindowsByClassNameSync] NO_WINDOW_FOUND (24)" }); + await assert.rejects(wm.closeWindowsByClassName("nope.Nope"), { message: "[closeWindowsByClassName] NO_WINDOW_FOUND (24)" }); + // Like the C addon, closing by id only sends the request: a missing window is not reported. + assert.equal(wm.closeWindowByIdSync(MISSING), true); + }); + }); +}); diff --git a/src/unit-test/active-window-by-Id.ts b/src/unit-test/active-window-by-Id.ts deleted file mode 100644 index 057a560..0000000 --- a/src/unit-test/active-window-by-Id.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { - activeWindowById, - activeWindowByIdSync, - getWindowsByClassName, - closeWindowById -} from "../index"; -import { createXeyes } from "./utils"; - -export const run = (async () => { - try { - console.log(activeWindowByIdSync(0)); - } catch(e) { - console.log("[activeWindowByIdSync] Volountary error"); - } - - try { - await activeWindowById(0); - } catch(e) { - console.log("[activeWindowById] Volountary error"); - } - - await createXeyes(1); - const windows = await getWindowsByClassName("xeyes.XEyes"); - if (windows.length === 0) { - console.error("Can't create xeyes windos"); - return; - } - - const valid_win_id = windows[0].win_id; - const nbrTest = 1000 - console.time(`[activeWindowByIdSync] duration for ${nbrTest}`); - try { - for (let i = 0; i < nbrTest; i++) - activeWindowByIdSync(valid_win_id); - } catch(e) { - console.log("[activeWindowByIdSync] Volountary error"); - } - console.timeEnd(`[activeWindowByIdSync] duration for ${nbrTest}`); - - console.time(`[activeWindowById] duration for ${nbrTest}`); - try { - const promises = []; - for (let i = 0; i < nbrTest; i++) - promises.push(activeWindowById(valid_win_id)); - await Promise.all(promises); - } catch(e) { - console.log("[activeWindowById] Volountary error"); - } - console.timeEnd(`[activeWindowById] duration for ${nbrTest}`); - closeWindowById(valid_win_id); -})(); \ No newline at end of file diff --git a/src/unit-test/active-windows-by-className.ts b/src/unit-test/active-windows-by-className.ts deleted file mode 100644 index 89b4459..0000000 --- a/src/unit-test/active-windows-by-className.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { - activeWindowsByClassName, - activeWindowsByClassNameSync, - closeWindowsByClassName, - getWindowsByClassName -} from "../index"; -import { createXeyes, wait } from "./utils"; - -export const run = (async () => { - try { - activeWindowsByClassNameSync(""); - } catch(e) { - console.log("[activeWindowsByClassNameSync] Volountary error"); - } - - try { - await activeWindowsByClassName(""); - } catch(e) { - console.log("[activeWindowsByClassName] Volountary error"); - } - - await createXeyes(5); - await wait(5); - const windows = await getWindowsByClassName("xeyes.XEyes"); - if (windows.length === 0) { - console.error("Can't create xeyes windows"); - return; - } - - const valid_win_class_name = "xeyes.XEyes"; - const nbrTest = 10; - console.time(`[activeWindowsByClassNameSync] duration for ${nbrTest}`); - try { - for (let i = 0; i < nbrTest; i++) - activeWindowsByClassNameSync(valid_win_class_name); - } catch(e) { - console.log("[activeWindowsByClassNameSync] Unexpected error", e); - } - console.timeEnd(`[activeWindowsByClassNameSync] duration for ${nbrTest}`); - - console.time(`[activeWindowsByClassName] duration for ${nbrTest}`); - try { - const promises = []; - for (let i = 0; i < nbrTest; i++) - promises.push(activeWindowsByClassName(valid_win_class_name)); - await Promise.all(promises); - } catch(e) { - console.log("[activeWindowsByClassName] Unexpected error", e); - } - console.timeEnd(`[activeWindowsByClassName] duration for ${nbrTest}`); - closeWindowsByClassName(valid_win_class_name); -})(); \ No newline at end of file diff --git a/src/unit-test/active-windows-by-pid.ts b/src/unit-test/active-windows-by-pid.ts deleted file mode 100644 index 1d41fcc..0000000 --- a/src/unit-test/active-windows-by-pid.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { - activeWindowsByPid, - activeWindowsByPidSync, - closeWindowsByPid, - getWindowsByClassName -} from "../index"; -import { wait, createFirefox } from "./utils"; - -export const run = (async () => { - try { - activeWindowsByPidSync(0); - } catch(e) { - console.log("[activeWindowsByPidSync] Volountary error"); - } - - try { - await activeWindowsByPid(0); - } catch(e) { - console.log("[activeWindowsByPid] Volountary error"); - } - - await createFirefox(1); - await wait(2); - const windows = await getWindowsByClassName("Navigator.Firefox"); - if (windows.length === 0) { - console.error("Can't create firefox windows"); - return; - } - const valid_win_pid = windows[0].win_pid; - const nbrTest = 100; - console.time(`[activeWindowsByPidSync] duration for ${nbrTest}`); - try { - for (let i = 0; i < nbrTest; i++) - activeWindowsByPidSync(valid_win_pid); - } catch(e) { - console.log("[activeWindowsByPidSync] Unexpected error", e); - } - console.timeEnd(`[activeWindowsByPidSync] duration for ${nbrTest}`); - - console.time(`[activeWindowsByPid] duration for ${nbrTest}`); - try { - const promises = []; - for (let i = 0; i < nbrTest; i++) - promises.push(activeWindowsByPid(valid_win_pid)); - await Promise.all(promises); - } catch(e) { - console.log("[activeWindowsByPid] Unexpected error", e); - } - console.timeEnd(`[activeWindowsByPid] duration for ${nbrTest}`); - await closeWindowsByPid(valid_win_pid); -})(); \ No newline at end of file diff --git a/src/unit-test/all.ts b/src/unit-test/all.ts deleted file mode 100644 index d3dd992..0000000 --- a/src/unit-test/all.ts +++ /dev/null @@ -1,17 +0,0 @@ -import * as fs from 'fs'; - -const forbbidenFiles = [ - "all.js", - "utils.js" -]; - -(async () => { - const files = fs.readdirSync(__dirname).filter(file => { - if (/^.*\.js$/.test(file) && !forbbidenFiles.includes(file)) - return true; - return false; - }); - for (const file of files) { - await require(`./${file}`).run; - } -})(); \ No newline at end of file diff --git a/src/unit-test/allow-all-sizes-window.ts b/src/unit-test/allow-all-sizes-window.ts deleted file mode 100644 index d60d484..0000000 --- a/src/unit-test/allow-all-sizes-window.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { - getWindowsByClassName, - windowAllowAllSizes, - windowAllowAllSizesSync, - windowMoveResize, - windowMoveResizeSync, - closeWindowById, - closeWindowByIdSync, - getScreen -} from '../index'; -import { createFirefox, wait } from './utils'; - -export const run = (async () => { - await createFirefox(2); - await wait(5); - const screen = await getScreen(); - const windows = await getWindowsByClassName("Navigator.Firefox"); - if (windows.length < 1) { - console.error("Can't create firefox window"); - return; - } - - const wid1 = windows[0].win_id; - const wid2 = windows[1].win_id; - await windowAllowAllSizes(wid1); - windowAllowAllSizesSync(wid2); - - await windowMoveResize(wid1, 0, 0, 0, 50, 50); - await wait(1); - windowMoveResizeSync(wid2, 0, screen.width -50, 0, 50, 50); - await wait(3); - closeWindowById(wid1); - closeWindowByIdSync(wid2); -})(); \ No newline at end of file diff --git a/src/unit-test/closeWindowById.ts b/src/unit-test/closeWindowById.ts deleted file mode 100644 index 64db434..0000000 --- a/src/unit-test/closeWindowById.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { - closeWindowById, - closeWindowByIdSync, - getWindowsByClassName -} from "../index"; -import { createXeyes, wait } from "./utils"; - -export const run = (async () => { - try { - console.log(closeWindowByIdSync(0)); - } catch(e) { - console.log("[closeWindowByIdSync] Volountary error"); - } - - try { - await closeWindowById(0) - } catch(e) { - console.log("[closeWindowById] Volountary error"); - } - - await createXeyes(20); - await wait(5); - const windows = await getWindowsByClassName("xeyes.XEyes"); - if (windows.length === 0) { - console.error("Can't create xeyes windows"); - return; - } - - console.time("[closeWindowByIdSync]"); - try { - for (let i = 0; i < 10; i++) - closeWindowByIdSync(windows[i].win_id); - } catch(e) { - console.error("[closeWindowByIdSync] Unexpected error", e); - } - console.timeEnd("[closeWindowByIdSync]"); - - console.time("[closeWindowById]"); - try { - const promises = []; - for (let i = 10; i < 20; i++) - promises.push(closeWindowById(windows[i].win_id)); - await Promise.all(promises); - } catch(e) { - console.error("[closeWindowById] Unexpected error", e); - } - console.timeEnd("[closeWindowById]"); -})(); \ No newline at end of file diff --git a/src/unit-test/closeWindowsByClassName.ts b/src/unit-test/closeWindowsByClassName.ts deleted file mode 100644 index bb3bc70..0000000 --- a/src/unit-test/closeWindowsByClassName.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { - closeWindowsByClassName, - closeWindowsByClassNameSync -} from "../index"; - -export const run = (async () => { - try { - closeWindowsByClassNameSync(""); - } catch(e) { - console.log("[closeWindowsByClassNameSync] Volountary error"); - } - - try { - await closeWindowsByClassName(""); - } catch(e) { - console.log("[closeWindowsByClassName] Volountary error"); - } -})(); \ No newline at end of file diff --git a/src/unit-test/closeWindowsByPid.ts b/src/unit-test/closeWindowsByPid.ts deleted file mode 100644 index 3c29134..0000000 --- a/src/unit-test/closeWindowsByPid.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { - closeWindowsByPid, - closeWindowsByPidSync -} from "../index"; - -export const run = (async () => { - try { - closeWindowsByPidSync(0); - } catch(e) { - console.log("[closeWindowsByPidSync] Volountary error"); - } - - try { - await closeWindowsByPid(0); - } catch(e) { - console.log("[closeWindowsByPid] Volountary error"); - } -})(); \ No newline at end of file diff --git a/src/unit-test/get-active-window.ts b/src/unit-test/get-active-window.ts deleted file mode 100644 index b8c00fb..0000000 --- a/src/unit-test/get-active-window.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { - getActiveWindowSync, - getActiveWindow -} from '../index'; - -export const run = (async () => { - console.time(`[getActiveWindowSync] duration`); - try { - console.log(getActiveWindowSync()); - } catch(e) { - console.error(e); - } - console.timeEnd(`[getActiveWindowSync] duration`); - - console.time(`[getActiveWindowAsync] duration`); - try { - console.log(await getActiveWindow()); - } catch(e) { - console.error(e); - } - console.timeEnd(`[getActiveWindowAsync] duration`); - - const nbr = 1000; - console.time(`[getActiveWindowSync] for ${nbr} calls`); - try { - for (let i = 0; i < nbr; i++) - getActiveWindowSync(); - } catch(e) { - console.error(e); - } - console.timeEnd(`[getActiveWindowSync] for ${nbr} calls`); - - console.time(`[getActiveWindowAsync] for ${nbr} calls`); - try { - const promises = []; - for (let i = 0; i < nbr; i++) - promises.push(getActiveWindow()); - await Promise.all(promises); - } catch(e) { - console.error(e); - } - console.timeEnd(`[getActiveWindowAsync] for ${nbr} calls`); -})(); \ No newline at end of file diff --git a/src/unit-test/get-screen.ts b/src/unit-test/get-screen.ts deleted file mode 100644 index 718e5f3..0000000 --- a/src/unit-test/get-screen.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { - getScreen, - getScreenSync -} from '../index'; - -export const run = (async () => { - console.time("[getScreenSync]"); - try { - console.log(getScreenSync()); - } - catch(e) { - console.error("[getScreenSync] Unexpected error ", e); - } - console.timeEnd("[getScreenSync]"); - - console.time("[getScreen]"); - try { - console.log(await getScreen()); - } catch(e) { - console.error("[getScreen] Unexpected error ", e); - } - console.timeEnd("[getScreen]"); - - const nbr = 1000; - console.time(`[getScreenSync] ${nbr} calls`); - try { - for (let i = 0; i < nbr; i++) { - getScreenSync(); - } - } catch(e) { - console.error("[getScreenSync] Unexpected error ", e); - } - console.timeEnd(`[getScreenSync] ${nbr} calls`); - - console.time(`[getScreen] ${nbr} calls`); - try { - const promises = []; - for (let i = 0; i < nbr; i++) - promises.push(getScreen()); - - await Promise.all(promises); - } catch(e) { - console.error("[getScreen] Unexpected error ", e); - } - console.timeEnd(`[getScreen] ${nbr} calls`); -})(); \ No newline at end of file diff --git a/src/unit-test/get-windows-by-ClassName.ts b/src/unit-test/get-windows-by-ClassName.ts deleted file mode 100644 index 7eec901..0000000 --- a/src/unit-test/get-windows-by-ClassName.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { - getWindowsByClassNameSync, - getWindowsByClassName, - closeWindowsByClassName -} from '../index'; -import { createXeyes, wait } from './utils'; - -export const run = (async () => { - await createXeyes(3); - - await wait(5); - const windows = await getWindowsByClassName("xeyes.XEyes"); - console.log(windows); - - const class_name = windows[0].win_class; - const nbr = 1000; - console.time("[getWindowsByClassNameSync]"); - try { - for (let i = 0; i < nbr; i++) { - getWindowsByClassNameSync(class_name); - } - } catch(e) { - console.error("[getWindowsByClassNameSync] Unexpected error", e); - } - console.timeEnd("[getWindowsByClassNameSync]"); - - console.time("[getWindowsByClassName]"); - try { - const promises = []; - for (let i = 0; i < nbr; i++) - promises.push(getWindowsByClassName(class_name)); - - await Promise.all(promises); - } catch(e) { - console.error("[getWindowsByClassName] Unexpected error", e); - } - console.timeEnd("[getWindowsByClassName]"); - closeWindowsByClassName(class_name); -})(); \ No newline at end of file diff --git a/src/unit-test/get-windows-by-pid.ts b/src/unit-test/get-windows-by-pid.ts deleted file mode 100644 index 8a99c4e..0000000 --- a/src/unit-test/get-windows-by-pid.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { - getWindowsByPidSync, - getWindowsByPid, - getWindowsByClassName, - closeWindowsByClassName -} from '../index'; -import { createFirefox } from './utils'; - -export const run = (async () => { - await createFirefox(3); - - const windows = await getWindowsByClassName("Navigator.Firefox"); - const pid = windows[0].win_pid; - - console.log(getWindowsByPidSync(pid)); - console.log(await getWindowsByPid(pid)); - - const nbr = 1000; - console.time("[getWindowsByPidSync]"); - try { - for (let i = 0; i < nbr; i++) { - getWindowsByPidSync(pid); - } - } catch(e) { - console.error("[getWindowsByPidSync] Unexpected error", e); - } - console.timeEnd("[getWindowsByPidSync]"); - - console.time("[getWindowsByPid]"); - try { - const promises = []; - for (let i = 0; i < nbr; i++) - promises.push(getWindowsByPid(pid)); - - await Promise.all(promises); - } catch(e) { - console.error("[getWindowsByPid] Unexpected error", e); - } - console.timeEnd("[getWindowsByPid]"); - closeWindowsByClassName("xeyes.XEyes"); -})(); \ No newline at end of file diff --git a/src/unit-test/minimize-window.ts b/src/unit-test/minimize-window.ts deleted file mode 100644 index a6a80cf..0000000 --- a/src/unit-test/minimize-window.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { getWindowsByClassNameSync, windowMinimize, closeWindowById, closeWindowByIdSync } from '../index'; -import { createXeyes, wait } from './utils'; - -export const run = (async () => { - await createXeyes(2); - const windows = await getWindowsByClassNameSync("xeyes.XEyes"); - if (windows.length < 1) { - console.error("Can't create window xeyes"); - return; - } - - const wid1 = windows[0].win_id; - const wid2 = windows[1].win_id; - - await windowMinimize(wid1); - await wait(1); - await windowMinimize(wid2); - closeWindowByIdSync(wid1); - closeWindowById(wid2); -})(); \ No newline at end of file diff --git a/src/unit-test/move-resize-transition-window.ts b/src/unit-test/move-resize-transition-window.ts deleted file mode 100644 index c85f367..0000000 --- a/src/unit-test/move-resize-transition-window.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { - windowMoveResizeTransition, - getWindowsByClassName, - closeWindowsByClassName -} from '../index'; -import { createXeyes, wait } from './utils'; - -export const run = (async () => { - await createXeyes(5); - await wait(1); - const windows = await getWindowsByClassName("xeyes.XEyes"); - - await Promise.all([ - windowMoveResizeTransition(windows[0].win_id, 0, 500, 400, 100, 100, 20, 20), - windowMoveResizeTransition(windows[1].win_id, 0, 150, 150, 100, 100, 20, 20), - windowMoveResizeTransition(windows[2].win_id, 0, 200, 200, 200, 200, 20, 20), - windowMoveResizeTransition(windows[3].win_id, 0, 300, 200, 400, 400, 20, 20), - windowMoveResizeTransition(windows[4].win_id, 0, 400, 400, 400, 400, 20, 20), - windowMoveResizeTransition(windows[0].win_id, 0, 250, 250, 300, 300, 20, 20), - windowMoveResizeTransition(windows[1].win_id, 0, 300, 300, 400, 400, 20, 20), - windowMoveResizeTransition(windows[2].win_id, 0, 350, 350, 500, 500, 20, 20), - windowMoveResizeTransition(windows[3].win_id, 0, 500, 500, 500, 500, 20, 20), - windowMoveResizeTransition(windows[4].win_id, 0, 600, 600, 500, 500, 20, 20), - wait(2) - ]); - closeWindowsByClassName("xeyes.XEyes"); -})(); \ No newline at end of file diff --git a/src/unit-test/move-resize-window.ts b/src/unit-test/move-resize-window.ts deleted file mode 100644 index 3587618..0000000 --- a/src/unit-test/move-resize-window.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { - windowMoveResizeSync, - windowMoveResize, - getWindowsByClassName, - closeWindowsByClassName -} from '../index'; -import { createXeyes, wait } from './utils'; - -export const run = (async () => { - await createXeyes(3); - await wait(3); - const windows = await getWindowsByClassName("xeyes.XEyes"); - - await windowMoveResize(windows[0].win_id, 0, 100, 100, 50, 50); - await windowMoveResize(windows[1].win_id, 0, 150, 150, 100, 100); - await windowMoveResize(windows[2].win_id, 0, 200, 200, 200, 200); - await wait(3); - windowMoveResizeSync(windows[0].win_id, 0, 250, 250, 300, 300); - windowMoveResizeSync(windows[1].win_id, 0, 300, 300, 400, 400); - windowMoveResizeSync(windows[2].win_id, 0, 350, 350, 500, 500); - await wait(3); - closeWindowsByClassName("xeyes.XEyes"); -})(); \ No newline at end of file diff --git a/src/unit-test/raise-window.ts b/src/unit-test/raise-window.ts deleted file mode 100644 index 00af929..0000000 --- a/src/unit-test/raise-window.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { - getWindowsByClassName, - windowRaiseSync, - windowRaise, - closeWindowsByClassName -} from '../index'; -import { createFirefox, wait } from './utils'; - -export const run = (async () => { - await createFirefox(2); - await wait(5); - const windows = await getWindowsByClassName("Navigator.Firefox"); - if (windows.length < 1) { - console.error("Can't create firefox window"); - return; - } - - const wid1 = windows[0].win_id; - const wid2 = windows[1].win_id; - await windowRaise(wid1); - await wait(1); - windowRaiseSync(wid2); - await wait(1); - closeWindowsByClassName("Navigator.Firefox"); -})(); \ No newline at end of file diff --git a/src/unit-test/update-window-state.ts b/src/unit-test/update-window-state.ts deleted file mode 100644 index 0af371f..0000000 --- a/src/unit-test/update-window-state.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { - getWindowsByClassNameSync, - windowState, - windowStateSync, - closeWindowById -} from '../index'; -import { createXeyes, wait } from './utils'; - -export const run = (async () => { - await createXeyes(1); - const windows = getWindowsByClassNameSync("xeyes.XEyes"); - if (windows.length === 0) { - console.error("Can't create window xeyes"); - return; - } - const { win_id } = windows[0]; - await windowState(win_id, "add", "maximized_vert", "maximized_horz"); - await wait(5); - windowStateSync(win_id, "remove", "maximized_vert", "maximized_horz"); - await wait(2); - closeWindowById(win_id); -})(); \ No newline at end of file diff --git a/src/unit-test/utils.ts b/src/unit-test/utils.ts deleted file mode 100644 index f6dd1f0..0000000 --- a/src/unit-test/utils.ts +++ /dev/null @@ -1,21 +0,0 @@ -import * as cp from "child_process"; -import { promisify } from "util"; -const exec = promisify(cp.exec); - -export function wait(time:number):Promise<void> { - return new Promise((resolve) => { - setTimeout(() => { resolve(); }, time * 1000); - }); -} - -export async function createXeyes(nbr:number):Promise<void> { - for (let i = 0; i < nbr; i++) - exec("xeyes"); - return await wait(nbr / 2); -} - -export async function createFirefox(nbr:number):Promise<void> { - for (let i = 0; i < nbr; i++) - exec("firefox"); - return await wait(nbr / 2); -} \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index ca404d4..522455d 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,14 +1,12 @@ { "compilerOptions": { - /* Basic Options */ - "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ - "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ - "sourceMap": true, /* Generates corresponding '.map' file. */ - "outDir": "./dist", /* Redirect output structure to the directory. */ - "rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ - /* Strict Type-Checking Options */ - "strict": true, /* Enable all strict type-checking options. */ - "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ - "declaration": true + "target": "es2022", + "module": "nodenext", + "outDir": "./dist", + "rootDir": "./src", + "types": ["node"], + "strict": true, + "declaration": true, + "sourceMap": true } } diff --git a/yarn.lock b/yarn.lock index 09e0643..8a2f322 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2,17 +2,140 @@ # yarn lockfile v1 -"@types/node@^13.1.6": - version "13.13.14" - resolved "https://registry.yarnpkg.com/@types/node/-/node-13.13.14.tgz#20cd7d2a98f0c3b08d379f4ea9e6b315d2019529" - integrity sha512-Az3QsOt1U/K1pbCQ0TXGELTuTkPLOiFIQf3ILzbOyo0FqgV9SxRnxbxM5QlAveERZMHpZY+7u3Jz2tKyl+yg6g== - -node-addon-api@^2.0.0: - version "2.0.2" - resolved "https://registry.yarnpkg.com/node-addon-api/-/node-addon-api-2.0.2.tgz#432cfa82962ce494b132e9d72a15b29f71ff5d32" - integrity sha512-Ntyt4AIXyaLIuMHF6IOoTakB3K+RWxwtsHNRxllEoA6vPwP9o4866g6YWDLUdnucilZhmkxiHwHr11gAENw+QA== - -node-gyp-build@^4.2.0: - version "4.2.3" - resolved "https://registry.yarnpkg.com/node-gyp-build/-/node-gyp-build-4.2.3.tgz#ce6277f853835f718829efb47db20f3e4d9c4739" - integrity sha512-MN6ZpzmfNCRM+3t57PTJHgHyw/h4OWnZ6mR8P5j/uZtqQr46RRuDE/P+g3n0YR/AiYXeWixZZzaip77gdICfRg== +"@types/node@^22": + version "22.20.5" + resolved "https://registry.yarnpkg.com/@types/node/-/node-22.20.5.tgz#afa7bde6da81b8b83ea4e2f020487e9b148c11fd" + integrity sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA== + dependencies: + undici-types "~6.21.0" + +"@typescript/typescript-aix-ppc64@7.0.2": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz#cdc7ce81d60f1e09034960ddfb1fb880d7a776b6" + integrity sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ== + +"@typescript/typescript-darwin-arm64@7.0.2": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz#a55fdfcfa58df58d27db2237cde6a5c1e35a7235" + integrity sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA== + +"@typescript/typescript-darwin-x64@7.0.2": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz#38d1c9172800a91d707bec64d2a370a016634db4" + integrity sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA== + +"@typescript/typescript-freebsd-arm64@7.0.2": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz#f1ff8810030b35d2b5be0db6a2dc650460ea94fa" + integrity sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ== + +"@typescript/typescript-freebsd-x64@7.0.2": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz#3d86b03f353c5b1ba95162eb6ce35533bfc294bd" + integrity sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw== + +"@typescript/typescript-linux-arm64@7.0.2": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz#d9334d96d6dac6ff85da9c865588948de939e91f" + integrity sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ== + +"@typescript/typescript-linux-arm@7.0.2": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz#ad94b41e1aee2a4dcc6a298c7b67c43345fde32e" + integrity sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ== + +"@typescript/typescript-linux-loong64@7.0.2": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz#2965aee4fc873360139d893daafe6397a29138ad" + integrity sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ== + +"@typescript/typescript-linux-mips64el@7.0.2": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz#1a887a311bed3a833f80bfd4a9ed37c271936cf0" + integrity sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA== + +"@typescript/typescript-linux-ppc64@7.0.2": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz#8b63c9b2f445b393eb4e43ec21da225dade3577d" + integrity sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA== + +"@typescript/typescript-linux-riscv64@7.0.2": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz#b6e8a35c289b3ea97a92a41d461aaeed0d3b36e1" + integrity sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ== + +"@typescript/typescript-linux-s390x@7.0.2": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz#2ef96693be4861f6d17965427e5b009cbbed1a3e" + integrity sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw== + +"@typescript/typescript-linux-x64@7.0.2": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz#73269cb0baba50aea0ca060445a6b88e583f1ce2" + integrity sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A== + +"@typescript/typescript-netbsd-arm64@7.0.2": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz#3a3649f97fafa210b4e6e3798c15e06605c8a901" + integrity sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA== + +"@typescript/typescript-netbsd-x64@7.0.2": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz#47ec59491a40c470d2807dc4d2b825528fd979ab" + integrity sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA== + +"@typescript/typescript-openbsd-arm64@7.0.2": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz#796be8da0bd989d8a3fb96f2801e38a8365b4baf" + integrity sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ== + +"@typescript/typescript-openbsd-x64@7.0.2": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz#d37fe2a729eb942c076c454ee7f1815faf7d560f" + integrity sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg== + +"@typescript/typescript-sunos-x64@7.0.2": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz#aba8d3464c3565a7044789baba96916bd4ab2c88" + integrity sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g== + +"@typescript/typescript-win32-arm64@7.0.2": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz#b9de50a17196383f62620b5f9d0a2f34ad3b60d7" + integrity sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ== + +"@typescript/typescript-win32-x64@7.0.2": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz#cf3b7b0d6ce5635daca4c8e01c189cdcde47ec3c" + integrity sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g== + +typescript@^7.0.2: + version "7.0.2" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-7.0.2.tgz#9ec773d7954a8c182c17cc5bbd575aa28bc51582" + integrity sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA== + optionalDependencies: + "@typescript/typescript-aix-ppc64" "7.0.2" + "@typescript/typescript-darwin-arm64" "7.0.2" + "@typescript/typescript-darwin-x64" "7.0.2" + "@typescript/typescript-freebsd-arm64" "7.0.2" + "@typescript/typescript-freebsd-x64" "7.0.2" + "@typescript/typescript-linux-arm" "7.0.2" + "@typescript/typescript-linux-arm64" "7.0.2" + "@typescript/typescript-linux-loong64" "7.0.2" + "@typescript/typescript-linux-mips64el" "7.0.2" + "@typescript/typescript-linux-ppc64" "7.0.2" + "@typescript/typescript-linux-riscv64" "7.0.2" + "@typescript/typescript-linux-s390x" "7.0.2" + "@typescript/typescript-linux-x64" "7.0.2" + "@typescript/typescript-netbsd-arm64" "7.0.2" + "@typescript/typescript-netbsd-x64" "7.0.2" + "@typescript/typescript-openbsd-arm64" "7.0.2" + "@typescript/typescript-openbsd-x64" "7.0.2" + "@typescript/typescript-sunos-x64" "7.0.2" + "@typescript/typescript-win32-arm64" "7.0.2" + "@typescript/typescript-win32-x64" "7.0.2" + +undici-types@~6.21.0: + version "6.21.0" + resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-6.21.0.tgz#691d00af3909be93a7faa13be61b3a5b50ef12cb" + integrity sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ== From 7e20340ca9c5e210d80a728ed580043d3afb8226 Mon Sep 17 00:00:00 2001 From: kecsou <kevin.voyer.developpeur@gmail.com> Date: Sat, 31 Oct 2026 17:27:15 +0100 Subject: [PATCH 2/5] Fix transition pauses and windows on a second X screen From review of the Rust rewrite: - windowMoveResizeTransition: an await_time no Duration can hold (Infinity, 1e300) panicked on the libuv thread and aborted Node. It now rejects with CAN_NOT_MOVE_RESIZE_WINDOW before touching the window. - Window geometry: abs_x/abs_y of a window on another screen than the default one came out as 0,0. Translate to the window's own root, as the C addon did (one extra round trip, only for such windows). Transitions start from the window's own root too. - windowMinimize: send WM_CHANGE_STATE to the root of the window's screen, like XIconifyWindow, so that screen's WM receives it. Tests: a Rust unit test and an API test for the pause, and X11 tests on a second Xvfb screen with its own openbox (WMCTRLJS_SCREEN1), now set up in CI. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .github/workflows/ci.yml | 10 ++++++---- README.md | 4 ++-- native/src/wm.rs | 41 +++++++++++++++++++++++++++------------- src/test/api.test.ts | 6 ++++++ src/test/x11.test.ts | 26 ++++++++++++++++++++++--- 5 files changed, 65 insertions(+), 22 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 424992d..710aa20 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,7 +27,7 @@ jobs: path: dist/ # Cross-built with zig against old glibc releases, then tested in a container of the target arch - # (QEMU when it is not the runner's) with Xvfb and openbox. + # (QEMU when it is not the runner's) with a two-screen Xvfb and an openbox per screen. linux: needs: dist runs-on: ${{ matrix.runner || 'ubuntu-24.04' }} @@ -68,7 +68,8 @@ jobs: -e WMCTRLJS_FIXTURE=fixtures/${{ matrix.dir }}/fixture ${{ matrix.image }} sh -ec ' if command -v apk; then apk add --no-cache xvfb-run openbox; else apt-get update && apt-get install -y --no-install-recommends xvfb xauth openbox $(command -v node >/dev/null || echo nodejs); fi; - xvfb-run -a sh -c "openbox & node --test dist/test/*.test.js"' + xvfb-run -a -s "-screen 0 1280x1024x24 -screen 1 800x600x24" sh -c + "openbox & DISPLAY=\$DISPLAY.1 openbox & WMCTRLJS_SCREEN1=\$DISPLAY.1 node --test dist/test/*.test.js"' - uses: actions/upload-artifact@v7 with: name: prebuild-${{ matrix.dir }} @@ -91,9 +92,10 @@ jobs: run: | set -e node scripts/build-native.js - Xvfb :99 -nolisten tcp & sleep 2 + Xvfb :99 -screen 0 1280x1024x24 -screen 1 800x600x24 -nolisten tcp & sleep 2 DISPLAY=:99 openbox & - DISPLAY=:99 WMCTRLJS_FIXTURE=fixtures/freebsd-x64/fixture node --test dist/test/*.test.js + DISPLAY=:99.1 openbox & + DISPLAY=:99 WMCTRLJS_SCREEN1=:99.1 WMCTRLJS_FIXTURE=fixtures/freebsd-x64/fixture node --test dist/test/*.test.js - uses: actions/upload-artifact@v7 with: name: prebuild-freebsd-x64 diff --git a/README.md b/README.md index 6f284dd..4fc0952 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ Requirements: Node.js 18+, a Rust toolchain, and for tests an X server with an E yarn install yarn build:native # cargo build -> prebuilds/<platform>-<arch>/wmctrljs.node (+ the test fixture window) yarn build # TypeScript 7 -xvfb-run -a sh -c 'openbox & yarn test' +xvfb-run -a -s '-screen 0 1280x1024x24 -screen 1 800x600x24' sh -c 'openbox & DISPLAY=$DISPLAY.1 openbox & WMCTRLJS_SCREEN1=$DISPLAY.1 yarn test' cd native && cargo test --lib # Rust unit tests, no X server needed ``` @@ -50,7 +50,7 @@ Cross builds use [cargo-zigbuild](https://github.com/rust-cross/cargo-zigbuild) Three suites guard against regressions: - Rust unit tests: property decoding, window JSON, size hints, gravity flags, transitions, error codes. - `api.test`: exports, argument validation and error messages of every function, and the binary loader. Runs without X. -- `x11.test`: every function against a real window manager. It spawns its own fixture windows (`native/examples/fixture.rs`) and only ever acts on those. It is skipped when `DISPLAY` is unset. +- `x11.test`: every function against a real window manager. It spawns its own fixture windows (`native/examples/fixture.rs`) and only ever acts on those. It is skipped when `DISPLAY` is unset, and its second-screen tests when `WMCTRLJS_SCREEN1` (a display string for screen 1 of the same server, with its own window manager) is unset. CI builds and tests the 15 targets above, and publishes to npm when a `v*` tag is pushed. diff --git a/native/src/wm.rs b/native/src/wm.rs index f2eff77..9c23187 100644 --- a/native/src/wm.rs +++ b/native/src/wm.rs @@ -393,10 +393,10 @@ impl X { reply(self.get(win, prop, ty), ty) } - fn msg(&self, win: Window, ty: Atom, data: [u32; 5]) -> Result<(), Fail> { + fn msg(&self, root: Window, win: Window, ty: Atom, data: [u32; 5]) -> Result<(), Fail> { let ev = ClientMessageEvent::new(32, win, ty, data); let mask = EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY; - self.c.send_event(false, self.root, mask, ev)?; + self.c.send_event(false, root, mask, ev)?; Ok(()) } @@ -438,7 +438,11 @@ impl X { fn window(&self, p: Pending<'_>) -> Value { let geo = p.geo.and_then(|c| c.reply().ok()); - let abs = p.abs.and_then(|c| c.reply().ok()); + let abs = match (&geo, p.abs.and_then(|c| c.reply().ok())) { + // On another screen than the default one: translate to the window's own root (one more round trip). + (Some(g), Some(a)) if !a.same_screen => self.c.translate_coordinates(p.win, g.root, 0, 0).ok().and_then(|c| c.reply().ok()), + (_, abs) => abs, + }; window_json(p.win, p.props.map(|(ck, ty)| reply(ck, ty)), geo.zip(abs), &self.flags) } @@ -468,7 +472,7 @@ impl X { } self.c.configure_window(win, &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE))?; self.c.map_window(win)?; - self.msg(win, self.a._NET_ACTIVE_WINDOW, [0; 5]) + self.msg(self.root, win, self.a._NET_ACTIVE_WINDOW, [0; 5]) } fn supports(&self, atom: Atom) -> bool { @@ -481,7 +485,7 @@ impl X { } if self.supports(self.a._NET_MOVERESIZE_WINDOW) { let flags = moveresize_flags(grav, [x, y, w, h]); - return self.msg(win, self.a._NET_MOVERESIZE_WINDOW, [flags, x as u32, y as u32, w as u32, h as u32]); + return self.msg(self.root, win, self.a._NET_MOVERESIZE_WINDOW, [flags, x as u32, y as u32, w as u32, h as u32]); } self.c.configure_window(win, &fallback_geometry([x, y, w, h]))?; Ok(()) @@ -534,14 +538,14 @@ pub fn activate_by(by: &By) -> Res { pub fn close(win: Window) -> Res { let x = X::open()?; - x.msg(win, x.a._NET_CLOSE_WINDOW, [0; 5])?; + x.msg(x.root, win, x.a._NET_CLOSE_WINDOW, [0; 5])?; x.done() } pub fn close_by(by: &By) -> Res { let x = X::open()?; for win in x.find_ids(by)? { - x.msg(win, x.a._NET_CLOSE_WINDOW, [0; 5])?; + x.msg(x.root, win, x.a._NET_CLOSE_WINDOW, [0; 5])?; } x.done() } @@ -556,17 +560,18 @@ pub fn move_resize(win: Window, grav: i32, x: i32, y: i32, w: i32, h: i32) -> Re /// waiting `await_ms` between steps. -1 leaves a value untouched. #[allow(clippy::too_many_arguments)] pub fn move_resize_transition(win: Window, grav: i32, x: i32, y: i32, w: i32, h: i32, await_ms: f64, pad: i32) -> Res { + let pause = Duration::try_from_secs_f64(await_ms.max(0.0) / 1000.0).map_err(|_| Fail::CanNotMoveResizeWindow)?; let c = X::open()?; if grav < 0 { return Err(Fail::CanNotMoveResizeWindow); } let geo = c.c.get_geometry(win)?.reply()?; - let abs = c.c.translate_coordinates(win, c.root, 0, 0)?.reply()?; + let abs = c.c.translate_coordinates(win, geo.root, 0, 0)?.reply()?; let from = [abs.dst_x.into(), abs.dst_y.into(), geo.width.into(), geo.height.into()]; for [x, y, w, h] in transition(from, [x, y, w, h], pad) { c.move_resize(win, grav, x, y, w, h)?; c.c.sync()?; - thread::sleep(Duration::from_secs_f64(await_ms.max(0.0) / 1000.0)); + thread::sleep(pause); } c.done() } @@ -580,15 +585,17 @@ pub fn state(win: Window, action: &str, prop1: &str, prop2: &str) -> Res { } Ok(x.c.intern_atom(false, state_atom_name(p).as_bytes())?.reply()?.atom) }; - x.msg(win, x.a._NET_WM_STATE, [action, atom(prop1)?, atom(prop2)?, 0, 0])?; + x.msg(x.root, win, x.a._NET_WM_STATE, [action, atom(prop1)?, atom(prop2)?, 0, 0])?; x.done() } -/// XIconifyWindow: ask the WM to switch the window to IconicState (3). +/// XIconifyWindow: ask the WM of the window's own screen to switch it to IconicState (3). pub fn minimize(win: Window) -> Res { let x = X::open()?; - x.c.get_window_attributes(win)?.reply().map_err(|_| Fail::CanNotGetWindowAttributes)?; - x.msg(win, x.a.WM_CHANGE_STATE, [3, 0, 0, 0, 0])?; + let (attrs, geo) = (x.c.get_window_attributes(win)?, x.c.get_geometry(win)?); + attrs.reply().map_err(|_| Fail::CanNotGetWindowAttributes)?; + let root = geo.reply().map_err(|_| Fail::CanNotGetWindowAttributes)?.root; + x.msg(root, win, x.a.WM_CHANGE_STATE, [3, 0, 0, 0, 0])?; x.done() } @@ -630,6 +637,14 @@ mod tests { flags()[name] } + #[test] + fn transitions_refuse_pauses_a_duration_cannot_hold() { + // Checked before connecting: no display needed. + for ms in [f64::INFINITY, 1e300] { + assert_eq!(move_resize_transition(1, 0, 0, 0, 1, 1, ms, 1), Err(Fail::CanNotMoveResizeWindow), "{ms}"); + } + } + #[test] fn fail_messages_keep_the_c_codes() { let all = [ diff --git a/src/test/api.test.ts b/src/test/api.test.ts index 09117a1..c52199f 100644 --- a/src/test/api.test.ts +++ b/src/test/api.test.ts @@ -130,6 +130,12 @@ describe("windowState validation", () => { }); }); +test("windowMoveResizeTransition refuses a pause no timer can hold", async () => { + // Checked before connecting, so this needs no display. + for (const ms of [Infinity, 1e300]) + await assert.rejects(wm.windowMoveResizeTransition(1, 0, 0, 0, 10, 10, ms, 1), { message: "[windowMoveResizeTransition] CAN_NOT_MOVE_RESIZE_WINDOW (27)" }); +}); + describe("binary loader", () => { // Runs index.js in a child process after `setup`, printing the native path it requires. const load = (setup:string) => execFileSync(process.execPath, ["-e", ` diff --git a/src/test/x11.test.ts b/src/test/x11.test.ts index dd6db65..e501409 100644 --- a/src/test/x11.test.ts +++ b/src/test/x11.test.ts @@ -11,6 +11,8 @@ import * as wm from "../index"; const FIXTURE = process.env.WMCTRLJS_FIXTURE ?? path.join(__dirname, "../../native/target/release/examples/fixture"); const skip = !process.env.DISPLAY && "DISPLAY is not set"; +// Screen 1 of the same X server, managed by its own window manager. +const skipScreen1 = !process.env.WMCTRLJS_SCREEN1 && "WMCTRLJS_SCREEN1 is not set"; const spawned:ChildProcess[] = []; interface Fixture { @@ -22,10 +24,11 @@ interface Fixture { } let serial = 0; -async function fixture(opts:{ count?:number, legacy?:boolean, instance?:string } = {}):Promise<Fixture> { +async function fixture(opts:{ count?:number, legacy?:boolean, instance?:string, screen1?:boolean } = {}):Promise<Fixture> { const instance = opts.instance ?? `wmctrljs-${process.pid}-${serial++}`; const args = [instance, `title ${instance}`, String(opts.count ?? 1), opts.legacy ? "legacy" : ""]; - const proc = spawn(FIXTURE, args, { stdio: ["ignore", "pipe", "inherit"] }); + const env = opts.screen1 ? { ...process.env, DISPLAY: process.env.WMCTRLJS_SCREEN1 } : process.env; + const proc = spawn(FIXTURE, args, { stdio: ["ignore", "pipe", "inherit"], env }); spawned.push(proc); const exited = once(proc, "exit"); const ids:number[] = []; @@ -34,7 +37,8 @@ async function fixture(opts:{ count?:number, legacy?:boolean, instance?:string } if (ids.length === (opts.count ?? 1)) break; } - await waitFor(() => ids.every(id => wm.getWindowListSync().some(w => w.win_id === id))); + // _NET_CLIENT_LIST only covers the default screen: on screen 1, wait for the WM's frame instead. + await waitFor(() => ids.every(id => opts.screen1 ? wm.getWindowByIdSync(id).frame_extents : wm.getWindowListSync().some(w => w.win_id === id))); return { ids, id: ids[0], pid: proc.pid!, cls: `${instance}.Fixture`, exited }; } @@ -413,6 +417,22 @@ describe("X11", { skip }, () => { }); }); + describe("a window on another screen", { skip: skipScreen1 }, () => { + test("its absolute position is on its own root", async () => { + const f = await fixture({ screen1: true }); + const { left, top } = wm.getWindowByIdSync(f.id).frame_extents!; + // Translated to the default root instead, X answers 0,0. + assert.ok(top > 0); + assert.ok(geometry(f.id).abs_x >= left && geometry(f.id).abs_y >= top, JSON.stringify(geometry(f.id))); + }); + + test("windowMinimize reaches its window manager", async () => { + const f = await fixture({ screen1: true }); + assert.equal(wm.windowMinimizeSync(f.id), true); + await waitFor(() => states(f.id).includes("_NET_WM_STATE_HIDDEN")); + }); + }); + describe("closing", () => { test("by id", async () => { const a = await fixture(); From 46940b57d032c0a9183dc52d26bef67d1bc7ef25 Mon Sep 17 00:00:00 2001 From: kecsou <kevin.voyer.developpeur@gmail.com> Date: Sat, 31 Oct 2026 17:42:19 +0100 Subject: [PATCH 3/5] Forbid unsafe and panics in the native code - Drop the Json wrapper and its unsafe ToNapiValue impl: sync functions return serde_json::Value, async jobs implement ScopedTask and resolve through the safe Env::to_js_value. - unsafe_code is denied crate-wide and forbidden in wm.rs (it cannot be forbidden at the crate root: #[napi] expands to code that allows it). - Clippy forbids unwrap, expect, panic!, unreachable!, todo!, unimplemented!, indexing/slicing, string slicing and unchecked arithmetic; clippy.toml relaxes the panic lints in tests only. - What the lints found: transitions now step with saturating arithmetic and lazily (pad 1 towards i32::MAX overflowed, or allocated every step up front), and lookups use get() instead of indexing. - Any panic left (in a dependency) is caught at the N-API boundary and reported as INTERNAL_ERROR (43) instead of aborting Node. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- README.md | 4 ++ native/Cargo.toml | 16 +++++ native/clippy.toml | 4 ++ native/examples/fixture.rs | 4 +- native/src/lib.rs | 126 ++++++++++++++++++------------------- native/src/wm.rs | 122 +++++++++++++++++++---------------- 6 files changed, 158 insertions(+), 118 deletions(-) create mode 100644 native/clippy.toml diff --git a/README.md b/README.md index 4fc0952..6bf7261 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ The native part is written in Rust ([napi-rs](https://napi.rs) + [x11rb](https:/ Every function exists in two flavours: `xxxSync` runs on the calling thread, `xxx` returns a promise and runs on the libuv thread pool. Errors are `Error` objects whose message looks like `[functionName] NO_WINDOW_FOUND (24)`. +A bug that would have crashed the native code is reported as `INTERNAL_ERROR (43)` instead of taking the Node process down. ## Upgrading from 1.x @@ -32,6 +33,7 @@ The JS API is unchanged. The behaviour changes below are fixes: - Windows now carry `win_icon_name` (it was declared but never set). The `Aspect` type now says `numerator` / `denominator`, which is what was always returned. - `windowMoveResizeTransition` really animates y (it used to step it with x) and starts from the window's absolute position. - The 1.x C addon double-freed memory in `getActiveWindow()` and could crash the process. That is gone. +- `windowMoveResizeTransition` rejects an `await_time` no timer can hold (`Infinity`) and handles extreme coordinates without overflowing. ## Development @@ -47,6 +49,8 @@ cd native && cargo test --lib # Rust unit tests, no X server needed Cross builds use [cargo-zigbuild](https://github.com/rust-cross/cargo-zigbuild) (and zig): `node scripts/build-native.js --zig --target aarch64-unknown-linux-gnu.2.17 --dir linux-arm64`. +The native code has no `unsafe`, `unwrap`, `expect`, `panic!`, unchecked indexing or unchecked arithmetic outside tests: lints in `native/Cargo.toml` reject them, and CI runs clippy with `-D warnings`. + Three suites guard against regressions: - Rust unit tests: property decoding, window JSON, size hints, gravity flags, transitions, error codes. - `api.test`: exports, argument validation and error messages of every function, and the binary loader. Runs without X. diff --git a/native/Cargo.toml b/native/Cargo.toml index bc2de3c..04503f7 100644 --- a/native/Cargo.toml +++ b/native/Cargo.toml @@ -13,6 +13,22 @@ napi-derive = "3" serde_json = { version = "1", features = ["preserve_order"] } x11rb = "0.14" +# Nothing may panic or use unsafe outside tests (clippy.toml relaxes the panic lints in tests, +# lib.rs forbids unsafe outside them). CI runs clippy with -D warnings. +[lints.rust] +unsafe_code = "deny" + +[lints.clippy] +unwrap_used = "forbid" +expect_used = "forbid" +panic = "forbid" +unreachable = "forbid" +todo = "forbid" +unimplemented = "forbid" +indexing_slicing = "forbid" +string_slice = "forbid" +arithmetic_side_effects = "forbid" + [build-dependencies] napi-build = "2" diff --git a/native/clippy.toml b/native/clippy.toml new file mode 100644 index 0000000..4b6c79f --- /dev/null +++ b/native/clippy.toml @@ -0,0 +1,4 @@ +allow-unwrap-in-tests = true +allow-expect-in-tests = true +allow-panic-in-tests = true +allow-indexing-slicing-in-tests = true diff --git a/native/examples/fixture.rs b/native/examples/fixture.rs index 0cb7595..3d715b9 100644 --- a/native/examples/fixture.rs +++ b/native/examples/fixture.rs @@ -15,7 +15,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> { let legacy = args.get(3).is_some_and(|s| s == "legacy"); let (c, n) = x11rb::connect(None)?; - let screen = &c.setup().roots[n]; + let screen = c.setup().roots.get(n).ok_or("no such screen")?; let atom = |name: &str| -> Result<Atom, Box<dyn std::error::Error>> { Ok(c.intern_atom(false, name.as_bytes())?.reply()?.atom) }; let (utf8, protocols, delete) = (atom("UTF8_STRING")?, atom("WM_PROTOCOLS")?, atom("WM_DELETE_WINDOW")?); @@ -54,7 +54,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> { while !wins.is_empty() { if let Event::ClientMessage(ev) = c.wait_for_event()? - && ev.data.as_data32()[0] == delete + && ev.data.as_data32().first() == Some(&delete) { c.destroy_window(ev.window)?; c.flush()?; diff --git a/native/src/lib.rs b/native/src/lib.rs index 2796c5d..801b140 100644 --- a/native/src/lib.rs +++ b/native/src/lib.rs @@ -1,5 +1,10 @@ //! N-API bindings: every operation is exported as `<name>Sync` and `<name>Async`. +//! No unsafe here: napi-rs does the raw N-API calls. `unsafe_code` is denied crate-wide (Cargo.toml); +//! it cannot be forbidden at the root because #[napi] expands to code that allows it. +use std::panic::{AssertUnwindSafe, catch_unwind}; + +use napi::ScopedTask; use napi::bindgen_prelude::*; use napi_derive::napi; use serde_json::Value; @@ -7,30 +12,17 @@ use serde_json::Value; mod wm; use wm::{By, Fail, Res}; -pub struct Json(Value); - -impl TypeName for Json { - fn type_name() -> &'static str { - "Object" - } - - fn value_type() -> ValueType { - ValueType::Object - } -} - -impl ToNapiValue for Json { - unsafe fn to_napi_value(env: sys::napi_env, val: Self) -> Result<sys::napi_value> { - unsafe { Value::to_napi_value(env, val.0) } - } -} - fn error(name: &str, fail: Fail) -> Error { Error::from_reason(format!("[{name}] {fail}")) } -fn now(name: &str, res: Res) -> Result<Json> { - res.map(Json).map_err(|f| error(name, f)) +/// Runs an operation, turning a panic (from a dependency, say) into an error instead of aborting Node. +fn guard(op: impl FnOnce() -> Res) -> Res { + catch_unwind(AssertUnwindSafe(op)).unwrap_or(Err(Fail::Internal)) +} + +fn now(name: &str, op: impl FnOnce() -> Res) -> Result<Value> { + guard(op).map_err(|f| error(name, f)) } type Op = Box<dyn FnOnce() -> Res + Send>; @@ -38,17 +30,17 @@ type Op = Box<dyn FnOnce() -> Res + Send>; /// Runs an operation on the libuv thread pool and settles a promise with it. pub struct Job(&'static str, Option<Op>); -impl Task for Job { +impl<'task> ScopedTask<'task> for Job { type Output = Value; - type JsValue = Json; + type JsValue = Unknown<'task>; fn compute(&mut self) -> Result<Value> { - let op = self.1.take().expect("a job runs once"); - op().map_err(|f| error(self.0, f)) + let op = self.1.take().ok_or(Fail::Internal); + op.and_then(guard).map_err(|f| error(self.0, f)) } - fn resolve(&mut self, _env: Env, out: Value) -> Result<Json> { - Ok(Json(out)) + fn resolve(&mut self, env: &'task Env, out: Value) -> Result<Unknown<'task>> { + env.to_js_value(&out) } } @@ -57,8 +49,8 @@ fn later(name: &'static str, op: impl FnOnce() -> Res + Send + 'static) -> Async } #[napi] -pub fn get_screen_sync() -> Result<Json> { - now("getScreenSync", wm::screen()) +pub fn get_screen_sync() -> Result<Value> { + now("getScreenSync", wm::screen) } #[napi] @@ -67,8 +59,8 @@ pub fn get_screen_async() -> AsyncTask<Job> { } #[napi] -pub fn get_window_by_id_sync(win_id: u32) -> Result<Json> { - now("getWindowByIdSync", wm::window(win_id)) +pub fn get_window_by_id_sync(win_id: u32) -> Result<Value> { + now("getWindowByIdSync", || wm::window(win_id)) } #[napi] @@ -77,8 +69,8 @@ pub fn get_window_by_id_async(win_id: u32) -> AsyncTask<Job> { } #[napi] -pub fn get_active_window_sync() -> Result<Json> { - now("getActiveWindowSync", wm::active_window()) +pub fn get_active_window_sync() -> Result<Value> { + now("getActiveWindowSync", wm::active_window) } #[napi] @@ -87,8 +79,8 @@ pub fn get_active_window_async() -> AsyncTask<Job> { } #[napi] -pub fn get_window_list_sync() -> Result<Json> { - now("getWindowListSync", wm::list()) +pub fn get_window_list_sync() -> Result<Value> { + now("getWindowListSync", wm::list) } #[napi] @@ -97,8 +89,8 @@ pub fn get_window_list_async() -> AsyncTask<Job> { } #[napi] -pub fn get_windows_by_pid_sync(win_pid: u32) -> Result<Json> { - now("getWindowsByPidSync", wm::windows_by(&By::Pid(win_pid))) +pub fn get_windows_by_pid_sync(win_pid: u32) -> Result<Value> { + now("getWindowsByPidSync", || wm::windows_by(&By::Pid(win_pid))) } #[napi] @@ -107,8 +99,8 @@ pub fn get_windows_by_pid_async(win_pid: u32) -> AsyncTask<Job> { } #[napi] -pub fn get_windows_by_class_name_sync(win_class_name: String) -> Result<Json> { - now("getWindowsByClassNameSync", wm::windows_by(&By::Class(win_class_name))) +pub fn get_windows_by_class_name_sync(win_class_name: String) -> Result<Value> { + now("getWindowsByClassNameSync", || wm::windows_by(&By::Class(win_class_name))) } #[napi] @@ -117,8 +109,8 @@ pub fn get_windows_by_class_name_async(win_class_name: String) -> AsyncTask<Job> } #[napi] -pub fn active_window_by_id_sync(win_id: u32) -> Result<Json> { - now("activeWindowByIdSync", wm::activate(win_id)) +pub fn active_window_by_id_sync(win_id: u32) -> Result<Value> { + now("activeWindowByIdSync", || wm::activate(win_id)) } #[napi] @@ -127,8 +119,8 @@ pub fn active_window_by_id_async(win_id: u32) -> AsyncTask<Job> { } #[napi] -pub fn active_windows_by_pid_sync(win_pid: u32) -> Result<Json> { - now("activeWindowsByPidSync", wm::activate_by(&By::Pid(win_pid))) +pub fn active_windows_by_pid_sync(win_pid: u32) -> Result<Value> { + now("activeWindowsByPidSync", || wm::activate_by(&By::Pid(win_pid))) } #[napi] @@ -137,8 +129,8 @@ pub fn active_windows_by_pid_async(win_pid: u32) -> AsyncTask<Job> { } #[napi] -pub fn active_windows_by_class_name_sync(win_class_name: String) -> Result<Json> { - now("activeWindowsByClassNameSync", wm::activate_by(&By::Class(win_class_name))) +pub fn active_windows_by_class_name_sync(win_class_name: String) -> Result<Value> { + now("activeWindowsByClassNameSync", || wm::activate_by(&By::Class(win_class_name))) } #[napi] @@ -147,8 +139,8 @@ pub fn active_windows_by_class_name_async(win_class_name: String) -> AsyncTask<J } #[napi] -pub fn close_window_by_id_sync(win_id: u32) -> Result<Json> { - now("closeWindowByIdSync", wm::close(win_id)) +pub fn close_window_by_id_sync(win_id: u32) -> Result<Value> { + now("closeWindowByIdSync", || wm::close(win_id)) } #[napi] @@ -157,8 +149,8 @@ pub fn close_window_by_id_async(win_id: u32) -> AsyncTask<Job> { } #[napi] -pub fn close_windows_by_pid_sync(win_pid: u32) -> Result<Json> { - now("closeWindowsByPidSync", wm::close_by(&By::Pid(win_pid))) +pub fn close_windows_by_pid_sync(win_pid: u32) -> Result<Value> { + now("closeWindowsByPidSync", || wm::close_by(&By::Pid(win_pid))) } #[napi] @@ -167,8 +159,8 @@ pub fn close_windows_by_pid_async(win_pid: u32) -> AsyncTask<Job> { } #[napi] -pub fn close_windows_by_class_name_sync(win_class_name: String) -> Result<Json> { - now("closeWindowsByClassNameSync", wm::close_by(&By::Class(win_class_name))) +pub fn close_windows_by_class_name_sync(win_class_name: String) -> Result<Value> { + now("closeWindowsByClassNameSync", || wm::close_by(&By::Class(win_class_name))) } #[napi] @@ -177,8 +169,8 @@ pub fn close_windows_by_class_name_async(win_class_name: String) -> AsyncTask<Jo } #[napi] -pub fn window_move_resize_sync(win_id: u32, gravity: i32, x: i32, y: i32, width: i32, height: i32) -> Result<Json> { - now("windowMoveResizeSync", wm::move_resize(win_id, gravity, x, y, width, height)) +pub fn window_move_resize_sync(win_id: u32, gravity: i32, x: i32, y: i32, width: i32, height: i32) -> Result<Value> { + now("windowMoveResizeSync", || wm::move_resize(win_id, gravity, x, y, width, height)) } #[napi] @@ -204,8 +196,8 @@ pub fn window_move_resize_transition_async( } #[napi] -pub fn window_state_sync(win_id: u32, action: String, prop1: String, prop2: String) -> Result<Json> { - now("windowStateSync", wm::state(win_id, &action, &prop1, &prop2)) +pub fn window_state_sync(win_id: u32, action: String, prop1: String, prop2: String) -> Result<Value> { + now("windowStateSync", || wm::state(win_id, &action, &prop1, &prop2)) } #[napi] @@ -214,8 +206,8 @@ pub fn window_state_async(win_id: u32, action: String, prop1: String, prop2: Str } #[napi] -pub fn window_minimize_sync(win_id: u32) -> Result<Json> { - now("windowMinimizeSync", wm::minimize(win_id)) +pub fn window_minimize_sync(win_id: u32) -> Result<Value> { + now("windowMinimizeSync", || wm::minimize(win_id)) } #[napi] @@ -224,8 +216,8 @@ pub fn window_minimize_async(win_id: u32) -> AsyncTask<Job> { } #[napi] -pub fn window_allow_all_sizes_sync(win_id: u32) -> Result<Json> { - now("windowAllowAllSizesSync", wm::allow_all_sizes(win_id)) +pub fn window_allow_all_sizes_sync(win_id: u32) -> Result<Value> { + now("windowAllowAllSizesSync", || wm::allow_all_sizes(win_id)) } #[napi] @@ -234,8 +226,8 @@ pub fn window_allow_all_sizes_async(win_id: u32) -> AsyncTask<Job> { } #[napi] -pub fn window_raise_sync(win_id: u32) -> Result<Json> { - now("windowRaiseSync", wm::raise(win_id)) +pub fn window_raise_sync(win_id: u32) -> Result<Value> { + now("windowRaiseSync", || wm::raise(win_id)) } #[napi] @@ -250,8 +242,8 @@ mod tests { #[test] fn errors_are_prefixed_with_the_js_name() { assert_eq!(error("getScreenSync", Fail::CanNotOpenDisplay).reason, "[getScreenSync] CAN_NOT_OPEN_DISPLAY (3)"); - assert_eq!(now("closeWindowsByPidSync", Err(Fail::NoWindowFound)).err().unwrap().reason, "[closeWindowsByPidSync] NO_WINDOW_FOUND (24)"); - assert_eq!(now("x", Ok(Value::Bool(true))).ok().unwrap().0, Value::Bool(true)); + assert_eq!(now("closeWindowsByPidSync", || Err(Fail::NoWindowFound)).unwrap_err().reason, "[closeWindowsByPidSync] NO_WINDOW_FOUND (24)"); + assert_eq!(now("x", || Ok(Value::Bool(true))).unwrap(), Value::Bool(true)); } #[test] @@ -260,12 +252,20 @@ mod tests { assert_eq!(ok.compute().unwrap(), Value::Array(vec![])); let mut fail = Job("getWindowList", Some(Box::new(|| Err(Fail::CanNotGetClientList)))); assert_eq!(fail.compute().unwrap_err().reason, "[getWindowList] CAN_NOT_GET_CLIENT_LIST (1)"); - assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| ok.compute())).is_err()); + assert_eq!(ok.compute().unwrap_err().reason, "[getWindowList] INTERNAL_ERROR (43)"); + } + + #[test] + fn panics_become_errors() { + assert_eq!(now("getScreenSync", || panic!("boom")).unwrap_err().reason, "[getScreenSync] INTERNAL_ERROR (43)"); + let mut job = Job("getScreen", Some(Box::new(|| panic!("boom")))); + assert_eq!(job.compute().unwrap_err().reason, "[getScreen] INTERNAL_ERROR (43)"); } #[test] fn no_display_fails_every_operation() { // SAFETY: tests touching DISPLAY run in this single test. + #[allow(unsafe_code)] unsafe { std::env::set_var("DISPLAY", ":4242") }; let ops: Vec<(&str, Res)> = vec![ ("screen", wm::screen()), diff --git a/native/src/wm.rs b/native/src/wm.rs index 9c23187..aab177b 100644 --- a/native/src/wm.rs +++ b/native/src/wm.rs @@ -1,5 +1,6 @@ //! EWMH window management spoken directly over the X11 protocol (x11rb): //! no libX11/libXmu at build or run time. +#![forbid(unsafe_code)] use std::{collections::HashMap, fmt, thread, time::Duration}; @@ -88,6 +89,8 @@ pub enum Fail { CanNotMoveResizeWindow = 27, NoWindowActiveForNow = 28, CanNotGetWindowAttributes = 36, + /// A panic, caught at the N-API boundary. + Internal = 43, } impl fmt::Display for Fail { @@ -101,6 +104,7 @@ impl fmt::Display for Fail { Fail::CanNotMoveResizeWindow => "CAN_NOT_MOVE_RESIZE_WINDOW", Fail::NoWindowActiveForNow => "NO_WINDOW_ACTIVE_FOR_NOW", Fail::CanNotGetWindowAttributes => "CAN_NOT_GET_WINDOW_ATTRIBUTES", + Fail::Internal => "INTERNAL_ERROR", }; write!(f, "{name} ({})", *self as i32) } @@ -177,10 +181,9 @@ fn text(r: Option<GetPropertyReply>) -> Option<String> { /// WM_CLASS "instance\0Class\0" -> "instance.Class". fn class(r: Option<GetPropertyReply>) -> Option<String> { let mut v = r?.value; - if let Some(i) = v.iter().position(|&c| c == 0) - && i + 1 < v.len() - { - v[i] = b'.'; + // The first NUL, unless it is the last byte. + if let Some(nul) = v.split_last_mut().and_then(|(_, init)| init.iter_mut().find(|c| **c == 0)) { + *nul = b'.'; } Some(cstr(&v)) } @@ -193,7 +196,7 @@ fn size_hints(r: Option<GetPropertyReply>) -> (u32, Value) { 15..18 => 255, _ => 1023, }; - let f = |i: usize| if supplied == 0 || (i >= 15 && supplied != 1023) { 0 } else { v[i] }; + let f = |i: usize| if supplied == 0 || (i >= 15 && supplied != 1023) { 0 } else { v.get(i).copied().unwrap_or(0) }; let hints = json!({ "flags": f(0) as u32 & supplied, "x": f(1), @@ -217,7 +220,7 @@ fn size_hints(r: Option<GetPropertyReply>) -> (u32, Value) { /// _NET_MOVERESIZE_WINDOW flags: gravity, plus one bit per value that is not -1 (untouched). fn moveresize_flags(grav: i32, xywh: [i32; 4]) -> u32 { - xywh.iter().enumerate().filter(|(_, v)| **v != -1).fold(grav as u32, |f, (i, _)| f | 1 << (8 + i)) + xywh.iter().zip([0x100, 0x200, 0x400, 0x800]).filter(|(v, _)| **v != -1).fold(grav as u32, |f, (_, bit)| f | bit) } /// Plain ConfigureWindow used when the WM lacks _NET_MOVERESIZE_WINDOW. @@ -232,22 +235,28 @@ fn fallback_geometry([x, y, w, h]: [i32; 4]) -> ConfigureWindowAux { aux } -/// Values a transition goes through from `from` to `to`, `pad` at a time. -1 never moves. -fn steps(from: i32, to: i32, pad: i32) -> Vec<i32> { - let mut v = vec![]; - let mut cur = from; - while to != -1 && cur != to { - cur = if cur < to { (cur + pad).min(to) } else { (cur - pad).max(to) }; - v.push(cur); - } - v +/// One step of `pad` from `cur` towards `to`, saturating instead of overflowing. +fn step(cur: i32, to: i32, pad: i32) -> i32 { + if cur < to { cur.saturating_add(pad).min(to) } else { cur.saturating_sub(pad).max(to) } } -/// Every (x, y, width, height) a transition requests; the last one is `to`. -fn transition(from: [i32; 4], to: [i32; 4], pad: i32) -> Vec<[i32; 4]> { - let paths: Vec<_> = (0..4).map(|i| steps(from[i], to[i], pad.max(1))).collect(); - let n = paths.iter().map(Vec::len).max().unwrap_or(0).max(1); - (0..n).map(|i| std::array::from_fn(|axis| paths[axis].get(i).copied().unwrap_or(to[axis]))).collect() +/// Every (x, y, width, height) a transition requests, `pad` at a time; the last one is `to`, and +/// there is at least one. -1 in `to` leaves a value untouched. Lazy: pad 1 to a far target is +/// billions of steps. +fn transition(from: [i32; 4], to: [i32; 4], pad: i32) -> impl Iterator<Item = [i32; 4]> { + let pad = pad.max(1); + let ([fx, fy, fw, fh], [tx, ty, tw, th]) = (from, to); + let mut axes = [(fx, tx), (fy, ty), (fw, tw), (fh, th)]; + let mut first = true; + std::iter::from_fn(move || { + let next = axes.map(|(c, t)| (if t == -1 { c } else { step(c, t, pad) }, t)); + if next == axes && !std::mem::take(&mut first) { + return None; + } + first = false; + axes = next; + Some(next.map(|(c, t)| if t == -1 { -1 } else { c })) + }) } /// _NET_WM_STATE action: REMOVE, ADD or TOGGLE. @@ -315,21 +324,24 @@ fn window_json( "wm_normal_hints_supplied": supplied, "wm_hints_supplied": 0, }); - if let Some((g, t)) = geo { - w["win_geometry"] = json!({ - "width": g.width, - "height": g.height, - "x": g.x, - "y": g.y, - "abs_x": t.dst_x, - "abs_y": t.dst_y, - }); - } - w["WM_NORMAL_HINTS"] = normal_hints; - // ponytail: WM_HINTS was always an empty XSizeHints in the C addon; kept for shape compatibility. - w["WM_HINTS"] = size_hints(None).1; - if let [left, right, top, bottom] = longs(extents)[..] { - w["frame_extents"] = json!({ "left": left, "right": right, "top": top, "bottom": bottom }); + if let Some(o) = w.as_object_mut() { + if let Some((g, t)) = geo { + let geometry = json!({ + "width": g.width, + "height": g.height, + "x": g.x, + "y": g.y, + "abs_x": t.dst_x, + "abs_y": t.dst_y, + }); + o.insert("win_geometry".into(), geometry); + } + o.insert("WM_NORMAL_HINTS".into(), normal_hints); + // ponytail: WM_HINTS was always an empty XSizeHints in the C addon; kept for shape compatibility. + o.insert("WM_HINTS".into(), size_hints(None).1); + if let [left, right, top, bottom] = longs(extents)[..] { + o.insert("frame_extents".into(), json!({ "left": left, "right": right, "top": top, "bottom": bottom })); + } } w } @@ -363,7 +375,7 @@ fn screen_json(s: &Screen) -> Value { impl X { fn open() -> Result<Self, Fail> { let (c, screen) = connect()?; - let root = c.setup().roots[screen].root; + let root = c.setup().roots.get(screen).ok_or(Fail::CanNotOpenDisplay)?.root; let names = TYPES.iter().chain(ACTIONS).chain(STATES); let a = Atoms::new(&c)?; let cookies = names @@ -494,7 +506,7 @@ impl X { pub fn screen() -> Res { let (c, n) = connect()?; - Ok(screen_json(&c.setup().roots[n])) + Ok(screen_json(c.setup().roots.get(n).ok_or(Fail::CanNotOpenDisplay)?)) } pub fn window(win: Window) -> Res { @@ -630,7 +642,7 @@ mod tests { /// Every known flag gets atom 1000 + its index in TYPES ++ ACTIONS ++ STATES. fn flags() -> Flags { - TYPES.iter().chain(ACTIONS).chain(STATES).enumerate().map(|(i, n)| (*n, 1000 + i as u32)).collect() + TYPES.iter().chain(ACTIONS).chain(STATES).zip(1000..).map(|(n, a)| (*n, a)).collect() } fn atom_of(name: &str) -> u32 { @@ -656,6 +668,7 @@ mod tests { (Fail::CanNotMoveResizeWindow, "CAN_NOT_MOVE_RESIZE_WINDOW (27)"), (Fail::NoWindowActiveForNow, "NO_WINDOW_ACTIVE_FOR_NOW (28)"), (Fail::CanNotGetWindowAttributes, "CAN_NOT_GET_WINDOW_ATTRIBUTES (36)"), + (Fail::Internal, "INTERNAL_ERROR (43)"), ]; for (fail, msg) in all { assert_eq!(fail.to_string(), msg); @@ -935,28 +948,31 @@ mod tests { } #[test] - fn steps_walk_towards_the_target() { - assert_eq!(steps(0, 10, 3), [3, 6, 9, 10]); - assert_eq!(steps(10, 0, 4), [6, 2, 0]); - assert_eq!(steps(5, 5, 1), Vec::<i32>::new()); - assert_eq!(steps(5, -1, 1), Vec::<i32>::new()); - assert_eq!(steps(0, 3, 100), [3]); - assert_eq!(steps(-30, -10, 10), [-20, -10]); + fn steps_walk_towards_the_target_without_overflowing() { + assert_eq!([step(0, 10, 3), step(9, 10, 3), step(10, 0, 4), step(5, 5, 1)], [3, 10, 6, 5]); + assert_eq!([step(0, 3, 100), step(-30, -10, 10)], [3, -20]); + assert_eq!(step(i32::MAX - 1, i32::MAX, i32::MAX), i32::MAX); + assert_eq!(step(i32::MIN + 1, i32::MIN, i32::MAX), i32::MIN); } #[test] fn transition_ends_on_the_target_and_holds_finished_axes() { - let t = transition([0, 0, 100, 100], [20, 10, 100, 120], 10); - assert_eq!(t, [[10, 10, 100, 110], [20, 10, 100, 120]]); - assert_eq!(transition([5, 5, 5, 5], [5, 5, 5, 5], 1), [[5, 5, 5, 5]]); - assert_eq!(transition([0, 0, 10, 10], [-1, -1, 12, -1], 1), [[-1, -1, 11, -1], [-1, -1, 12, -1]]); + let all = |from, to, pad| transition(from, to, pad).collect::<Vec<_>>(); + assert_eq!(all([0, 0, 100, 100], [20, 10, 100, 120], 10), [[10, 10, 100, 110], [20, 10, 100, 120]]); + assert_eq!(all([5, 5, 5, 5], [5, 5, 5, 5], 1), [[5, 5, 5, 5]]); + assert_eq!(all([0, 0, 10, 10], [-1, -1, 12, -1], 1), [[-1, -1, 11, -1], [-1, -1, 12, -1]]); + assert_eq!(all([0, 0, 0, 0], [-1, -1, -1, -1], 1), [[-1, -1, -1, -1]]); // pad <= 0 behaves like 1 instead of looping forever like the C addon. - assert_eq!(transition([0, 0, 0, 0], [2, 0, 0, 0], 0).len(), 2); - assert_eq!(transition([0, 0, 0, 0], [2, 0, 0, 0], -5).len(), 2); - let long = transition([0, 0, 50, 50], [1000, 500, 800, 600], 7); + assert_eq!(all([0, 0, 0, 0], [2, 0, 0, 0], 0).len(), 2); + assert_eq!(all([0, 0, 0, 0], [2, 0, 0, 0], -5).len(), 2); + let long = all([0, 0, 50, 50], [1000, 500, 800, 600], 7); assert_eq!(long.len(), 143); assert_eq!(*long.last().unwrap(), [1000, 500, 800, 600]); assert!(long.windows(2).all(|p| (0..4).all(|i| p[1][i] >= p[0][i]))); + // Extreme values neither overflow nor allocate every step up front. + assert_eq!(all([i32::MIN, 0, 0, 0], [i32::MAX, 0, 0, 0], i32::MAX).len(), 3); + let far: Vec<_> = transition([0, 0, 0, 0], [i32::MAX, 0, 0, 0], 1).take(2).collect(); + assert_eq!(far, [[1, 0, 0, 0], [2, 0, 0, 0]]); } #[test] @@ -968,7 +984,7 @@ mod tests { assert_eq!(state_action(""), None); assert_eq!(state_atom_name("maximized_vert"), "_NET_WM_STATE_MAXIMIZED_VERT"); for s in STATES { - assert_eq!(state_atom_name(&s["_NET_WM_STATE_".len()..].to_lowercase()), *s); + assert_eq!(state_atom_name(&s.strip_prefix("_NET_WM_STATE_").unwrap().to_lowercase()), *s); } } } From 05eacf9a2105516c326efedfd09b52025e0a1b0f Mon Sep 17 00:00:00 2001 From: kecsou <kevin.voyer.developpeur@gmail.com> Date: Sat, 31 Oct 2026 17:47:01 +0100 Subject: [PATCH 4/5] Wait for the screen 1 WM before the X11 tests X has one input focus per display, and openbox takes it when it starts managing screen 1. Under QEMU in CI it came up in the middle of the activation tests and left screen 0 without an active window ("activating a minimized window restores it" timed out on ppc64le). The setup hook now waits for both WMs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/test/x11.test.ts | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/test/x11.test.ts b/src/test/x11.test.ts index e501409..09d911f 100644 --- a/src/test/x11.test.ts +++ b/src/test/x11.test.ts @@ -60,8 +60,24 @@ const geometry = (id:number) => wm.getWindowByIdSync(id).win_geometry!; const active = () => { try { return wm.getActiveWindowSync().win_id; } catch { return 0; } }; const MISSING = 1; // never a client window id: X servers hand out ids from 0x200000 -// The WM publishes _NET_CLIENT_LIST once it manages the screen; it starts slowly under emulation. -before(() => skip || waitFor(() => { try { return wm.getWindowListSync(); } catch { return false; } }, 60000)); +// A WM publishes _NET_CLIENT_LIST once it manages its screen; it starts slowly under emulation. +const wmReady = () => { try { return wm.getWindowListSync(); } catch { return false; } }; +before(async () => { + if (skip) + return; + await waitFor(wmReady, 60000); + if (skipScreen1) + return; + // X has one input focus per display: the screen 1 WM takes it when it starts, so it must be up + // before any test that expects a window of screen 0 to stay active. + const display = process.env.DISPLAY; + process.env.DISPLAY = process.env.WMCTRLJS_SCREEN1; + try { + await waitFor(wmReady, 60000); + } finally { + process.env.DISPLAY = display; + } +}); after(() => spawned.forEach(p => p.kill())); describe("X11", { skip }, () => { From c49f1664c2fc6bb67c83198680c67c714e1202be Mon Sep 17 00:00:00 2001 From: kecsou <kevin.voyer.developpeur@gmail.com> Date: Sat, 31 Oct 2026 21:46:53 +0100 Subject: [PATCH 5/5] Stop the FreeBSD CI step from hanging after its tests Xvfb and openbox ran in the background with the ssh session's output, so the session stayed open after the tests passed and the step never ended. Jobs now also time out after 30 minutes, and a new push to a PR cancels its older runs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .github/workflows/ci.yml | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 710aa20..5828192 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,6 +6,11 @@ on: tags: ["v*"] pull_request: +# A new push to a PR supersedes its running checks. +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + jobs: # TypeScript 7's compiler is not built for every target: compile once, test everywhere. dist: @@ -31,6 +36,7 @@ jobs: linux: needs: dist runs-on: ${{ matrix.runner || 'ubuntu-24.04' }} + timeout-minutes: 30 strategy: fail-fast: false matrix: @@ -79,6 +85,7 @@ jobs: freebsd: needs: dist runs-on: ubuntu-24.04 + timeout-minutes: 30 steps: - uses: actions/checkout@v7 - uses: actions/download-artifact@v8 @@ -92,9 +99,10 @@ jobs: run: | set -e node scripts/build-native.js - Xvfb :99 -screen 0 1280x1024x24 -screen 1 800x600x24 -nolisten tcp & sleep 2 - DISPLAY=:99 openbox & - DISPLAY=:99.1 openbox & + # Detached from the ssh session's output, or it stays open after the tests and the step never ends. + Xvfb :99 -screen 0 1280x1024x24 -screen 1 800x600x24 -nolisten tcp </dev/null >/dev/null 2>&1 & sleep 2 + DISPLAY=:99 openbox </dev/null >/dev/null 2>&1 & + DISPLAY=:99.1 openbox </dev/null >/dev/null 2>&1 & DISPLAY=:99 WMCTRLJS_SCREEN1=:99.1 WMCTRLJS_FIXTURE=fixtures/freebsd-x64/fixture node --test dist/test/*.test.js - uses: actions/upload-artifact@v7 with: @@ -105,6 +113,7 @@ jobs: others: needs: dist runs-on: ${{ matrix.runner }} + timeout-minutes: 30 strategy: fail-fast: false matrix: